import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import {
  dashboardTileGridClassName,
  DASHBOARD_TILE_GRID_COLS,
} from '../../utils/dashboardLayout'
import DashboardTile from '../DashboardTile'

export default function NutritionActivitySummaryWidget({ refreshTick = 0 }) {
  const nav = useNavigate()
  const [nutrition, setNutrition] = useState([])
  const [activities, setActivities] = useState([])
  const [latestWeight, setLatestWeight] = useState(null)

  useEffect(() => {
    Promise.all([api.listNutrition(30), api.listActivity(800, 30), api.listWeight(1)])
      .then(([n, a, w]) => {
        setNutrition(n)
        setActivities(a)
        setLatestWeight(w?.[0]?.weight ?? null)
      })
      .catch(() => {
        setNutrition([])
        setActivities([])
        setLatestWeight(null)
      })
  }, [refreshTick])

  const recentNutr = nutrition.filter((n) => n.date >= dayjs().subtract(7, 'day').format('YYYY-MM-DD'))
  const avgKcal = recentNutr.length
    ? Math.round(recentNutr.reduce((s, n) => s + (n.kcal || 0), 0) / recentNutr.length)
    : null
  const avgProtein = recentNutr.length
    ? Math.round(recentNutr.reduce((s, n) => s + (n.protein_g || 0), 0) / recentNutr.length * 10) / 10
    : null
  const ptLow = Math.round((latestWeight || 80) * 1.6)
  const proteinOk = avgProtein && avgProtein >= ptLow

  const recentAct = activities.filter((a) => a.date >= dayjs().subtract(7, 'day').format('YYYY-MM-DD'))
  const actKcal = recentAct.length ? Math.round(recentAct.reduce((s, a) => s + (a.kcal_active || 0), 0)) : null

  const showNutr = !!(avgKcal || avgProtein)
  const showAct = actKcal != null
  if (!showNutr && !showAct) {
    return (
      <div className="card section-gap" style={{ marginBottom: 16, fontSize: 13, color: 'var(--text3)' }}>
        Noch keine Ernährungs- oder Aktivitätsdaten (7 Tage).
      </div>
    )
  }

  const summaryBoth = showNutr && showAct
  const summarySpanM = summaryBoth ? 1 : 2
  const summarySpanD = summaryBoth ? 2 : 4

  return (
    <div className="card section-gap" style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 10, color: 'var(--text1)' }}>
        Ernährung &amp; Aktivität
      </div>
      <div className={`dashboard-summary-row ${dashboardTileGridClassName(DASHBOARD_TILE_GRID_COLS.mobile)}`}>
        {showNutr && (
          <DashboardTile spanMobile={summarySpanM} spanDesktop={summarySpanD}>
            <div
              className="card"
              style={{ cursor: 'pointer', height: '100%' }}
              role="button"
              tabIndex={0}
              onKeyDown={(e) => e.key === 'Enter' && nav('/history', { state: { tab: 'nutrition' } })}
              onClick={() => nav('/history', { state: { tab: 'nutrition' } })}
            >
              <div style={{ fontWeight: 600, fontSize: 12, marginBottom: 8, color: 'var(--text3)' }}>
                🍽️ ERNÄHRUNG (Ø 7T)
              </div>
              {avgKcal != null && <div style={{ fontSize: 16, fontWeight: 700, color: '#EF9F27' }}>{avgKcal} kcal</div>}
              {avgProtein != null && (
                <div
                  style={{
                    fontSize: 13,
                    fontWeight: 600,
                    color: proteinOk ? 'var(--accent)' : 'var(--warn)',
                  }}
                >
                  {avgProtein}g Protein {proteinOk ? '✓' : '⚠️'}
                </div>
              )}
              <div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 4 }}>→ Verlauf Ernährung</div>
            </div>
          </DashboardTile>
        )}
        {showAct && (
          <DashboardTile spanMobile={summarySpanM} spanDesktop={summarySpanD}>
            <div
              className="card"
              style={{ cursor: 'pointer', height: '100%' }}
              role="button"
              tabIndex={0}
              onKeyDown={(e) => e.key === 'Enter' && nav('/history', { state: { tab: 'activity' } })}
              onClick={() => nav('/history', { state: { tab: 'activity' } })}
            >
              <div style={{ fontWeight: 600, fontSize: 12, marginBottom: 8, color: 'var(--text3)' }}>
                🏋️ AKTIVITÄT (7T)
              </div>
              <div style={{ fontSize: 16, fontWeight: 700, color: '#EF9F27' }}>{actKcal} kcal</div>
              <div style={{ fontSize: 13, color: 'var(--text2)' }}>{recentAct.length} Trainings</div>
              <div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 4 }}>→ Verlauf Aktivität</div>
            </div>
          </DashboardTile>
        )}
      </div>
    </div>
  )
}
