import { useEffect, useState } from "react";
import { CalendarRange, RefreshCw, BarChart3, AlertTriangle, CheckCircle2 } from "lucide-react";

const REKAP_API = "http://openplate.my.id/api/tracking/rekap.php";

export default function RekapPengiriman({ role = "admin", sppgId = "" }) {
  const [periode, setPeriode] = useState("mingguan");
  const [data, setData] = useState({
    tanggal_mulai: "",
    tanggal_selesai: "",
    summary: {
      total_pengiriman: 0,
      total_porsi: 0,
      total_tervalidasi: 0,
      total_bermasalah: 0,
      bukti_omprengan: 0,
      bukti_menu: 0,
      bukti_penerimaan: 0,
    },
  });
  const [loading, setLoading] = useState(false);

  const loadRekap = async () => {
    try {
      setLoading(true);

      const params = new URLSearchParams({ periode });
      if (role === "sppg" && sppgId) {
        params.set("sppg_id", String(sppgId));
      }

      const res = await fetch(`${REKAP_API}?${params.toString()}`);
      const result = await res.json();

      if (result.success) {
        setData(result.data);
      }
    } catch (err) {
      console.error("Gagal mengambil rekap:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadRekap();
  }, [periode, role, sppgId]);

  const summary = data.summary || {};

  return (
    <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
      <div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <div className="inline-flex items-center gap-2 rounded-full bg-purple-50 px-3 py-1 text-xs font-bold text-purple-700">
            <CalendarRange className="h-4 w-4" />
            Rekap Pengiriman
          </div>

          <h2 className="mt-3 text-xl font-black text-slate-950">
            Rekap {periode === "mingguan" ? "Mingguan" : "Bulanan"}
          </h2>

          <p className="mt-1 text-sm text-slate-500">
            Periode {data.tanggal_mulai || "-"} sampai {data.tanggal_selesai || "-"}
          </p>
        </div>

        <div className="flex gap-2">
          <select
            value={periode}
            onChange={(e) => setPeriode(e.target.value)}
            className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold"
          >
            <option value="mingguan">Mingguan</option>
            <option value="bulanan">Bulanan</option>
          </select>

          <button
            type="button"
            onClick={loadRekap}
            className="inline-flex items-center gap-2 rounded-xl border border-slate-200 px-3 py-2 text-sm font-bold text-slate-700 hover:bg-slate-50"
          >
            <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
            Refresh
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <div className="rounded-2xl bg-blue-50 p-4">
          <BarChart3 className="mb-2 h-5 w-5 text-blue-700" />
          <p className="text-sm font-semibold text-blue-700">Total Pengiriman</p>
          <p className="mt-1 text-2xl font-black text-blue-700">{summary.total_pengiriman || 0}</p>
        </div>

        <div className="rounded-2xl bg-amber-50 p-4">
          <p className="text-sm font-semibold text-amber-700">Total Porsi</p>
          <p className="mt-1 text-2xl font-black text-amber-700">
            {Number(summary.total_porsi || 0).toLocaleString("id-ID")}
          </p>
        </div>

        <div className="rounded-2xl bg-emerald-50 p-4">
          <CheckCircle2 className="mb-2 h-5 w-5 text-emerald-700" />
          <p className="text-sm font-semibold text-emerald-700">Tervalidasi</p>
          <p className="mt-1 text-2xl font-black text-emerald-700">{summary.total_tervalidasi || 0}</p>
        </div>

        <div className="rounded-2xl bg-red-50 p-4">
          <AlertTriangle className="mb-2 h-5 w-5 text-red-700" />
          <p className="text-sm font-semibold text-red-700">Bermasalah</p>
          <p className="mt-1 text-2xl font-black text-red-700">{summary.total_bermasalah || 0}</p>
        </div>
      </div>

      <div className="mt-4 grid grid-cols-1 gap-3 text-sm md:grid-cols-3">
        <div className="rounded-2xl bg-slate-50 p-3 font-semibold text-slate-600">
          Bukti Omprengan: {summary.bukti_omprengan || 0}
        </div>
        <div className="rounded-2xl bg-slate-50 p-3 font-semibold text-slate-600">
          Bukti Menu: {summary.bukti_menu || 0}
        </div>
        <div className="rounded-2xl bg-slate-50 p-3 font-semibold text-slate-600">
          Bukti Penerimaan: {summary.bukti_penerimaan || 0}
        </div>
      </div>
    </section>
  );
}
