import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import { useProfile } from '../../context/ProfileContext'
import { getBfCategory } from '../../utils/calc'
import { StatCard } from '../DashboardStatKit'
import { dashboardStatGridClassName, DASHBOARD_TILE_GRID_COLS } from '../../utils/dashboardLayout'

export default function BodyStatStripWidget({ refreshTick = 0 }) {
  const nav = useNavigate()
  const { activeProfile } = useProfile()
  const sex = activeProfile?.sex || 'm'
  const [weights, setWeights] = useState([])
  const [calipers, setCalipers] = useState([])
  const [nutrition, setNutrition] = useState([])

  useEffect(() => {
    Promise.all([api.listWeight(60), api.listCaliper(3), api.listNutrition(30)])
      .then(([w, ca, n]) => {
        setWeights(w)
        setCalipers(ca)
        setNutrition(n)
      })
      .catch(() => {
        setWeights([])
        setCalipers([])
        setNutrition([])
      })
  }, [refreshTick])

  const latestW = weights[0]
  const prevW = weights[1]
  const latestCal = calipers[0]
  const wDelta = latestW && prevW ? Math.round((latestW.weight - prevW.weight) * 10) / 10 : null
  const bfCat = latestCal?.body_fat_pct ? getBfCategory(latestCal.body_fat_pct, sex) : null
  const bfPrev = calipers[1]?.body_fat_pct
  const bfDelta =
    latestCal?.body_fat_pct && bfPrev ? Math.round((latestCal.body_fat_pct - bfPrev) * 10) / 10 : null

  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

  if (!latestW && !latestCal?.body_fat_pct && !avgKcal) {
    return (
      <div className="card section-gap" style={{ marginBottom: 16, fontSize: 13, color: 'var(--text3)' }}>
        Noch keine Kennzahlen – erfasse Gewicht oder Körperdaten.
      </div>
    )
  }

  return (
    <div className="card section-gap" style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 10, color: 'var(--text1)' }}>Kennzahlen</div>
      <div className={dashboardStatGridClassName(DASHBOARD_TILE_GRID_COLS.mobile)}>
        {latestW && (
          <StatCard
            icon="⚖️"
            label="Gewicht"
            value={latestW.weight}
            unit="kg"
            delta={wDelta}
            deltaGoodWhenNeg
            sub={dayjs(latestW.date).format('DD.MM.')}
            onClick={() => nav('/history')}
            color="#378ADD"
          />
        )}
        {latestCal?.body_fat_pct != null && (
          <StatCard
            icon="🫧"
            label="Körperfett"
            value={latestCal.body_fat_pct}
            unit="%"
            delta={bfDelta}
            deltaGoodWhenNeg
            sub={bfCat?.label}
            onClick={() => nav('/history', { state: { tab: 'body' } })}
            color={bfCat?.color}
          />
        )}
        {latestCal?.lean_mass != null && (
          <StatCard
            icon="💪"
            label="Magermasse"
            value={latestCal.lean_mass}
            unit="kg"
            sub={latestCal.date ? dayjs(latestCal.date).format('DD.MM.') : '–'}
            onClick={() => nav('/history', { state: { tab: 'body' } })}
          />
        )}
        {avgKcal != null && (
          <StatCard
            icon="🍽️"
            label="Ø Kalorien"
            value={avgKcal}
            unit="kcal"
            sub="letzte 7 Tage"
            onClick={() => nav('/history', { state: { tab: 'nutrition' } })}
            color="#EF9F27"
          />
        )}
      </div>
    </div>
  )
}
