"use client";

import React, { useEffect, useMemo, useState } from "react";
import type { AgingRow } from "./agingApi";

interface Props {
  rows: AgingRow[]; // already search-filtered by the parent
}

function fmtDate(s?: string | null) {
  if (!s) return "—";
  try {
    return new Date(s)
      .toLocaleDateString("en-GB", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      })
      .replace(/ /g, "-");
  } catch {
    return "—";
  }
}

const badge: React.CSSProperties = {
  display: "inline-block",
  padding: "3px 9px",
  borderRadius: 999,
  fontSize: 11,
  fontWeight: 700,
  whiteSpace: "nowrap",
  lineHeight: 1.4,
};

function BucketBadge({ bucket }: { bucket: string }) {
  const map: Record<string, { bg: string; c: string; b: string }> = {
    Expired: { bg: "#fef2f2", c: "#b91c1c", b: "#fecaca" },
    "0-30 days": { bg: "#fff7ed", c: "#c2410c", b: "#fed7aa" },
    "31-90 days": { bg: "#fefce8", c: "#a16207", b: "#fde68a" },
    "91-180 days": { bg: "#eff6ff", c: "#1d4ed8", b: "#bfdbfe" },
    "180+ days": { bg: "#f0fdf4", c: "#15803d", b: "#bbf7d0" },
    "No Expiry Date": { bg: "#f1f5f9", c: "#64748b", b: "#e2e8f0" },
  };
  const m = map[bucket] ?? map["No Expiry Date"];
  return (
    <span style={{ ...badge, background: m.bg, color: m.c, border: `1px solid ${m.b}` }}>
      {bucket}
    </span>
  );
}

function CategoryBadge({ category }: { category: string }) {
  let bg = "#f1f5f9", c = "#475569";
  if (category.includes("Re-cert")) { bg = "#f5f3ff"; c = "#7c3aed"; }
  else if (category.includes("1st")) { bg = "#ecfeff"; c = "#0891b2"; }
  else if (category.includes("2nd")) { bg = "#f0fdfa"; c = "#0e7490"; }
  return <span style={{ ...badge, background: bg, color: c }}>{category}</span>;
}

