import { useEffect, useState } from 'react'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import { useProfile } from '../../context/ProfileContext'
import { getBfCategory } from '../../utils/calc'
import { Pill } from '../DashboardStatKit'

/** WHR, WHtR, Protein Ø7T, KF – wie Dashboard-Pill-Leiste */
export default function StatusPillsWidget({ refreshTick = 0 }) {
  const { activeProfile } = useProfile()
  const sex = activeProfile?.sex || 'm'
  const height = activeProfile?.height || 178
  const [weights, setWeights] = useState([])
  const [calipers, setCalipers] = useState([])
  const [circs, setCircs] = useState([])
  const [nutrition, setNutrition] = useState([])

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

  const latestCal = calipers[0]
  const latestCir = circs[0]
  const latestW = weights[0]

  const recentNutr = nutrition.filter((n) => n.date >= dayjs().subtract(7, 'day').format('YYYY-MM-DD'))
  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((latestW?.weight || 80) * 1.6)
  const proteinOk = avgProtein && avgProtein >= ptLow

  const whr =
    latestCir?.c_waist && latestCir?.c_hip
      ? Math.round((latestCir.c_waist / latestCir.c_hip) * 100) / 100
      : null
  const whtr =
    latestCir?.c_waist && height ? Math.round((latestCir.c_waist / height) * 100) / 100 : null
  const bfCat = latestCal?.body_fat_pct ? getBfCategory(latestCal.body_fat_pct, sex) : null

  const pills = []
  if (whr)
    pills.push({
      label: 'WHR',
      value: whr,
      status: whr < (sex === 'm' ? 0.9 : 0.85) ? 'good' : 'warn',
      sub: `<${sex === 'm' ? '0,90' : '0,85'}`,
    })
  if (whtr) pills.push({ label: 'WHtR', value: whtr, status: whtr < 0.5 ? 'good' : 'warn', sub: '<0,50' })
  if (avgProtein)
    pills.push({
      label: 'Protein Ø7T',
      value: `${avgProtein}g`,
      status: proteinOk ? 'good' : 'warn',
      sub: `Ziel ${ptLow}g`,
    })
  if (bfCat && latestCal?.body_fat_pct != null)
    pills.push({
      label: 'KF',
      value: `${latestCal.body_fat_pct}%`,
      status: latestCal.body_fat_pct < (sex === 'm' ? 18 : 25) ? 'good' : 'warn',
      sub: bfCat.label,
    })

  if (pills.length === 0) return null

  return (
    <div className="card section-gap" style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text3)', marginBottom: 8 }}>Indikatoren</div>
      <div className="dashboard-pill-row">
        {pills.map((p, i) => (
          <Pill key={i} {...p} />
        ))}
      </div>
    </div>
  )
}
