// pages/Policy.js
import { useEffect, useMemo, useState } from "react";
import axios from "axios";

import PolicyHeader from "@/Components/Policy/PolicyHeader";
import PolicyFilters from "@/Components/Policy/PolicyFilters";
import PolicyToolbar from "@/Components/Policy/PolicyToolbar";
import PolicyTable from "@/Components/Policy/PolicyTable";

const TOKEN = process.env.NEXT_PUBLIC_SECRET_TOKEN;

export default function PolicyPage() {
  const [query, setQuery] = useState("");
  const [dateFrom, setDateFrom] = useState("2021-02-01");
  const [dateTo, setDateTo] = useState("2026-03-28");
  const [expandedId, setExpandedId] = useState(null);

  const [policies, setPolicies] = useState([]);
  const [loading, setLoading] = useState(false);
  const [apiError, setApiError] = useState("");

  const fetchPolicies = async () => {
    setLoading(true);
    setApiError("");
    try {
      const { data } = await axios.get("/api/Policy", {
        params: { q: query, from: dateFrom, to: dateTo, take: 500 },
        headers: { Authorization: TOKEN ? `Bearer ${TOKEN}` : "" },
      });

      if (!data?.success) throw new Error(data?.message || "Fetch failed");

      // Map DB -> UI shape (so your PolicyTable/InlineDetails work without changes)
      const ui = (data.policies || []).map(mapDbPolicyToUi);

      setPolicies(ui);
      setExpandedId(null);
    } catch (e) {
      console.error(e);
      setPolicies([]);
      setApiError(
        e?.response?.data?.message || e?.message || "Poliçeler getirilemedi."
      );
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPolicies();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return policies;

    return policies.filter((p) => {
      return (
        p.insured.toLowerCase().includes(q) ||
        p.plate.toLowerCase().includes(q) ||
        p.policyEndorsementNo.toLowerCase().includes(q) ||
        p.agency.toLowerCase().includes(q)
      );
    });
  }, [policies, query]);

  const onReset = () => {
    setQuery("");
    setDateFrom("2021-02-01");
    setDateTo("2026-03-28");
    setExpandedId(null);
    // fetch with defaults
    setTimeout(fetchPolicies, 0);
  };

  const toggleRow = (policyId) => {
    setExpandedId((prev) => (prev === policyId ? null : policyId));
  };

  return (
    <div className="min-h-screen bg-[#fafafa]">
      <div className="p-4 sm:p-6 lg:p-8">
        <PolicyHeader />

        <PolicyFilters
          query={query}
          onQuery={setQuery}
          dateFrom={dateFrom}
          onDateFrom={setDateFrom}
          dateTo={dateTo}
          onDateTo={setDateTo}
          onReset={onReset}
          onFilter={fetchPolicies}
          onList={fetchPolicies}
        />

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

        <div className="mt-4 rounded-3xl border border-black/10 bg-white shadow-sm">
          <PolicyToolbar
            onPrint={() => console.log("yazdır")}
            onSms={() => console.log("sms")}
            onExcel={() => console.log("excel")}
            onTransfer={() => console.log("transfer")}
          />

          <PolicyTable
            policies={filtered}
            expandedId={expandedId}
            onToggle={toggleRow}
            loading={loading} // optional if you want
          />
        </div>
      </div>
    </div>
  );
}

/* ---------------- helpers: DB -> UI ---------------- */

function num(v) {
  if (v === null || v === undefined || v === "") return null;
  const n = Number(v);
  return Number.isFinite(n) ? n : null;
}

function daysRemainingLabel(endISO) {
  if (!endISO) return "—";
  const end = new Date(endISO);
  if (Number.isNaN(end.getTime())) return "—";
  const now = new Date();
  const diff = Math.ceil((end.getTime() - now.getTime()) / 86400000);
  if (diff < 0) return "Sona Erdi";
  if (diff === 0) return "Bugün";
  return `${diff} gün`;
}

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

function mapDbPolicyToUi(p) {
  const start = p.startdate;
  const end = p.enddate;

  return {
    id: String(p.id),
    agency: p.agency,
    date: start, // keep your table working (it uses trDate on `date`)
    insured: p.insured,
    policyEndorsementNo: p.policyEndorsementNo,
    product: p.product,
    plate: p.plate,
    premium: num(p.premium) ?? 0,
    assignments: p.assignments || "-",
    paymentStatus: p.paymentStatus || "-",

    meta: {
      issueDate: start,       // no separate issueDate in schema
      startDate: start,
      endDate: end,
      transferDate: start,
      remainingLabel: daysRemainingLabel(end),
    },

    installments: [
      {
        date: start,
        amount: num(p.grossPremium) ?? num(p.premium) ?? 0,
        paid: (num(p.remainingAmount) ?? 0) <= 0,
        note: "",
      },
    ],

    grossPremium: num(p.grossPremium) ?? num(p.premium) ?? 0,
    paidAmount: num(p.paidAmount) ?? 0,
    vGecen: num(p.vGecen) ?? 0,
    remainingAmount: num(p.remainingAmount) ?? 0,

    policyInfo: {
      Marka: p.brand || "—",
      "Marka Tipi": p.brandType || "—",
      Model: p.modelYear ?? "—",
      Plaka: p.plate || "—",
      "Motor No": p.motorNo || "—",
      "Şasi No": p.chassisNo || "—",
      "Araç Bedeli": p.vehicleValue ?? "—",
      "Kullanım Tarzı": p.usageType || "—",
      "Ruhsat Seri No": p.licenseSerialNo || "—",
      "Muayene Tarihi": p.inspectionDate ? formatTRDate(p.inspectionDate) : "—",
      "Ürün Kodu": p.productCode || "—",
      Telefon: p.phone || "—",
      "TC Kimlik": p.nationalId || "—",
      "Doğum Tarihi": p.birthDate ? formatTRDate(p.birthDate) : "—",
    },

    netPremium: num(p.netPremium) ?? 0,
    commission: num(p.commission) ?? 0,
    branch: p.branch || "—",
    representative: p.representative || "—",
    policyStatus: p.policyStatus || "—",
    renewed: Boolean(p.renewed),
  };
}