export function AgingTable({ rows }: Props) {
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(10);

  // reset to page 1 whenever the (filtered) row set changes
  useEffect(() => setPage(1), [rows]);

  const total = rows.length;
  const lastPage = Math.max(1, Math.ceil(total / perPage));
  const start = (page - 1) * perPage;
  const pageRows = useMemo(
    () => rows.slice(start, start + perPage),
    [rows, start, perPage],
  );

  const th: React.CSSProperties = {
    textAlign: "left",
    padding: "10px 12px",
    fontSize: 11,
    fontWeight: 700,
    color: "#64748b",
    textTransform: "uppercase",
    letterSpacing: 0.4,
    borderBottom: "2px solid #e2e8f0",
    whiteSpace: "nowrap",
  };
  const td: React.CSSProperties = {
    padding: "10px 12px",
    fontSize: 13,
    color: "#334155",
    borderBottom: "1px solid #f1f5f9",
    verticalAlign: "middle",
  };
  const mono: React.CSSProperties = {
    fontFamily: "'IBM Plex Mono', monospace",
    fontSize: 12,
    fontWeight: 600,
    color: "#0f172a",
  };

  return (
    <div>
      {/* Showing count */}
      <div
        style={{
          padding: "10px 16px",
          background: "#f0fdfa",
          border: "1px solid #99f6e4",
          borderRadius: 8,
          marginBottom: 12,
          fontSize: 13,
          color: "#0f766e",
        }}
      >
        📋 Showing{" "}
        <strong>
          {total === 0 ? 0 : start + 1}–{Math.min(start + perPage, total)}
        </strong>{" "}
        of <strong>{total.toLocaleString()}</strong> certificate(s)
      </div>

      <div style={{ overflowX: "auto", border: "1px solid #e2e8f0", borderRadius: 12 }}>
        <table style={{ width: "100%", borderCollapse: "collapse", background: "#fff" }}>
          <thead style={{ background: "#f8fafc" }}>
            <tr>
              <th style={th}>S.No</th>
              <th style={th}>Certificate No</th>
              <th style={th}>Company</th>
              <th style={th}>Standard</th>
              <th style={th}>Category</th>
              <th style={th}>Orig. Registered</th>
              <th style={th}>Issue</th>
              <th style={th}>Expire</th>
              <th style={th}>Aging Bucket</th>
              <th style={{ ...th, textAlign: "right" }}>Days to Expiry</th>
              <th style={th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {pageRows.length === 0 ? (
              <tr>
                <td colSpan={11} style={{ ...td, textAlign: "center", padding: 40, color: "#9ca3af" }}>
                  No rows match your search.
                </td>
              </tr>
            ) : (
              pageRows.map((r, i) => {
                const dte = r.days_to_expiry;
                return (
                  <tr
                    key={`${r.certificate_no}-${r.standard}-${start + i}`}
                    style={{ transition: "background 0.1s" }}
                    onMouseEnter={(e) => (e.currentTarget.style.background = "#fafafa")}
                    onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
                  >
                    <td style={{ ...td, color: "#94a3b8" }}>{start + i + 1}</td>
                    <td style={td}><span style={mono}>{r.certificate_no}</span></td>
                    <td style={{ ...td, fontWeight: 600, minWidth: 200 }}>{r.company_name}</td>
                    <td style={td}>{r.standard}</td>
                    <td style={td}><CategoryBadge category={r.category} /></td>
                    <td style={{ ...td, color: "#64748b" }}>{fmtDate(r.originally_registered)}</td>
                    <td style={{ ...td, color: "#64748b" }}>{fmtDate(r.issue_date)}</td>
                    <td style={{ ...td, color: "#64748b" }}>{fmtDate(r.expire_date)}</td>
                    <td style={td}><BucketBadge bucket={r.aging_bucket} /></td>
                    <td
                      style={{
                        ...td,
                        textAlign: "right",
                        fontFamily: "'IBM Plex Mono', monospace",
                        fontWeight: 700,
                        color: dte == null ? "#94a3b8" : dte < 0 ? "#dc2626" : dte <= 90 ? "#c2410c" : "#15803d",
                      }}
                    >
                      {dte == null ? "—" : dte}
                    </td>
                    <td style={td}>
                      <span style={{ ...badge, background: "#f1f5f9", color: "#475569" }}>
                        {r.status || "—"}
                      </span>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          flexWrap: "wrap",
          gap: 10,
          marginTop: 12,
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "#64748b" }}>
          Rows per page:
          <select
            value={perPage}
            onChange={(e) => { setPerPage(Number(e.target.value)); setPage(1); }}
            style={{ padding: "6px 10px", borderRadius: 8, border: "1px solid #e2e8f0", fontSize: 13, fontWeight: 600 }}
          >
            {[10, 25, 50, 100].map((n) => <option key={n} value={n}>{n}</option>)}
          </select>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page <= 1}
            style={pagerBtn(page <= 1)}
          >
            ‹ Prev
          </button>
          <span style={{ fontSize: 13, color: "#475569", padding: "0 8px", fontWeight: 600 }}>
            Page {page} of {lastPage}
          </span>
          <button
            onClick={() => setPage((p) => Math.min(lastPage, p + 1))}
            disabled={page >= lastPage}
            style={pagerBtn(page >= lastPage)}
          >
            Next ›
          </button>
        </div>
      </div>
    </div>
  );
}

function pagerBtn(disabled: boolean): React.CSSProperties {
  return {
    padding: "7px 14px",
    borderRadius: 8,
    border: "1px solid #e2e8f0",
    background: disabled ? "#f8fafc" : "#fff",
    color: disabled ? "#cbd5e1" : "#475569",
    fontSize: 13,
    fontWeight: 600,
    cursor: disabled ? "not-allowed" : "pointer",
  };
}

export default AgingTable;
