import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
  CartesianGrid,
  ReferenceLine,
} from 'recharts'
import { ChevronRight } from 'lucide-react'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import { useProfile } from '../../context/ProfileContext'
import { getInterpretation } from '../../utils/interpret'
import { rollingAvg, fmtDate } from '../../pilot/pilotChartUtils'
import {
  BODY_CHART_DAYS_DEFAULT,
  normalizeBodyChartDays,
} from '../../widgetSystem/bodyChartDays'
import PilotRuleCard from './PilotRuleCard'

export default function PilotBodySection({ refreshTick = 0, chartDays = BODY_CHART_DAYS_DEFAULT }) {
  const windowDays = normalizeBodyChartDays(chartDays)
  const { activeProfile } = useProfile()
  const [weights, setWeights] = useState([])
  const [calipers, setCalipers] = useState([])
  const [circs, setCircs] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      try {
        const fetchDays = Math.max(120, windowDays + 60)
        const [w, ca, ci] = await Promise.all([
          api.listWeight(fetchDays),
          api.listCaliper(Math.max(30, windowDays)),
          api.listCirc(Math.max(30, windowDays)),
        ])
        if (!cancelled) {
          setWeights(Array.isArray(w) ? w : [])
          setCalipers(Array.isArray(ca) ? ca : [])
          setCircs(Array.isArray(ci) ? ci : [])
        }
      } catch {
        if (!cancelled) {
          setWeights([])
          setCalipers([])
          setCircs([])
        }
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [refreshTick, windowDays])

  const cutoff = dayjs().subtract(windowDays, 'day').format('YYYY-MM-DD')

  const filtW = [...(weights || [])]
    .sort((a, b) => a.date.localeCompare(b.date))
    .filter((d) => d.date >= cutoff)
  const filtCal = (calipers || []).filter((d) => d.date >= cutoff)
  const filtCir = (circs || []).filter((d) => d.date >= cutoff)

  const hasWeight = filtW.length >= 2
  const latestCal = filtCal[0]
  const prevCal = filtCal[1]
  const latestCir = filtCir[0]
  const latestW2 = filtW[filtW.length - 1]

  const withAvg = rollingAvg(filtW, 'weight', 7)
  const withAvg14 = rollingAvg(filtW, 'weight', 14)
  const wCd = withAvg.map((d, i) => ({
    date: fmtDate(d.date),
    weight: d.weight,
    avg7: d.weight_avg,
    avg14: withAvg14[i]?.weight_avg,
  }))
  const ws = filtW.map((w) => w.weight)
  const avgAll = ws.length ? Math.round((ws.reduce((a, b) => a + b, 0) / ws.length) * 10) / 10 : null

  const combined = {
    ...(latestCal || {}),
    c_waist: latestCir?.c_waist,
    c_hip: latestCir?.c_hip,
    weight: latestW2?.weight,
  }
  const rules = getInterpretation(combined, activeProfile || {}, prevCal || null)

  if (loading) {
    return (
      <div className="card section-gap" style={{ textAlign: 'center', padding: 24 }}>
        <div className="spinner" />
      </div>
    )
  }

  return (
    <div className="section-gap" style={{ marginBottom: 24 }}>
      <div
        style={{
          gridColumn: '1 / -1',
          marginBottom: 12,
          paddingBottom: 8,
          borderBottom: '2px solid var(--border)',
        }}
      >
        <h2 style={{ fontSize: 17, fontWeight: 700, margin: 0, color: 'var(--text1)' }}>Bereich Körper</h2>
        <p style={{ fontSize: 12, color: 'var(--text2)', margin: '6px 0 0', lineHeight: 1.5 }}>
          Fokus letzte {windowDays} Tage · Gewicht mit Ø 7 / Ø 14 Tage wie im Verlauf
        </p>
      </div>

      {!hasWeight && (
        <div className="card" style={{ padding: 20, fontSize: 13, color: 'var(--text2)' }}>
          Zu wenig Gewichtsdaten für den Graph.{' '}
          <Link to="/weight" style={{ color: 'var(--accent)' }}>
            Gewicht erfassen
          </Link>
        </div>
      )}

      {hasWeight && (
        <div className="card section-gap">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text3)' }}>
              Gewicht · {filtW.length} Messungen ({windowDays}T)
            </div>
            <Link to="/history" state={{ tab: 'body' }} className="btn btn-secondary" style={{ fontSize: 10, padding: '2px 8px', textDecoration: 'none' }}>
              Verlauf Körper <ChevronRight size={10} />
            </Link>
          </div>
          <ResponsiveContainer width="100%" height={200}>
            <LineChart data={wCd} margin={{ top: 4, right: 8, bottom: 0, left: -20 }}>
              <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" />
              <XAxis
                dataKey="date"
                tick={{ fontSize: 9, fill: 'var(--text3)' }}
                tickLine={false}
                interval={Math.max(0, Math.floor(wCd.length / 6) - 1)}
              />
              <YAxis tick={{ fontSize: 9, fill: 'var(--text3)' }} tickLine={false} domain={['auto', 'auto']} />
              {avgAll && (
                <ReferenceLine
                  y={avgAll}
                  stroke="var(--text3)"
                  strokeDasharray="4 4"
                  strokeWidth={1}
                  label={{ value: `Ø ${avgAll}`, fontSize: 9, fill: 'var(--text3)', position: 'right' }}
                />
              )}
              {activeProfile?.goal_weight && (
                <ReferenceLine
                  y={activeProfile.goal_weight}
                  stroke="var(--accent)"
                  strokeDasharray="5 3"
                  strokeWidth={1.5}
                  label={{
                    value: `Ziel ${activeProfile.goal_weight}kg`,
                    fontSize: 9,
                    fill: 'var(--accent)',
                    position: 'right',
                  }}
                />
              )}
              <Tooltip
                contentStyle={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 11 }}
                formatter={(v, n) => [
                  `${v} kg`,
                  n === 'weight' ? 'Täglich' : n === 'avg7' ? 'Ø 7 Tage' : 'Ø 14 Tage',
                ]}
              />
              <Line type="monotone" dataKey="weight" stroke="#378ADD88" strokeWidth={1.5} dot={{ r: 3, fill: '#378ADD' }} name="weight" />
              <Line type="monotone" dataKey="avg7" stroke="#378ADD" strokeWidth={2.5} dot={false} name="avg7" />
              <Line type="monotone" dataKey="avg14" stroke="#1D9E75" strokeWidth={2} dot={false} strokeDasharray="6 3" name="avg14" />
            </LineChart>
          </ResponsiveContainer>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 6, fontSize: 10, color: 'var(--text3)', flexWrap: 'wrap' }}>
            <span>
              <span style={{ display: 'inline-block', width: 12, height: 2, background: '#378ADD88', verticalAlign: 'middle', marginRight: 3 }} />
              Täglich
            </span>
            <span>
              <span style={{ display: 'inline-block', width: 12, height: 2, background: '#378ADD', verticalAlign: 'middle', marginRight: 3 }} />
              Ø 7T
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
              <svg width="14" height="4">
                <line x1="0" y1="2" x2="14" y2="2" stroke="#1D9E75" strokeWidth="2" strokeDasharray="5 3" />
              </svg>
              Ø 14T
            </span>
            <span>
              <span
                style={{
                  display: 'inline-block',
                  width: 12,
                  height: 2,
                  background: 'var(--text3)',
                  verticalAlign: 'middle',
                  marginRight: 3,
                  borderTop: '2px dashed',
                }}
              />
              Ø Zeitraum
            </span>
          </div>
        </div>
      )}

      {rules.length > 0 && (
        <div className="card section-gap">
          <div className="card-title">Bewertung · Körper</div>
          <p style={{ fontSize: 12, color: 'var(--text2)', marginTop: 4, marginBottom: 10, lineHeight: 1.5 }}>
            Körperfett, Magermasse (FFMI), BMI – gleiche Logik wie auf der Verlauf-Seite (Körper).
          </p>
          {rules.map((item, i) => (
            <PilotRuleCard key={i} item={item} />
          ))}
        </div>
      )}
    </div>
  )
}
