// ── Stats Page ────────────────────────────────────────────────────────────────

function MiniBar({ value, max, color = "#2d7a3a" }) {
  const pct = max > 0 ? (value / max) * 100 : 0;
  return (
    <div className="flex-1 bg-gray-100 rounded-full h-2 overflow-hidden">
      <div
        className="h-2 rounded-full"
        style={{ width: `${pct}%`, backgroundColor: color }}
      />
    </div>
  );
}

function StatCard({ label, value }) {
  return (
    <div className="bg-white rounded-xl shadow-sm p-4 flex flex-col gap-1">
      <span className="text-xs text-gray-500 uppercase tracking-wide">
        {label}
      </span>
      <span className="text-xl font-bold text-gray-800">{value}</span>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div className="bg-white rounded-xl shadow-sm p-4">
      <h2 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
        {title}
      </h2>
      {children}
    </div>
  );
}

function ChainPieChart({ data }) {
  const size = 180;
  const cx = size / 2;
  const cy = size / 2;
  const r = 70;
  const innerR = 36;

  let cumAngle = -Math.PI / 2;
  const slices = data.map((d) => {
    const angle = (d.pct / 100) * 2 * Math.PI;
    const start = cumAngle;
    cumAngle += angle;
    return { ...d, start, end: cumAngle, angle };
  });

  function arcPath(start, end, outerR, innerR) {
    const large = end - start > Math.PI ? 1 : 0;
    const x1 = cx + outerR * Math.cos(start);
    const y1 = cy + outerR * Math.sin(start);
    const x2 = cx + outerR * Math.cos(end);
    const y2 = cy + outerR * Math.sin(end);
    const x3 = cx + innerR * Math.cos(end);
    const y3 = cy + innerR * Math.sin(end);
    const x4 = cx + innerR * Math.cos(start);
    const y4 = cy + innerR * Math.sin(start);
    return `M${x1},${y1} A${outerR},${outerR} 0 ${large},1 ${x2},${y2} L${x3},${y3} A${innerR},${innerR} 0 ${large},0 ${x4},${y4} Z`;
  }

  return (
    <div className="flex flex-col sm:flex-row items-center gap-4">
      <svg width={size} height={size} className="shrink-0">
        {slices.map((s) => (
          <path
            key={s.chain}
            d={arcPath(s.start, s.end, r, innerR)}
            fill={s.color}
            stroke="#fff"
            strokeWidth="1.5"
          >
            <title>
              {s.chain}: €{s.total_eur.toFixed(2)} ({s.pct}%)
            </title>
          </path>
        ))}
      </svg>
      <div className="flex flex-col gap-1.5 text-sm w-full">
        {data.map((d) => (
          <div key={d.chain} className="flex items-center gap-2">
            <span
              className="inline-block w-3 h-3 rounded-sm shrink-0"
              style={{ backgroundColor: d.color }}
            />
            <span className="capitalize text-gray-700 flex-1">{d.chain}</span>
            <span className="text-gray-500 text-xs">{d.visits}×</span>
            <span className="font-medium text-gray-800 w-20 text-right">
              €{d.total_eur.toFixed(2)}
            </span>
            <span className="text-xs text-gray-400 w-10 text-right">
              {d.pct}%
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

const CATEGORY_COLORS = [
  "#2d7a3a",
  "#16a34a",
  "#4ade80",
  "#86efac",
  "#059669",
  "#0d9488",
  "#0891b2",
  "#2563eb",
  "#7c3aed",
  "#c026d3",
  "#e11d48",
  "#f59e0b",
  "#ea580c",
  "#78716c",
  "#94a3b8",
];

const NUTRISCORE_COLORS = {
  A: "#038141",
  B: "#85bb2f",
  C: "#fecb02",
  D: "#ee8100",
  E: "#e63e11",
};
const NOVA_COLORS = { 1: "#038141", 2: "#85bb2f", 3: "#fecb02", 4: "#e63e11" };

function CategoryPieChart({ data }) {
  const size = 180;
  const cx = size / 2,
    cy = size / 2,
    r = 70,
    innerR = 36;
  let cumAngle = -Math.PI / 2;

  const slices = data.map((d, i) => {
    const angle = (d.pct / 100) * 2 * Math.PI;
    const start = cumAngle;
    cumAngle += angle;
    return {
      ...d,
      start,
      end: cumAngle,
      color: CATEGORY_COLORS[i % CATEGORY_COLORS.length],
    };
  });

  function arcPath(start, end, outerR, ir) {
    const large = end - start > Math.PI ? 1 : 0;
    const x1 = cx + outerR * Math.cos(start),
      y1 = cy + outerR * Math.sin(start);
    const x2 = cx + outerR * Math.cos(end),
      y2 = cy + outerR * Math.sin(end);
    const x3 = cx + ir * Math.cos(end),
      y3 = cy + ir * Math.sin(end);
    const x4 = cx + ir * Math.cos(start),
      y4 = cy + ir * Math.sin(start);
    return `M${x1},${y1} A${outerR},${outerR} 0 ${large},1 ${x2},${y2} L${x3},${y3} A${ir},${ir} 0 ${large},0 ${x4},${y4} Z`;
  }

  return (
    <div className="flex flex-col sm:flex-row items-center gap-4">
      <svg width={size} height={size} className="shrink-0">
        {slices.map((s) => (
          <path
            key={s.category}
            d={arcPath(s.start, s.end, r, innerR)}
            fill={s.color}
            stroke="#fff"
            strokeWidth="1.5"
          >
            <title>
              {s.category}: {s.count} ({s.pct}%)
            </title>
          </path>
        ))}
      </svg>
      <div className="flex flex-col gap-1 text-sm w-full max-h-48 overflow-y-auto">
        {slices.map((d) => (
          <div key={d.category} className="flex items-center gap-2">
            <span
              className="inline-block w-3 h-3 rounded-sm shrink-0"
              style={{ backgroundColor: d.color }}
            />
            <span className="text-gray-700 flex-1 truncate">{d.category}</span>
            <span className="text-gray-500 text-xs">{d.count}</span>
            <span className="text-xs text-gray-400 w-10 text-right">
              {d.pct}%
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

function NutriscoreBar({ data, total }) {
  return (
    <div className="space-y-2">
      <div className="flex rounded-lg overflow-hidden h-8">
        {data.map((d) => (
          <div
            key={d.grade}
            className="flex items-center justify-center text-white text-xs font-bold"
            style={{
              width: `${(d.count / total) * 100}%`,
              backgroundColor: NUTRISCORE_COLORS[d.grade],
              minWidth: d.count > 0 ? "24px" : "0",
            }}
            title={`${d.grade}: ${d.count} products`}
          >
            {d.count > 0 && d.grade}
          </div>
        ))}
      </div>
      <div className="flex justify-center gap-3">
        {data.map((d) => (
          <div
            key={d.grade}
            className="flex items-center gap-1 text-xs text-gray-500"
          >
            <span
              className="inline-block w-2.5 h-2.5 rounded-sm"
              style={{ backgroundColor: NUTRISCORE_COLORS[d.grade] }}
            />
            {d.grade}: {d.count}
          </div>
        ))}
      </div>
    </div>
  );
}

function NovaBar({ data, total }) {
  return (
    <div className="space-y-2">
      <div className="flex rounded-lg overflow-hidden h-8">
        {data.map((d) => (
          <div
            key={d.group}
            className="flex items-center justify-center text-white text-xs font-bold"
            style={{
              width: `${(d.count / total) * 100}%`,
              backgroundColor: NOVA_COLORS[d.group],
              minWidth: d.count > 0 ? "24px" : "0",
            }}
            title={`NOVA ${d.group}: ${d.count} products`}
          >
            {d.count > 0 && d.group}
          </div>
        ))}
      </div>
      <div className="flex justify-center gap-3">
        {data.map((d) => (
          <div
            key={d.group}
            className="flex items-center gap-1 text-xs text-gray-500"
          >
            <span
              className="inline-block w-2.5 h-2.5 rounded-sm"
              style={{ backgroundColor: NOVA_COLORS[d.group] }}
            />
            NOVA {d.group}: {d.count}
          </div>
        ))}
      </div>
    </div>
  );
}

const MACRO_LABELS = {
  energy_kcal: { label: "Energia", unit: "kcal", color: "#f59e0b" },
  proteins: { label: "Proteine", unit: "g", color: "#2563eb" },
  carbohydrates: { label: "Carboidrati", unit: "g", color: "#16a34a" },
  sugars: { label: "Zuccheri", unit: "g", color: "#e11d48" },
  fat: { label: "Grassi", unit: "g", color: "#ea580c" },
  saturated_fat: { label: "Grassi saturi", unit: "g", color: "#c026d3" },
  fiber: { label: "Fibre", unit: "g", color: "#059669" },
  salt: { label: "Sale", unit: "g", color: "#78716c" },
};

function MacroTable({ macros }) {
  const entries = Object.entries(MACRO_LABELS).filter(
    ([k]) => macros[k] != null,
  );
  if (!entries.length) return null;
  // For the bar, use max among non-energy values for scale
  const nonEnergy = entries
    .filter(([k]) => k !== "energy_kcal")
    .map(([k]) => macros[k]);
  const maxVal = Math.max(...nonEnergy, 1);

  return (
    <div className="space-y-2">
      {entries.map(([key, { label, unit, color }]) => {
        const val = macros[key];
        const isEnergy = key === "energy_kcal";
        return (
          <div key={key} className="flex items-center gap-3">
            <span className="w-16 text-sm text-gray-600 shrink-0">{label}</span>
            {!isEnergy && (
              <div className="flex-1 bg-gray-100 rounded-full h-2 overflow-hidden">
                <div
                  className="h-2 rounded-full"
                  style={{
                    width: `${Math.min((val / maxVal) * 100, 100)}%`,
                    backgroundColor: color,
                  }}
                />
              </div>
            )}
            <span
              className={`text-sm font-medium text-gray-800 ${isEnergy ? "flex-1" : "w-20"} text-right shrink-0`}
            >
              {val} {unit}
            </span>
          </div>
        );
      })}
      <p className="text-xs text-gray-400 mt-1">
        Media per 100g su tutti i prodotti abbinati
      </p>
    </div>
  );
}

function StatsPage() {
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [range, setRange] = React.useState("6m");

  React.useEffect(() => {
    setData(null);
    fetch(`/api/stats?date_range=${range}`)
      .then((r) => r.json())
      .then(setData)
      .catch((e) => setError(e.message));
  }, [range]);

  if (error)
    return (
      <div className="text-red-600 p-4">
        Errore nel caricamento statistiche: {error}
      </div>
    );
  if (!data)
    return (
      <div className="flex justify-center py-16 text-gray-400">
        Caricamento…
      </div>
    );

  const {
    overview,
    monthly,
    stores,
    by_chain,
    by_day,
    payment_methods,
    nutrition,
  } = data;

  const maxMonthly = Math.max(...Object.values(monthly), 1);
  const maxDay = Math.max(...by_day.map((d) => d.visits), 1);

  return (
    <div className="space-y-4">
      {/* Header + date range selector */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">Statistiche</h1>
        <select
          value={range}
          onChange={(e) => setRange(e.target.value)}
          className="text-sm border border-gray-200 rounded-lg px-3 py-1.5 bg-white text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-400"
        >
          <option value="6m">Ultimi 6 mesi</option>
          <option value="1y">Ultimo anno</option>
          <option value="all">Tutto il periodo</option>
        </select>
      </div>

      {/* Overview cards */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
        <StatCard label="Scontrini" value={overview.receipt_count} />
        <StatCard
          label="Totale speso"
          value={`€${overview.total_spend_eur.toFixed(2)}`}
        />
        <StatCard label="Prodotti unici" value={overview.unique_items} />
        <div className="bg-white rounded-xl shadow-sm p-4 flex flex-col gap-1 col-span-2 sm:col-span-3">
          <span className="text-xs text-gray-500 uppercase tracking-wide">
            Scontrino
          </span>
          <div className="flex justify-between gap-2 mt-1">
            {[
              ["Min", overview.min_basket_eur],
              ["Med", overview.avg_basket_eur],
              ["Max", overview.max_basket_eur],
            ].map(([label, val]) => (
              <div key={label} className="flex flex-col items-center flex-1">
                <span className="text-xs text-gray-400">{label}</span>
                <span className="text-lg font-bold text-gray-800">
                  €{val.toFixed(2)}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Monthly spending */}
      {Object.keys(monthly).length > 0 && (
        <Section title="Spesa mensile">
          <div className="space-y-2">
            {Object.entries(monthly).map(([month, total]) => (
              <div key={month} className="flex items-center gap-3">
                <span className="w-18 text-sm font-mono text-gray-600 shrink-0">
                  {month}
                </span>
                <MiniBar value={total} max={maxMonthly} />
                <span className="text-sm font-medium text-gray-800 w-20 text-right shrink-0">
                  €{total.toFixed(2)}
                </span>
              </div>
            ))}
          </div>
        </Section>
      )}

      {/* Spending by chain — pie chart */}
      {by_chain && by_chain.length > 0 && (
        <Section title="Per catena">
          <ChainPieChart data={by_chain} />
        </Section>
      )}

      {/* Shopping by day */}
      <Section title="Per giorno della settimana">
        <div className="space-y-2">
          {by_day.map(({ day, visits, total_eur }) => (
            <div key={day} className="flex items-center gap-3">
              <span className="w-8 text-sm font-medium text-gray-600 shrink-0">
                {day}
              </span>
              <MiniBar value={visits} max={maxDay} color="#16a34a" />
              <span className="text-sm text-gray-700 shrink-0 w-16 text-right">
                {visits} {visits !== 1 ? "visite" : "visita"}
              </span>
              <span className="text-xs text-gray-400 shrink-0 w-16 text-right">
                €{total_eur.toFixed(2)}
              </span>
            </div>
          ))}
        </div>
      </Section>

      {/* Payment methods */}
      {payment_methods.length > 0 && (
        <Section title="Metodi di pagamento">
          <div className="space-y-1">
            {payment_methods.map(({ method, count }) => (
              <div key={method} className="flex justify-between text-sm">
                <span className="text-gray-700">{method}</span>
                <span className="font-medium text-gray-800">{count}×</span>
              </div>
            ))}
          </div>
        </Section>
      )}

      {/* Nutrition stats — from OFF data */}
      {nutrition && nutrition.product_count > 0 && (
        <>
          <h2 className="text-base font-bold text-gray-700 mt-6">
            Nutrizione — {nutrition.product_count} prodotti abbinati
          </h2>

          {nutrition.by_category?.length > 0 && (
            <Section title="Prodotti per categoria">
              <CategoryPieChart data={nutrition.by_category} />
            </Section>
          )}

          {nutrition.nutriscore?.length > 0 && (
            <Section title="Distribuzione Nutri-Score">
              <NutriscoreBar
                data={nutrition.nutriscore}
                total={nutrition.nutriscore.reduce((s, d) => s + d.count, 0)}
              />
            </Section>
          )}

          {nutrition.nova?.length > 0 && (
            <Section title="Livello di lavorazione NOVA">
              <NovaBar
                data={nutrition.nova}
                total={nutrition.nova.reduce((s, d) => s + d.count, 0)}
              />
            </Section>
          )}

          {nutrition.avg_macros &&
            Object.keys(nutrition.avg_macros).length > 0 && (
              <Section title="Valori nutrizionali medi">
                <MacroTable macros={nutrition.avg_macros} />
              </Section>
            )}
        </>
      )}
    </div>
  );
}
