"use client";

import React, { useEffect, useState, useCallback, useRef } from "react";
import toast from "react-hot-toast";
import styles from "../../modules/commonstyle/dattabale.module.css";
import { LegacyFilters } from "./LegacyFilters";
import { MonthYearFilter } from "./MonthYearFilter";
import { Pagination } from "../certificates/Pagination";
import { EnterpriseLoader } from "../../../../components/loader/loader";
import { deleteWithConfirm } from "../../../../components/ConfirmDialog/ConfirmDialog";
import {
  getLegacyPaginated,
  deleteLegacy,
  importLegacyExcel,
  type LegacyCertificate,
} from "@/lib/api/legacy.api";
import LegacyForm from "./Form/LegacyForm";

interface Props {
  refreshFlag?: boolean;
}

function useDebounce<T>(value: T, delay: number): T {
  const [d, setD] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setD(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return d;
}

export default function LegacyTable({ refreshFlag }: Props) {
  // ── Data state ──────────────────────────────────────────────────────────
  const [data, setData] = useState<LegacyCertificate[]>([]);
  const [total, setTotal] = useState(0);
  const [lastPage, setLastPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // ── Pagination ──────────────────────────────────────────────────────────
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(20);

  // ── Filters ─────────────────────────────────────────────────────────────
  const [searchTerm, setSearchTerm] = useState("");
  const [standardFilter, setStandardFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const debouncedSearch = useDebounce(searchTerm, 400);

  // ── Period filter (month / year) ─────────────────────────────────────────
  const [yearFilter, setYearFilter] = useState<number | "all">("all");
  const [monthFilter, setMonthFilter] = useState<number | "all">("all");
  const [monthlyCounts, setMonthlyCounts] = useState<number[]>(() =>
    Array(12).fill(0),
  );
  const [countsLoading, setCountsLoading] = useState(false);

  // Aggregated counts built from ALL matching rows: { [year]: number[12] }
  // plus an "all years" array. Year switches read from here with no refetch.
  const aggRef = useRef<{ byYear: Record<number, number[]>; all: number[] }>({
    byYear: {},
    all: Array(12).fill(0),
  });
  // Guards against stale async responses overwriting newer ones.
  const countsReqRef = useRef(0);
  // Real years discovered in the data (falls back to the static range below).
  const [availableYears, setAvailableYears] = useState<number[]>([]);

  // Fallback year range (current year back to 2018) if none discovered yet
  const YEARS = React.useMemo(() => {
    const y = new Date().getFullYear();
    return Array.from({ length: y - 2017 }, (_, i) => y - i);
  }, []);

  // ── Modals ──────────────────────────────────────────────────────────────
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);

  // ── File input ref for import ───────────────────────────────────────────
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [importing, setImporting] = useState(false);

  // ── Fetch ───────────────────────────────────────────────────────────────
  const fetchPage = useCallback(
    (
      page: number,
      limit: number,
      search: string,
      standard: string,
      status: string,
      year: number | "all",
      month: number | "all",
    ) => {
      setLoading(true);
      getLegacyPaginated({
        page,
        limit,
        ...(search && { q: search }),
        ...(standard !== "all" && { standard }),
        ...(status !== "all" && { status }),
        // NOTE: `year` & `month` are new server-side params. The backend
        // should filter rows by issue_date year / month when present.
        ...(year !== "all" && { year }),
        ...(month !== "all" && { month }),
      } as any)
        .then((res) => {
          setData(res.data);
          setTotal(res.total);
          setLastPage(res.lastPage);
        })
        .catch((err) => setError(err.message))
        .finally(() => setLoading(false));
    },
    [],
  );

  // ── Monthly counts (exact per-month totals) ───────────────────────────────
  // Pages through ALL matching rows (using the server's reported `total` as the
  // stop condition, so it works even if the API caps page size), then buckets
  // every row by year + month from its issue_date. Switching the year just
  // reads the pre-built aggregate — no refetch.
  //
  // For best performance on large tables, replace loadMonthlyCounts with a
  // dedicated aggregation endpoint, e.g.
  //   GET /legacy/monthly-counts?year=&q=&standard=&status=  ->  number[12]
  const COUNTS_PAGE_SIZE = 1000;

  // Apply the already-aggregated counts for a given year to the cards.
  const applyYear = useCallback((year: number | "all") => {
    const agg = aggRef.current;
    if (year === "all") {
      setMonthlyCounts(agg.all.slice());
    } else {
      setMonthlyCounts((agg.byYear[year] ?? Array(12).fill(0)).slice());
    }
  }, []);

  const loadMonthlyCounts = useCallback(
    async (
      search: string,
      standard: string,
      status: string,
      year: number | "all",
    ) => {
      const reqId = ++countsReqRef.current;
      setCountsLoading(true);

      const byYear: Record<number, number[]> = {};
      const all = Array(12).fill(0);

      try {
        let page = 1;
        let collected = 0;
        let total = Infinity;

        // Safety cap so a misbehaving API can never loop forever.
        while (collected < total && page <= 1000) {
          const res = await getLegacyPaginated({
            page,
            limit: COUNTS_PAGE_SIZE,
            ...(search && { q: search }),
            ...(standard !== "all" && { standard }),
            ...(status !== "all" && { status }),
          });

          // A newer request started — abandon this stale one.
          if (countsReqRef.current !== reqId) return;

          total = res.total ?? res.data.length;
          if (!res.data.length) break;

          for (const r of res.data) {
            if (!r.issue_date) continue;
            const d = new Date(r.issue_date);
            if (isNaN(d.getTime())) continue;
            const y = d.getFullYear();
            const m = d.getMonth();
            (byYear[y] ??= Array(12).fill(0))[m] += 1;
            all[m] += 1;
          }

          collected += res.data.length;
          page += 1;
        }

        if (countsReqRef.current !== reqId) return;

        aggRef.current = { byYear, all };
        setAvailableYears(
          Object.keys(byYear)
            .map(Number)
            .sort((a, b) => b - a),
        );
        applyYear(year);
      } catch {
        if (countsReqRef.current !== reqId) return;
        aggRef.current = { byYear: {}, all: Array(12).fill(0) };
        setMonthlyCounts(Array(12).fill(0));
      } finally {
        if (countsReqRef.current === reqId) setCountsLoading(false);
      }
    },
    [applyYear],
  );

  // ── Initial load ────────────────────────────────────────────────────────
  useEffect(() => {
    setCurrentPage(1);
    fetchPage(1, itemsPerPage, "", "all", "all", "all", "all");
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [refreshFlag]);

  // ── Page change ─────────────────────────────────────────────────────────
  useEffect(() => {
    fetchPage(
      currentPage,
      itemsPerPage,
      debouncedSearch,
      standardFilter,
      statusFilter,
      yearFilter,
      monthFilter,
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, itemsPerPage]);

  // ── Filter change → reset to page 1 ─────────────────────────────────────
  useEffect(() => {
    setCurrentPage(1);
    fetchPage(
      1,
      itemsPerPage,
      debouncedSearch,
      standardFilter,
      statusFilter,
      yearFilter,
      monthFilter,
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debouncedSearch, standardFilter, statusFilter, yearFilter, monthFilter]);

  // ── Rebuild the full aggregate when search/standard/status changes ────────
  useEffect(() => {
    loadMonthlyCounts(
      debouncedSearch,
      standardFilter,
      statusFilter,
      yearFilter,
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debouncedSearch, standardFilter, statusFilter, refreshFlag]);

  // ── Year change → just re-read the aggregate (no refetch) ─────────────────
  useEffect(() => {
    applyYear(yearFilter);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [yearFilter]);

  const refresh = () => {
    fetchPage(
      currentPage,
      itemsPerPage,
      debouncedSearch,
      standardFilter,
      statusFilter,
      yearFilter,
      monthFilter,
    );
    loadMonthlyCounts(
      debouncedSearch,
      standardFilter,
      statusFilter,
      yearFilter,
    );
  };

  const clearAllFilters = () => {
    setSearchTerm("");
    setStandardFilter("all");
    setStatusFilter("all");
    setYearFilter("all");
    setMonthFilter("all");
  };

  const periodActive = yearFilter !== "all" || monthFilter !== "all";
  const anyFilterActive =
    !!searchTerm ||
    standardFilter !== "all" ||
    statusFilter !== "all" ||
    periodActive;

  // ── Actions ─────────────────────────────────────────────────────────────
  const handleAdd = () => {
    setEditingId(null);
    setIsFormOpen(true);
  };

  const handleEdit = (row: LegacyCertificate) => {
    setEditingId(row.id);
    setIsFormOpen(true);
  };

  const handleDelete = async (row: LegacyCertificate) => {
    const { confirmed, error: e } = await deleteWithConfirm(
      row.cert_no,
      () => deleteLegacy(row.id),
      {
        successMessage: `✅ Previous certificate "${row.cert_no}" deleted successfully`,
        errorMessage: "Failed to delete previous certificate",
      },
    );
    if (confirmed && !e) refresh();
  };

  // ── Import Excel ────────────────────────────────────────────────────────
  const handleImportClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setImporting(true);
    try {
      const result = await importLegacyExcel(file);
      toast.success(
        `✅ Imported ${result.inserted} records (${result.skipped} skipped duplicates)`,
        { duration: 4000 },
      );
      refresh();
    } catch (err: any) {
      toast.error(err.message ?? "Import failed", { duration: 5000 });
    } finally {
      setImporting(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  // ✅ FIXED — Wrapper for refreshData passed to form
  const handleFormRefresh = useCallback(
    (toastMessage?: string) => {
      if (toastMessage) {
        toast.success(toastMessage, { duration: 4000 });
      }
      refresh();
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [
      currentPage,
      itemsPerPage,
      debouncedSearch,
      standardFilter,
      statusFilter,
      yearFilter,
      monthFilter,
    ],
  );

  // ── Format date helper ──────────────────────────────────────────────────
  const formatDate = (d: string | null) => {
    if (!d) return "—";
    try {
      return new Date(d).toLocaleDateString("en-GB");
    } catch {
      return String(d);
    }
  };

  // ── Status badge color ──────────────────────────────────────────────────
  const statusColor = (status: string) => {
    const s = (status || "").toUpperCase();
    if (s === "QRS")
      return { bg: "#dbeafe", color: "#1e40af", border: "#93c5fd" };
    if (s === "TQS")
      return { bg: "#fef3c7", color: "#b45309", border: "#fcd34d" };
    if (s === "MIGRATION")
      return { bg: "#e9d5ff", color: "#6b21a8", border: "#c4b5fd" };
    return { bg: "#f1f5f9", color: "#64748b", border: "#cbd5e1" };
  };

  if (error) {
    return (
      <div className={styles.errorContainer}>
        <div className={styles.errorIcon}>⚠️</div>
        <h3 className={styles.errorTitle}>Error</h3>
        <p className={styles.errorMessage}>{error}</p>
        <button className={styles.errorButton} onClick={refresh}>
          Retry
        </button>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      {/* ═══ Hidden file input for import ═══ */}
      <input
        ref={fileInputRef}
        type="file"
        accept=".xlsx,.xls,.csv"
        style={{ display: "none" }}
        onChange={handleFileChange}
      />

      {/* ═══ Toolbar ═══ */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          marginBottom: 12,
          flexWrap: "wrap",
          gap: 10,
        }}
      >
        <div>
          <h1
            style={{
              margin: 0,
              fontSize: 22,
              fontWeight: 800,
              color: "#0f172a",
            }}
          >
            📋 Previous Certificates
          </h1>
          <p
            style={{
              margin: "2px 0 0",
              fontSize: 12,
              color: "#64748b",
            }}
          >
            Previous certificates (UAE legacy + overseas + migrations)
          </p>
        </div>

        <button
          onClick={handleAdd}
          style={{
            padding: "10px 20px",
            backgroundColor: "#0f766e",
            color: "#fff",
            border: "none",
            borderRadius: 8,
            cursor: "pointer",
            fontSize: 13,
            fontWeight: 700,
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            boxShadow: "0 2px 8px rgba(15, 118, 110, 0.25)",
          }}
        >
          + Add Previous Certificates
        </button>
      </div>

      {/* ═══ Month / Year period filter (on top) ═══ */}
      <MonthYearFilter
        year={yearFilter}
        setYear={setYearFilter}
        month={monthFilter}
        setMonth={setMonthFilter}
        years={availableYears.length ? availableYears : YEARS}
        monthlyCounts={monthlyCounts}
        loading={countsLoading}
      />

      {/* ═══ Filters ═══ */}
      <LegacyFilters
        searchTerm={searchTerm}
        setSearchTerm={setSearchTerm}
        standardFilter={standardFilter}
        setStandardFilter={setStandardFilter}
        statusFilter={statusFilter}
        setStatusFilter={setStatusFilter}
        clearFilters={clearAllFilters}
        onRefresh={refresh}
        onImport={handleImportClick}
      />

      {/* ═══ Importing indicator ═══ */}
      {importing && (
        <div
          style={{
            padding: "10px 14px",
            backgroundColor: "#eef2ff",
            border: "1px solid #c7d2fe",
            borderRadius: 8,
            marginBottom: 12,
            fontSize: 13,
            color: "#4338ca",
            fontWeight: 600,
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}
        >
          <div
            style={{
              width: 16,
              height: 16,
              border: "2px solid #c7d2fe",
              borderTopColor: "#4338ca",
              borderRadius: "50%",
              animation: "spin 0.7s linear infinite",
            }}
          />
          Importing Excel file... please wait
        </div>
      )}

      {/* ═══ Record count ═══ */}
      <div
        style={{
          padding: "10px 16px",
          backgroundColor: "#f0fdfa",
          border: "1px solid #99f6e4",
          borderRadius: 8,
          marginBottom: 12,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          fontSize: 13,
          color: "#0f766e",
        }}
      >
        <span>
          📊 Showing{" "}
          <strong>
            {data.length > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0}–
            {(currentPage - 1) * itemsPerPage + data.length}
          </strong>{" "}
          of <strong>{total.toLocaleString()}</strong> Previous Certificates records
          {anyFilterActive && (
            <span style={{ marginLeft: 8, color: "#9ca3af" }}>(filtered)</span>
          )}
        </span>
      </div>

      {/* ═══ Table ═══ */}
      <div className={styles.tableWrapper}>
        <table className={styles.table}>
          <thead>
            <tr>
              <th className={styles.th} style={{ width: 60 }}>
                #
              </th>
              <th className={styles.th}>Cert No</th>
              <th className={styles.th}>Company</th>
              <th className={styles.th}>Standard</th>
              <th className={styles.th}>Issue Date</th>
              <th className={styles.th}>Expire Date</th>
              <th className={styles.th}>Source</th>
              <th className={styles.actionsCol}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td
                  colSpan={8}
                  style={{
                    textAlign: "center",
                    padding: "60px",
                    color: "#9ca3af",
                  }}
                >
                  <div
                    style={{
                      display: "inline-block",
                      width: 28,
                      height: 28,
                      border: "3px solid #e5e7eb",
                      borderTopColor: "#14b8a6",
                      borderRadius: "50%",
                      animation: "spin 0.7s linear infinite",
                      marginBottom: 10,
                    }}
                  />
                  <p style={{ margin: 0 }}>Loading...</p>
                </td>
              </tr>
            ) : data.length > 0 ? (
              data.map((row, idx) => {
                const sCol = statusColor(row.status);
                return (
                  <tr key={row.id} className={styles.tr}>
                    <td className={styles.td}>
                      {(currentPage - 1) * itemsPerPage + idx + 1}
                    </td>
                    {/* ✅ UPDATED — Cert No cell now has edit icon next to it */}
                    <td
                      className={styles.td}
                      style={{
                        fontFamily: "'IBM Plex Mono', monospace",
                        fontWeight: 600,
                        fontSize: 12,
                      }}
                    >
                      <div
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: 6,
                        }}
                      >
                        <span>{row.cert_no}</span>
                        <button
                          onClick={() => handleEdit(row)}
                          title="Edit this certificate"
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            justifyContent: "center",
                            width: 22,
                            height: 22,
                            padding: 0,
                            border: "1px solid #14b8a6",
                            backgroundColor: "#f0fdfa",
                            color: "#0f766e",
                            borderRadius: 4,
                            cursor: "pointer",
                            fontSize: 11,
                            transition: "all 0.15s",
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = "#ccfbf1";
                            e.currentTarget.style.transform = "scale(1.1)";
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = "#f0fdfa";
                            e.currentTarget.style.transform = "scale(1)";
                          }}
                        >
                          ✏️
                        </button>
                      </div>
                    </td>
                    <td className={styles.td} style={{ fontWeight: 500 }}>
                      {row.company_name}
                    </td>
                    <td className={styles.td}>
                      <span
                        style={{
                          padding: "3px 8px",
                          backgroundColor: "#f1f5f9",
                          color: "#475569",
                          borderRadius: 6,
                          fontSize: 11,
                          fontWeight: 600,
                        }}
                      >
                        {row.standard}
                      </span>
                    </td>
                    <td
                      className={styles.td}
                      style={{ fontSize: 12, color: "#64748b" }}
                    >
                      {formatDate(row.issue_date)}
                    </td>
                    <td
                      className={styles.td}
                      style={{ fontSize: 12, color: "#64748b" }}
                    >
                      {formatDate(row.expire_date)}
                    </td>
                    <td className={styles.td}>
                      <span
                        style={{
                          padding: "3px 8px",
                          backgroundColor: sCol.bg,
                          color: sCol.color,
                          border: `1px solid ${sCol.border}`,
                          borderRadius: 6,
                          fontSize: 10,
                          fontWeight: 700,
                          textTransform: "uppercase",
                          letterSpacing: 0.3,
                        }}
                      >
                        {row.status || "—"}
                      </span>
                    </td>
                    <td className={styles.actionsCol}>
                      <div style={{ display: "flex", gap: 6 }}>
                        <button
                          onClick={() => handleEdit(row)}
                          style={{
                            padding: "5px 10px",
                            border: "1px solid #14b8a6",
                            backgroundColor: "#f0fdfa",
                            color: "#0f766e",
                            borderRadius: 6,
                            cursor: "pointer",
                            fontSize: 11,
                            fontWeight: 600,
                          }}
                          title="Edit"
                        >
                          ✏️ Edit
                        </button>
                        <button
                          onClick={() => handleDelete(row)}
                          style={{
                            padding: "5px 10px",
                            border: "1px solid #ef4444",
                            backgroundColor: "#fef2f2",
                            color: "#b91c1c",
                            borderRadius: 6,
                            cursor: "pointer",
                            fontSize: 11,
                            fontWeight: 600,
                          }}
                          title="Delete"
                        >
                          🗑️ Delete
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })
            ) : (
              <tr>
                <td colSpan={8} style={{ textAlign: "center", padding: "60px" }}>
                  <div
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "center",
                      gap: 12,
                    }}
                  >
                    <div style={{ fontSize: 36 }}>📋</div>
                    <h3 style={{ margin: 0, color: "#111827" }}>
                      No Previous Certificates Found
                    </h3>
                    <p style={{ color: "#6b7280", margin: 0 }}>
                      {anyFilterActive
                        ? "No records match your filters."
                        : "Get started by adding a Previous Certificates or importing Excel."}
                    </p>
                    {!anyFilterActive && (
                      <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
                        <button
                          onClick={handleAdd}
                          style={{
                            padding: "10px 20px",
                            backgroundColor: "#0f766e",
                            color: "#fff",
                            border: "none",
                            borderRadius: 8,
                            cursor: "pointer",
                            fontSize: 13,
                            fontWeight: 700,
                          }}
                        >
                          + Add Manually
                        </button>
                        <button
                          onClick={handleImportClick}
                          style={{
                            padding: "10px 20px",
                            backgroundColor: "#fff",
                            color: "#4f46e5",
                            border: "1.5px solid #6366f1",
                            borderRadius: 8,
                            cursor: "pointer",
                            fontSize: 13,
                            fontWeight: 700,
                          }}
                        >
                          📥 Import Excel
                        </button>
                      </div>
                    )}
                  </div>
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* ═══ Pagination ═══ */}
      {total > 0 && (
        <Pagination
          currentPage={currentPage}
          setCurrentPage={setCurrentPage}
          totalPages={lastPage}
          startIndex={(currentPage - 1) * itemsPerPage + 1}
          endIndex={Math.min(currentPage * itemsPerPage, total)}
          sortedDataLength={total}
          itemsPerPage={itemsPerPage}
          setItemsPerPage={(v) => {
            setCurrentPage(1);
            setItemsPerPage(v);
          }}
        />
      )}

      {/* ═══ Form modal ═══ */}
      <LegacyForm
        isOpen={isFormOpen}
        onClose={() => {
          setIsFormOpen(false);
          setEditingId(null);
        }}
        refreshData={handleFormRefresh}
        editId={editingId}
      />
    </div>
  );
}