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

/** Profil-Ziele Gewicht / Körperfett (Balken wie Dashboard) */
export default function ProfileGoalsProgressWidget({ refreshTick = 0 }) {
  const { activeProfile } = useProfile()
  const sex = activeProfile?.sex || 'm'
  const [weights, setWeights] = useState([])
  const [calipers, setCalipers] = useState([])

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

  const latestW = weights[0]
  const latestCal = calipers[0]
  const bfCat = latestCal?.body_fat_pct ? getBfCategory(latestCal.body_fat_pct, sex) : null

  const gw = activeProfile?.goal_weight
  const gbf = activeProfile?.goal_bf_pct
  if ((!gw || !latestW) && (!gbf || latestCal?.body_fat_pct == null)) return null

  return (
    <div className="card section-gap" style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 10, color: 'var(--text1)' }}>Profil-Ziele</div>
      {gw && latestW && (
        <div style={{ marginBottom: 10 }}>
          {(() => {
            const start = Math.max(...weights.map((w) => w.weight))
            const curr = latestW.weight
            const goal = gw
            const total = start - goal
            const done = start - curr
            const pct = total > 0 ? Math.min(100, Math.round((done / total) * 100)) : 100
            const remain = Math.round((curr - goal) * 10) / 10
            return (
              <>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
                  <span>
                    Gewicht: {curr} → {goal} kg
                  </span>
                  <span style={{ color: 'var(--accent)', fontWeight: 600 }}>
                    {remain > 0 ? `noch ${remain}kg` : 'Ziel erreicht! 🎉'}
                  </span>
                </div>
                <div style={{ height: 8, background: 'var(--border)', borderRadius: 4, overflow: 'hidden' }}>
                  <div
                    style={{
                      height: '100%',
                      width: `${pct}%`,
                      background: 'var(--accent)',
                      borderRadius: 4,
                      transition: 'width 0.5s',
                    }}
                  />
                </div>
                <div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 2 }}>{pct}% des Weges</div>
              </>
            )
          })()}
        </div>
      )}
      {gbf && latestCal?.body_fat_pct != null && (
        <div>
          {(() => {
            const curr = latestCal.body_fat_pct
            const goal = gbf
            const remain = Math.round((curr - goal) * 10) / 10
            const pct =
              curr <= goal ? 100 : Math.min(100, Math.round((1 - (curr - goal) / Math.max(curr - goal, 5)) * 100))
            return (
              <>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
                  <span>
                    Körperfett: {curr}% → {goal}%
                  </span>
                  <span style={{ color: 'var(--accent)', fontWeight: 600 }}>
                    {remain > 0 ? `noch ${remain}%` : 'Ziel erreicht! 🎉'}
                  </span>
                </div>
                <div style={{ height: 8, background: 'var(--border)', borderRadius: 4, overflow: 'hidden' }}>
                  <div
                    style={{
                      height: '100%',
                      width: `${pct}%`,
                      background: bfCat?.color || 'var(--accent)',
                      borderRadius: 4,
                    }}
                  />
                </div>
                <div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 2 }}>Aktuell: {bfCat?.label}</div>
              </>
            )
          })()}
        </div>
      )}
    </div>
  )
}
