'use client';
import {
  Bar, BarChart, CartesianGrid, Cell, ComposedChart, Line, ReferenceLine, ResponsiveContainer, Scatter, Tooltip, XAxis, YAxis,
} from 'recharts';
import type { Entry, TrendPoint } from '@/lib/stats';
import { kg, int, dateShort, dateMid } from '@/lib/format';

const AXIS = { fill: '#9a9c93', fontSize: 12 };
const GRID = '#2e302a';
const ACCENT = '#c8f031';
const MUTED = '#4a4c45';
const BAD = '#ff6b5a';

type Row = { label: string; value: string };
function Tip({ title, rows }: { title: string; rows: Row[] }) {
  return (
    <div className="tip">
      <div>{title}</div>
      {rows.map((r) => (
        <div key={r.label}>
          <span className="t">{r.label} </span>
          {r.value}
        </div>
      ))}
    </div>
  );
}

// recharts ipucu bileşeninin aldığı alanlar
type TipProps = { active?: boolean; payload?: readonly { payload?: unknown }[] };

export function WeightChart({ data }: { data: TrendPoint[] }) {
  const vals = data.flatMap((d) => [d.weight, d.avg7, d.plan]).filter((v): v is number => v !== null);
  const lo = Math.floor(Math.min(...vals) - 0.5);
  const hi = Math.ceil(Math.max(...vals) + 0.5);
  return (
    <div className="chart" role="img" aria-label="Günlük kilo, 7 günlük ortalama ve plan çizgisi">
      <ResponsiveContainer>
        <ComposedChart data={data} margin={{ top: 8, right: 12, bottom: 0, left: 0 }}>
          <CartesianGrid stroke={GRID} vertical={false} />
          <XAxis dataKey="day" tickFormatter={dateShort} tick={AXIS} axisLine={{ stroke: GRID }} tickLine={false} minTickGap={24} />
          <YAxis domain={[lo, hi]} tickFormatter={(v: number) => kg(v)} tick={AXIS} axisLine={false} tickLine={false} width={48} />
          <Tooltip
            cursor={{ stroke: '#6e7068' }}
            content={({ active, payload }: TipProps) => {
              if (!active || !payload?.length) return null;
              const d = payload[0].payload as unknown as TrendPoint;
              return (
                <Tip
                  title={dateMid(d.day)}
                  rows={[
                    { label: 'Tartı', value: d.weight === null ? '—' : `${kg(d.weight)} kg` },
                    { label: '7 gün ort.', value: d.avg7 === null ? '—' : `${kg(d.avg7)} kg` },
                    { label: 'Plan', value: d.plan === null ? '—' : `${kg(d.plan)} kg` },
                  ]}
                />
              );
            }}
          />
          <Line dataKey="plan" stroke="#6e7068" strokeDasharray="4 4" strokeWidth={1.5} dot={false} isAnimationActive={false} connectNulls />
          <Scatter dataKey="weight" fill={ACCENT} fillOpacity={0.35} isAnimationActive={false} />
          <Line dataKey="avg7" stroke={ACCENT} strokeWidth={2.5} dot={false} type="linear" isAnimationActive={false} connectNulls />
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  );
}

export function GoalBarChart({
  data, field, goal, mode, unit, label,
}: { data: Entry[]; field: 'steps' | 'calories'; goal: number | null; mode: 'min' | 'max'; unit: string; label: string }) {
  const color = (v: number | null) => {
    if (v === null || !goal) return ACCENT;
    if (mode === 'min') return v >= goal ? ACCENT : MUTED;
    return v > goal ? BAD : ACCENT;
  };
  return (
    <div className="chart" style={{ height: 230 }} role="img" aria-label={label}>
      <ResponsiveContainer>
        <BarChart data={data} margin={{ top: 8, right: goal ? 84 : 12, bottom: 0, left: 0 }}>
          <CartesianGrid stroke={GRID} vertical={false} />
          <XAxis dataKey="day" tickFormatter={dateShort} tick={AXIS} axisLine={{ stroke: GRID }} tickLine={false} minTickGap={24} />
          <YAxis tickFormatter={(v: number) => int(v)} tick={AXIS} axisLine={false} tickLine={false} width={52} />
          <Tooltip
            cursor={{ fill: 'rgba(255,255,255,0.04)' }}
            content={({ active, payload }: TipProps) => {
              if (!active || !payload?.length) return null;
              const d = payload[0].payload as unknown as Entry;
              const v = d[field];
              let status = '';
              if (v !== null && goal) {
                if (mode === 'min') status = v >= goal ? 'Hedef tuttu' : `Hedefe ${int(goal - v)} eksik`;
                else status = v > goal ? `${int(v - goal)} ${unit} fazla` : `${int(goal - v)} ${unit} altında`;
              }
              return <Tip title={dateMid(d.day)} rows={[{ label: unit === 'adım' ? 'Adım' : 'Kalori', value: v === null ? '—' : `${int(v)} ${unit}` }, ...(status ? [{ label: '', value: status }] : [])]} />;
            }}
          />
          {goal && <ReferenceLine y={goal} stroke="#9a9c93" strokeDasharray="4 4" label={{ value: `Hedef ${int(goal)}`, position: 'right', fill: '#9a9c93', fontSize: 12 }} />}
          <Bar dataKey={field} radius={[3, 3, 0, 0]} isAnimationActive={false}>
            {data.map((d) => (
              <Cell key={d.day} fill={color(d[field])} />
            ))}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

export function MacroChart({ data }: { data: Entry[] }) {
  const rows = data.map((d) => ({
    ...d,
    pk: (d.protein ?? 0) * 4,
    fk: (d.fat ?? 0) * 9,
    ck: (d.carbs ?? 0) * 4,
  }));
  const g = (v: number | null) => (v === null ? '—' : `${int(v)} g`);
  return (
    <div className="chart" style={{ height: 230 }} role="img" aria-label="Protein, yağ ve karbonhidratın günlük kaloriye katkısı">
      <ResponsiveContainer>
        <BarChart data={rows} margin={{ top: 8, right: 12, bottom: 0, left: 0 }}>
          <CartesianGrid stroke={GRID} vertical={false} />
          <XAxis dataKey="day" tickFormatter={dateShort} tick={AXIS} axisLine={{ stroke: GRID }} tickLine={false} minTickGap={24} />
          <YAxis tickFormatter={(v: number) => int(v)} tick={AXIS} axisLine={false} tickLine={false} width={52} />
          <Tooltip
            cursor={{ fill: 'rgba(255,255,255,0.04)' }}
            content={({ active, payload }: TipProps) => {
              if (!active || !payload?.length) return null;
              const d = payload[0].payload as unknown as (typeof rows)[number];
              return (
                <Tip
                  title={dateMid(d.day)}
                  rows={[
                    { label: 'Protein', value: g(d.protein) },
                    { label: 'Yağ', value: g(d.fat) },
                    { label: 'Karbonhidrat', value: g(d.carbs) },
                    { label: 'Makrolardan', value: `${int(d.pk + d.fk + d.ck)} kcal` },
                  ]}
                />
              );
            }}
          />
          <Bar dataKey="pk" stackId="m" fill="var(--protein)" isAnimationActive={false} />
          <Bar dataKey="fk" stackId="m" fill="var(--fat)" isAnimationActive={false} />
          <Bar dataKey="ck" stackId="m" fill="var(--carbs)" radius={[3, 3, 0, 0]} isAnimationActive={false} />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}
