import React, { useEffect, useMemo, useRef, useState } from "react";
import { FiBarChart2, FiTable, FiUsers } from "react-icons/fi";
import {
  getStatsMeta,
  getTopDrinkers as apiTopDrinkers,
  getProductShare as apiProductShare,
  API_BASE,  
} from "../../api";
import {
  ResponsiveContainer,
  BarChart, Bar, XAxis, YAxis, Tooltip,
  PieChart, Pie, Cell, CartesianGrid, LabelList,
} from "recharts";

/* ---------- Utils ---------- */
const euro = (c) => (Number(c ?? 0) / 100).toFixed(2);

function useLocalState(key, initial) {
  const [v, setV] = useState(() => {
    try { const s = localStorage.getItem(key); return s ? JSON.parse(s) : initial; } catch { return initial; }
  });
  useEffect(() => { try { localStorage.setItem(key, JSON.stringify(v)); } catch {} }, [key, v]);
  return [v, setV];
}

const absMedia = (u) => {
  if (!u) return "";
  // schon absolut?
  if (/^https?:\/\//i.test(u)) return u;
  // relativ -> an API_BASE anhängen
  return `${API_BASE}${u}`;
};

const DEFAULT_AVATAR = "/avatar-default.png"; // liegt in /public

function resolveAvatar(raw) {
  const v = (raw ?? "").trim();
  if (!v) return DEFAULT_AVATAR;                                 // nichts gesetzt
  if (/^(https?:|data:|blob:|\/\/)/i.test(v)) return v;          // absolute/data/blob
  if (v === DEFAULT_AVATAR) return v;                            // Frontend-Asset nie präfixen
  return `${API_BASE}${v.startsWith("/") ? v : `/${v}`}`;        // Backend-relativ → präfixen
}


const PALETTE = ["#60a5fa", "#a78bfa", "#34d399", "#f59e0b", "#f472b6", "#22d3ee", "#fb7185", "#84cc16", "#c084fc", "#facc15"];
const djb2 = (str) => { let h = 5381; for (let i = 0; i < str.length; i++) h = ((h << 5) + h) ^ str.charCodeAt(i); return Math.abs(h); };
const colorFor = (name) => PALETTE[djb2(String(name)) % PALETTE.length];

function aggregateTopN(items, n = 5) {
  const sorted = [...items].sort((a, b) => b.value - a.value);
  const top = sorted.slice(0, n);
  const rest = sorted.slice(n);
  const restSum = rest.reduce((s, it) => s + it.value, 0);
  return restSum > 0 ? [...top, { name: "Sonstige", value: restSum, __other: true }] : top;
}

/* ---------- Tooltips ---------- */
function BarTip({ active, payload }) {
  if (!active || !payload || !payload.length) return null;
  const p = payload[0]?.payload;
  return (
    <div className="rounded-lg bg-black/80 text-white/90 border border-white/10 px-3 py-2 text-xs">
      <div className="font-medium">{p?.name}</div>
      <div className="opacity-80">{p?.count} Buchungen · {p?.value} Stück · {p?.euro} €</div>
    </div>
  );
}
function PieTip({ active, payload }) {
  if (!active || !payload || !payload.length) return null;
  const p = payload[0];
  return (
    <div className="rounded-lg bg-black/80 text-white/90 border border-white/10 px-3 py-2 text-xs">
      <div className="font-medium">{p?.name}</div>
      <div className="opacity-80">Anzahl: {p?.value}</div>
    </div>
  );
}

/* ---------- Avatar-Tick für Y-Achse ---------- */
function makeYAvatarTick(avatarByName) {
  return function YAvatarTick({ x, y, payload }) {
    const url = avatarByName[payload?.value];
    const size = 20;
    const cx = x - 10; // nach links in den Achsenbereich
    const cy = y - size / 2;
    return (
      <g>
        {url
          ? <image href={url} x={cx - size} y={cy} width={size} height={size} preserveAspectRatio="xMidYMid slice" />
          : <circle cx={cx - 10} cy={y} r={9} fill="#94a3b8" />}
      </g>
    );
  };
}

/* ---------- Component ---------- */
export default function StatsPage() {
  const [meta, setMeta] = useState({ categories: [], last_delivery_at: null, visible_count: 0, hidden_count: 0, now: null });
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState(null);

  const [period, setPeriod] = useLocalState("stats.period", "last_delivery");
  const [view, setView] = useLocalState("stats.view", "chart"); // "chart" | "table"
  const [category, setCategory] = useLocalState("stats.category", "Alle");

  // Caches
  const cacheTop = useRef(new Map());   // key `${period}::${category}`
  const cacheShare = useRef(new Map()); // key `${period}`

  const [topRows, setTopRows] = useState([]);
  const [share, setShare] = useState({ total: 0, items: [] });

  /* ---- Aufbereitete Daten (Hooks VOR early-returns!) ---- */
  const topChartData = useMemo(
    () => topRows
      .slice(0, 10)
      .map(r => ({
        name: r.alias,
        value: r.amount_sum,
        avatar_url: resolveAvatar(r.avatar_url),
        count: r.count,
        euro: euro(r.revenue_cents),
      })),
    [topRows]
  );
  
  

  const avatarByName = useMemo(() => {
    const m = Object.create(null);
    for (const r of topChartData) m[r.name] = r.avatar_url || "";
    return m;
  }, [topChartData]);

  const pieDataRaw = useMemo(
    () => (share.items || []).map((it) => ({ name: it.product_name, value: it.count })),
    [share]
  );
  const pieData = useMemo(() => aggregateTopN(pieDataRaw, 5), [pieDataRaw]);

  /* ---- Daten laden ---- */
  useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const m = await getStatsMeta();
        if (!alive) return;
        setMeta(m || {});
        const cats = Array.isArray(m?.categories) ? m.categories : [];
        if (category !== "Alle" && !cats.includes(category)) setCategory("Alle");
      } catch (e) {
        if (alive) setErr(e);
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    let alive = true;
    const catParam = category === "Alle" ? "all" : category;
    (async () => {
      const kTop = `${period}::${catParam}`;
      if (cacheTop.current.has(kTop)) {
        setTopRows(cacheTop.current.get(kTop));
      } else {
        try {
          const rows = await apiTopDrinkers({ period, category: catParam, limit: 10 }); // Top 10
          if (!alive) return;
          cacheTop.current.set(kTop, rows || []);
          setTopRows(rows || []);
        } catch {
          if (alive) setTopRows([]);
        }
      }
      const kShare = `${period}`;
      if (cacheShare.current.has(kShare)) {
        setShare(cacheShare.current.get(kShare));
      } else {
        try {
          const data = await apiProductShare({ period });
          if (!alive) return;
          const norm = data && data.items ? data : { total: 0, items: [] };
          cacheShare.current.set(kShare, norm);
          setShare(norm);
        } catch {
          if (alive) setShare({ total: 0, items: [] });
        }
      }
    })();
    return () => { alive = false; };
  }, [period, category]);

  const YAvatarTick = ({ x, y, payload }) => {
    const name = String(payload?.value ?? "");
    const url  = avatarByName[name] || "";
    const size = 55;
    const r    = size / 2;
  
    // stabiler, eindeutiger ID-String (keine Sonderzeichen)
    const id = "clip-" + name.replace(/\W+/g, "") + "-" + Math.abs([...name].reduce((h,c)=>((h<<5)-h)+c.charCodeAt(0),0));
  
    // Position: links der Achse
    const imgX = (x - 12) - size;   // Bild links ausrichten
    const imgY = y - r;
    const cx   = imgX + r;          // Kreiszentrum auf Bildmitte
    const cy   = imgY + r;
  
    return (
      <g>
        <defs>
          <clipPath id={id}>
            <circle cx={cx} cy={cy} r={r} />
          </clipPath>
        </defs>
  
        {url ? (
          <image
            href={url}
            xlinkHref={url}           // Safari-Fallback
            x={imgX}
            y={imgY}
            width={size}
            height={size}
            preserveAspectRatio="xMidYMid slice"
            clipPath={`url(#${id})`}  // <- macht es rund
          />
        ) : (
          <circle cx={cx} cy={cy} r={r} fill="#94a3b8" />
        )}
      </g>
    );
  };
  
  

  /* ---- Early returns ---- */
  if (loading) return <div className="text-white">Lade Statistiken…</div>;
  if (err) return <div className="text-red-300">Fehler: {String(err.message || err)}</div>;

  const categories = ["Alle", ...(meta.categories || [])];

  return (
    <div className="space-y-6">
      {/* Header / Meta */}
      <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
        <div className="text-white/80 text-sm flex items-center gap-3">
          <span className="inline-flex items-center gap-2"><FiUsers className="opacity-70" /> sichtbar: <strong>{meta.visible_count}</strong></span>
          <span className="text-white/50">·</span>
          <span>ausgeblendet: <strong>{meta.hidden_count}</strong></span>
          {meta.last_delivery_at && (
            <>
              <span className="text-white/50">·</span>
              <span>letzte Lieferung: <code className="text-white/90">{new Date(meta.last_delivery_at).toLocaleString("de-DE")}</code></span>
            </>
          )}
        </div>

        <div className="flex flex-wrap items-center gap-2">
          {[
            ["last_delivery", "seit letzter Lieferung"],
            ["ytd", "dieses Jahr"],
            ["all", "gesamt"],
          ].map(([k, label]) => (
            <button key={k}
              onClick={() => setPeriod(k)}
              className={`px-3 py-1 rounded-full border transition ${period === k ? "bg-cyan-600 border-cyan-400 text-white" : "bg-transparent border-cyan-400/30 text-white/80 hover:bg-cyan-600/30"}`}>
              {label}
            </button>
          ))}
          <div className="ml-2 inline-flex rounded-lg overflow-hidden border border-cyan-400/30" role="group" aria-label="Ansicht wählen">
            <button
              className={`px-3 py-1 ${view === "chart" ? "bg-cyan-600 text-white" : "bg-transparent text-white/80 hover:bg-cyan-600/30"}`}
              onClick={() => setView("chart")}
              title="Grafik">
              <FiBarChart2 />
            </button>
            <button
              className={`px-3 py-1 ${view === "table" ? "bg-cyan-600 text-white" : "bg-transparent text-white/80 hover:bg-cyan-600/30"}`}
              onClick={() => setView("table")}
              title="Tabelle">
              <FiTable />
            </button>
          </div>
        </div>
      </div>

      {/* Kategorie-Tabs */}
      <div className="flex items-center gap-2 overflow-x-auto pb-1">
        {categories.map((c) => (
          <button key={c} onClick={() => setCategory(c)}
            className={`px-3 py-1 rounded-full border shrink-0 transition ${category === c ? "bg-cyan-600 border-cyan-400 text-white" : "bg-transparent border-cyan-400/30 text-white/80 hover:bg-cyan-600/30"}`}>
            {c}
          </button>
        ))}
      </div>

      {/* Inhalt */}
      {view === "chart" ? (
        <div className="grid md:grid-cols-2 gap-5">
          {/* Horizontales Ranking */}
          <div className="rounded-2xl bg-white/5 border border-white/10 p-5">
            <h3 className="text-white/90 font-semibold mb-3">Top-Trinker ({category})</h3>
            {topChartData.length === 0 ? (
              <div className="text-white/60 text-sm">Keine Daten für den Zeitraum.</div>
            ) : (
              <div className="h-80">
                <ResponsiveContainer width="100%" height="110%">
                  <BarChart layout="vertical" data={topChartData} margin={{ top: 8, right: 16, left: 8, bottom: 8 }} >
                    <CartesianGrid stroke="#cbd5e122" />
                    <XAxis type="number" allowDecimals={false} tick={{ fill: "#cbd5e1" }} domain={[0, "dataMax + 1"]} />
                    {/* Avatar statt Name */}
                    <YAxis
                      type="category"
                      dataKey="name"
                      tick={<YAvatarTick />}
                      tickLine={false}
                      axisLine={false}
                      width={72}          // vorher 36
                      tickMargin={6}
                    />          
                    <Tooltip content={<BarTip />} />
                    <Bar dataKey="value" isAnimationActive={true} radius={[4,4,4,4]}>
                      <LabelList dataKey="value" position="right" fill="#cbd5e1" />
                      {topChartData.map((d) => <Cell key={d.name} fill={colorFor(d.name)} />)}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            )}
          </div>

          {/* Donut + rechte Legende (Top-5 + Sonstige) */}
          <div className="rounded-2xl bg-white/5 border border-white/10 p-5">
            <div className="flex items-start gap-4">
              <div className="flex-1">
                <h3 className="text-white/90 font-semibold mb-3">Produktverteilung</h3>
                {(pieData.length === 0 || share.total === 0) ? (
                  <div className="text-white/60 text-sm">Keine Daten für den Zeitraum.</div>
                ) : (
                  <div className="h-64 relative">
                    <ResponsiveContainer width="100%" height="120%">
                      <PieChart>
                        <Pie
                          data={pieData}
                          dataKey="value"
                          nameKey="name"
                          innerRadius={70}
                          outerRadius={120}
                          isAnimationActive={true}
                          paddingAngle={2}
                        >
                          {pieData.map((s) => (
                            <Cell key={s.name} fill={s.__other ? "#64748b" : colorFor(s.name)} />
                          ))}
                        </Pie>
                        <Tooltip content={<PieTip />} />
                      </PieChart>
                    </ResponsiveContainer>
                    <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
                      <div className="text-center leading-tight">
                        <div className="text-white/70 text-xs">gesamt</div>
                        <div className="text-white font-semibold">{share.total}</div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
              <div className="min-w-[180px] max-w-[220px]">
                <ul className="space-y-1">
                  {pieData.map((s) => (
                    <li key={s.name} className="flex items-center gap-2 text-white/80 text-sm">
                      <span className="inline-block w-3 h-3 rounded" style={{ backgroundColor: s.__other ? "#64748b" : colorFor(s.name) }} />
                      <span className="truncate" title={s.name}>{s.name}</span>
                      <span className="ml-auto text-white/60">{s.value}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          </div>
        </div>
      ) : (
        // Tabellenansicht
        <div className="grid md:grid-cols-2 gap-6">
          <div className="rounded-2xl bg-white/5 border border-white/10 p-5">
            <h3 className="text-white/90 font-semibold mb-3">Top-Trinker ({category})</h3>
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm text-white/80">
                <thead className="text-white/60">
                  <tr>
                    <th className="text-left py-2 pr-4">Nutzer</th>
                    <th className="text-right py-2 pr-4">Buchungen</th>
                    <th className="text-right py-2 pr-4">Stück</th>
                    <th className="text-right py-2 pr-4">Umsatz (€)</th>
                  </tr>
                </thead>
                <tbody>
                  {topRows.slice(0, 10).map((r) => (
                    <tr key={r.user_id} className="border-t border-white/10">
                      <td className="py-2 pr-4">
                        <div className="flex items-center gap-4">
                          {r.avatar_url ? (
                             <img
                               src={resolveAvatar(r.avatar_url)}
                               alt={r.alias}
                               className="w-8 h-8 rounded-full object-cover"
                               loading="lazy"
                               decoding="async"
                               referrerPolicy="no-referrer"
                               onError={(e) => { e.currentTarget.onerror = null; e.currentTarget.src = DEFAULT_AVATAR; }}
                             />
                          ) : null}
                          <span className="truncate">{r.alias}</span>
                        </div>
                      </td>
                      <td className="py-2 pr-4 text-right">{r.count}</td>
                      <td className="py-2 pr-4 text-right">{r.amount_sum}</td>
                      <td className="py-2 pr-4 text-right font-mono">{euro(r.revenue_cents)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          <div className="rounded-2xl bg-white/5 border border-white/10 p-5">
            <h3 className="text-white/90 font-semibold mb-3">Produktverteilung</h3>
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm text-white/80">
                <thead className="text-white/60">
                  <tr>
                    <th className="text-left py-2 pr-4">Produkt</th>
                    <th className="text-right py-2 pr-4">Anzahl</th>
                  </tr>
                </thead>
                <tbody>
                  {pieData.map((p) => (
                    <tr key={p.name} className="border-t border-white/10">
                      <td className="py-2 pr-4">{p.name}</td>
                      <td className="py-2 pr-4 text-right">{p.value}</td>
                    </tr>
                  ))}
                  {pieData.length === 0 && (
                    <tr><td className="py-2 text-white/60" colSpan={2}>Keine Daten.</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
