import { useEffect, useMemo, useState } from "react";
import axios from "axios";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFileLines, faChartLine, faBoxesStacked } from "@fortawesome/free-solid-svg-icons";

const TOKEN = process.env.NEXT_PUBLIC_SECRET_TOKEN;

function formatTRY(n) {
  const num = Number(n || 0);
  return new Intl.NumberFormat("tr-TR", { style: "currency", currency: "TRY" }).format(num);
}

function formatDateTR(iso) {
  if (!iso) return "—";
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "—";
  const pad = (x) => String(x).padStart(2, "0");
  return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${d.getFullYear()}`;
}

export default function Home() {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [data, setData] = useState(null);

  useEffect(() => {
    let mounted = true;

    (async () => {
      setLoading(true);
      setError("");

      try {
        const res = await axios.get("/api/Dashboard/Home", {
          headers: {
            Authorization: TOKEN ? `Bearer ${TOKEN}` : "",
          },
        });

        if (!res.data?.success) throw new Error(res.data?.message || "Veri alınamadı");
        if (mounted) setData(res.data);
      } catch (e) {
        if (!mounted) return;
        setError(
          e?.response?.data?.message ||
            e?.response?.data?.error ||
            e?.message ||
            "Hata oluştu"
        );
      } finally {
        if (mounted) setLoading(false);
      }
    })();

    return () => {
      mounted = false;
    };
  }, []);

  const totalPolicies = data?.summary?.totalPolicies || 0;
  const premiumSum = data?.summary?.premiumSum || "0";

  const topProducts = useMemo(() => {
    const list = data?.products || [];
    return [...list].sort((a, b) => (b.count || 0) - (a.count || 0)).slice(0, 2);
  }, [data]);

  const recent = data?.recent || [];
  const products = data?.products || [];

  return (
    <div className="min-h-screen bg-[#fafafa] p-4 sm:p-6 lg:p-8">
      {/* Header */}
      <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <h1 className="text-2xl sm:text-3xl font-extrabold tracking-tight text-black/90">
            Anasayfa
          </h1>
          <p className="mt-1 text-sm text-black/55">
            Poliçe özetleri ve son kayıtlar.
          </p>
        </div>
      </div>

      {/* Error */}
      {!!error && (
        <div className="mt-4 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm font-semibold text-red-600">
          {error}
        </div>
      )}

      {/* KPI cards */}
      <div className="mt-6 grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-3">
        <KpiCard
          title="Toplam Poliçe"
          value={loading ? "—" : String(totalPolicies)}
          hint="Sistemde kayıtlı"
          icon={faFileLines}
          tone="red"
        />
        <KpiCard
          title="Toplam Prim"
          value={loading ? "—" : formatTRY(premiumSum)}
          hint="Toplam (net/iptal dahil olabilir)"
          icon={faChartLine}
          tone="emerald"
        />

        <KpiCard
          title={topProducts?.[0]?.product || "Ürün #1"}
          value={loading ? "—" : String(topProducts?.[0]?.count || 0)}
          hint={loading ? "—" : `Prim: ${formatTRY(topProducts?.[0]?.premiumSum || 0)}`}
          icon={faBoxesStacked}
          tone="amber"
        />
        <KpiCard
          title={topProducts?.[1]?.product || "Ürün #2"}
          value={loading ? "—" : String(topProducts?.[1]?.count || 0)}
          hint={loading ? "—" : `Prim: ${formatTRY(topProducts?.[1]?.premiumSum || 0)}`}
          icon={faBoxesStacked}
          tone="indigo"
        />
      </div>

      {/* Products breakdown + recent */}
      <div className="mt-4 grid grid-cols-1 xl:grid-cols-12 gap-3">
        {/* Ürün dağılımı */}
        <Card className="xl:col-span-5" title="Ürün Dağılımı">
          {loading ? (
            <div className="text-sm text-black/55">Yükleniyor...</div>
          ) : !products.length ? (
            <div className="text-sm text-black/55">Henüz veri yok.</div>
          ) : (
            <div className="space-y-2">
              {products.map((p, idx) => (
                <div
                  key={idx}
                  className="flex items-center justify-between rounded-2xl border border-black/10 bg-white px-4 py-3"
                >
                  <div>
                    <div className="text-sm font-extrabold text-black/80">{p.product}</div>
                    <div className="text-xs text-black/50">Adet: {p.count}</div>
                  </div>
                  <div className="text-sm font-extrabold text-black/75">
                    {formatTRY(p.premiumSum || 0)}
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>

        {/* Son 10 poliçe */}
        <Card className="xl:col-span-7" title="Son 10 Poliçe">
          <div className="overflow-x-auto">
            <table className="min-w-[900px] w-full text-left">
              <thead className="bg-black/[0.02]">
                <tr className="text-xs font-semibold text-black/55">
                  <th className="px-6 py-3">Acente</th>
                  <th className="px-6 py-3">Tarih</th>
                  <th className="px-6 py-3">Sigortalı</th>
                  <th className="px-6 py-3">Poliçe–Zeyil No</th>
                  <th className="px-6 py-3">Ürün</th>
                  <th className="px-6 py-3">Plaka</th>
                  <th className="px-6 py-3">Prim</th>
                  <th className="px-6 py-3">Ödeme</th>
                </tr>
              </thead>

              <tbody className="divide-y divide-black/10">
                {loading ? (
                  <tr>
                    <td colSpan={8} className="px-6 py-10 text-center text-sm text-black/50">
                      Yükleniyor...
                    </td>
                  </tr>
                ) : !recent.length ? (
                  <tr>
                    <td colSpan={8} className="px-6 py-10 text-center text-sm text-black/50">
                      Henüz veri yok.
                    </td>
                  </tr>
                ) : (
                  recent.map((p) => (
                    <tr key={p.id} className="hover:bg-black/[0.015] transition">
                      {/* first 3 letters + hover full name */}
                      <td
                        className="px-6 py-4 text-sm font-semibold text-black/75"
                        title={p.agency || ""}
                      >
                        {String(p.agency || "").slice(0, 3).toUpperCase()}
                      </td>

                      <td className="px-6 py-4 text-sm text-black/60">
                        {formatDateTR(p.startdate)}
                      </td>

                      <td className="px-6 py-4 text-sm font-semibold text-black/75">
                        {p.insured || "—"}
                      </td>

                      <td className="px-6 py-4 text-sm text-black/70">
                        {p.policyEndorsementNo || "—"}
                      </td>

                      <td className="px-6 py-4 text-sm text-black/70">
                        {p.product || "—"}
                      </td>

                      <td className="px-6 py-4 text-sm text-black/70">{p.plate || "—"}</td>

                      <td className="px-6 py-4 text-sm font-semibold">
                        <span
                          className={Number(p.premium) < 0 ? "text-red-500" : "text-emerald-600"}
                        >
                          {formatTRY(p.premium || 0)}
                        </span>
                      </td>

                      <td className="px-6 py-4">
                        <span className="inline-flex rounded-full border border-black/10 bg-black/5 px-3 py-1 text-xs font-semibold text-black/65">
                          {p.paymentStatus || "—"}
                        </span>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </Card>
      </div>
    </div>
  );
}

/* ---------- UI Components ---------- */

function Card({ title, children, className = "" }) {
  return (
    <div className={["rounded-3xl border border-black/10 bg-white shadow-sm", className].join(" ")}>
      <div className="px-5 py-4 border-b border-black/10 flex items-center justify-between">
        <div className="text-sm font-extrabold text-black/80">{title}</div>
      </div>
      <div className="p-5">{children}</div>
    </div>
  );
}

function KpiCard({ title, value, hint, icon, tone = "red" }) {
  const toneCls =
    tone === "red"
      ? "bg-[#e04a3b]/10 text-[#e04a3b] border-[#e04a3b]/15"
      : tone === "amber"
      ? "bg-amber-500/10 text-amber-700 border-amber-500/15"
      : tone === "indigo"
      ? "bg-indigo-500/10 text-indigo-700 border-indigo-500/15"
      : "bg-emerald-500/10 text-emerald-700 border-emerald-500/15";

  return (
    <div className="rounded-3xl border border-black/10 bg-white shadow-sm p-5">
      <div className="flex items-start justify-between gap-3">
        <div>
          <div className="text-sm font-semibold text-black/60">{title}</div>
          <div className="mt-2 text-2xl font-extrabold text-black/85">{value}</div>
          <div className="mt-1 text-xs text-black/45">{hint}</div>
        </div>
        <div className={["h-11 w-11 rounded-2xl border grid place-items-center", toneCls].join(" ")}>
          <FontAwesomeIcon icon={icon} />
        </div>
      </div>
    </div>
  );
}