"use client";

import React, { useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { FiSearch, FiRefreshCw, FiDownload, FiAward, FiCheckCircle, FiClock, FiXCircle } from "react-icons/fi";
import { clientPortalApi } from "@/lib/api/clientPortalApi";
import styles from "../../../(dashboard)/modules/commonstyle/dattabale.module.css";
import CertificateRow from "./CertificateRow";
import {
  type Certificate,
  statusMeta,
  getPageNumbers,
} from "./certificate.utils";

function extractArray(res: any): any[] {
  if (Array.isArray(res)) return res;
  if (Array.isArray(res?.data)) return res.data;
  if (Array.isArray(res?.data?.data)) return res.data.data;
  return [];
}

const PREMIUM_CSS = `
@keyframes cpFadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
.cp-rise { opacity: 0; animation: cpFadeUp 0.55s cubic-bezier(0.22,1,0.36,1) forwards; }
.cp-kpi { position: relative; overflow: hidden; transition: transform 0.2s ease, box-shadow 0.2s ease; }
.cp-kpi::before {
  content: ""; position: absolute; top: 0; left: -120%; width: 90%; height: 100%;
  background: linear-gradient(100deg, transparent 0%, rgba(255,255,255,0.18) 50%, transparent 100%);
  transform: skewX(-18deg); transition: left 0.6s cubic-bezier(0.4,0,0.2,1); pointer-events: none;
}
.cp-kpi:hover::before { left: 130%; }
.cp-kpi:hover { transform: translateY(-3px); }
`;

function useCountUp(target: number, ms = 900) {
  const [n, setN] = useState(0);
  useEffect(() => {
    if (!target) {
      setN(0);
      return;
    }
    let raf = 0;
    const start = performance.now();
    const tick = (t: number) => {
      const p = Math.min((t - start) / ms, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(Math.round(target * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, ms]);
  return n;
}

function Kpi({
  label, value, icon, gradient, shadow, subtitle, delay = 0,
}: {
  label: string; value: number; icon: React.ReactNode; gradient: string; shadow: string; subtitle: string; delay?: number;
}) {
  const animated = useCountUp(value);
  return (
    <div
      className="cp-rise cp-kpi"
      style={{
        animationDelay: delay * 80 + "ms",
        background: gradient,
        // borderRadius: 16,
        padding: "20px",
        color: "#fff",
        minHeight: 108,
        display: "flex",
        alignItems: "center",
        gap: 14,
        boxShadow: "inset 0 1px 0 rgba(255,255,255,0.2), 0 6px 16px " + shadow + ", 0 16px 34px -16px " + shadow,
        border: "1px solid rgba(255,255,255,0.14)",
      }}
    >
      <span
        style={{
          width: 46, height: 46, borderRadius: 13, background: "rgba(255,255,255,0.18)",
          border: "1px solid rgba(255,255,255,0.24)", display: "flex", alignItems: "center", justifyContent: "center",
          flexShrink: 0,
        }}
      >
        {icon}
      </span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: "rgba(255,255,255,0.92)" }}>{label}</div>
        <div style={{ fontSize: 26, fontWeight: 800, fontFamily: "'Cabinet Grotesk', 'Plus Jakarta Sans', sans-serif", lineHeight: 1.2 }}>
          {animated}
        </div>
        <div style={{ fontSize: 11.5, color: "rgba(255,255,255,0.68)", fontWeight: 500 }}>{subtitle}</div>
      </div>
    </div>
  );
}

const STATUS_OPTIONS = [
  { value: "all", label: "All statuses" },
  { value: "active", label: "Active" },
  { value: "expiring", label: "Expiring soon" },
  { value: "expired", label: "Expired" },
];

export default function CertificatesPage() {
  const [certificates, setCertificates] = useState<Certificate[]>([]);
  const [loading, setLoading] = useState(true);
  const [downloadingAll, setDownloadingAll] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  useEffect(() => {
    fetchCertificates();
  }, []);

  const fetchCertificates = async () => {
    try {
      setLoading(true);
      const response = await clientPortalApi.getCertificates();
      setCertificates(extractArray(response));
    } catch (error) {
      toast.error("Failed to load certificates");
    } finally {
      setLoading(false);
    }
  };

  const filtered = useMemo(() => {
    return certificates.filter((cert) => {
      const term = searchTerm.toLowerCase();
      const matchesSearch =
        !term ||
        cert.certificate_no?.toLowerCase().includes(term) ||
        cert.standard_name?.toLowerCase().includes(term);

      const meta = statusMeta(cert, styles);
      const matchesStatus =
        statusFilter === "all" ||
        (statusFilter === "expired" && meta.label === "Expired") ||
        (statusFilter === "expiring" && meta.label === "Expiring soon") ||
        (statusFilter === "active" && meta.label === "Active");

      return matchesSearch && matchesStatus;
    });
  }, [certificates, searchTerm, statusFilter]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / rowsPerPage));
  const paginated = filtered.slice(
    (currentPage - 1) * rowsPerPage,
    currentPage * rowsPerPage
  );

  const activeCount = certificates.filter((c) => statusMeta(c, styles).label === "Active").length;
  const expiringCount = certificates.filter((c) => statusMeta(c, styles).label === "Expiring soon").length;
  const expiredCount = certificates.filter((c) => statusMeta(c, styles).label === "Expired").length;

  const hasActiveFilters = searchTerm !== "" || statusFilter !== "all";

  const clearFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setCurrentPage(1);
  };

  const handleDownload = (cert: Certificate) => {
    if (!cert.scan_pdf_url) {
      toast.error("No PDF available for this certificate yet");
      return;
    }
    window.open(cert.scan_pdf_url, "_blank");
  };

  const handleDownloadAll = async () => {
    const withPdfs = certificates.filter((c) => c.scan_pdf_url);
    if (withPdfs.length === 0) {
      toast.error("No certificate PDFs available yet");
      return;
    }
    setDownloadingAll(true);
    withPdfs.forEach((cert, i) => {
      setTimeout(() => window.open(cert.scan_pdf_url, "_blank"), i * 400);
    });
    toast.success(`Opening ${withPdfs.length} certificate${withPdfs.length > 1 ? "s" : ""}`);
    setTimeout(() => setDownloadingAll(false), withPdfs.length * 400 + 200);
  };

  return (
    <div className={styles.container}>
      <style>{PREMIUM_CSS}</style>

      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>My certificates</h1>
          <p className={styles.subtitle}>
            View and download your certifications
            {certificates.length > 0 ? ` · ${certificates.length} total` : ""}
          </p>
        </div>
        <div className={styles.headerRight}>
          <button
            title="Download all certificate PDFs"
            onClick={handleDownloadAll}
            disabled={downloadingAll}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              padding: "8px 16px",
              background: "linear-gradient(135deg, #0f766e 0%, #14b8a6 100%)",
              color: "white",
              border: "none",
              borderRadius: 8,
              fontSize: "0.875rem",
              fontWeight: 600,
              cursor: downloadingAll ? "not-allowed" : "pointer",
              opacity: downloadingAll ? 0.7 : 1,
              boxShadow: "0 2px 8px rgba(15,118,110,0.3)",
              whiteSpace: "nowrap",
            }}
          >
            <FiDownload size={16} /> {downloadingAll ? "Opening..." : "Download all"}
          </button>
          <button className={styles.btnSecondary} onClick={fetchCertificates}>
            <FiRefreshCw className={styles.icon} /> Refresh
          </button>
        </div>
      </div>

      <div
        className="cp-rise"
        style={{
          background: "#fff",
          border: "1px solid #e2e8f0",
          // borderRadius: 20,
          padding: 22,
          marginBottom: 24,
          boxShadow: "0 2px 12px rgba(15,23,42,0.06), 0 12px 32px -18px rgba(15,23,42,0.14)",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
          <span style={{ width: 28, height: 28, borderRadius: 8, background: "rgba(139,20,212,0.10)", color: "#6a0dad", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <FiAward size={14} />
          </span>
          <span style={{ fontSize: 13, fontWeight: 700, color: "#334155" }}>Certificate overview</span>
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 12, color: "#94a3b8" }}>{certificates.length} certificates loaded</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
          <Kpi label="Digital Certificate" value={certificates.length} icon={<FiAward size={18} />} gradient="linear-gradient(135deg, #9b1de9 0%, #6a0dad 48%, #2c0560 100%)" shadow="rgba(74,0,128,0.25)" subtitle="Verified" delay={0} />
          <Kpi label="Active" value={activeCount} icon={<FiCheckCircle size={18} />} gradient="linear-gradient(135deg, #22c55e 0%, #15803d 100%)" shadow="rgba(21,128,61,0.25)" subtitle="currently valid" delay={1} />
          <Kpi label="Expiring soon" value={expiringCount} icon={<FiClock size={18} />} gradient="linear-gradient(135deg, #f59e0b 0%, #b45309 100%)" shadow="rgba(180,83,9,0.25)" subtitle="within 30 days" delay={2} />
          <Kpi label="Expired" value={expiredCount} icon={<FiXCircle size={18} />} gradient="linear-gradient(135deg, #ef4444 0%, #991b1b 100%)" shadow="rgba(153,27,27,0.25)" subtitle="need renewal" delay={3} />
        </div>
      </div>

      <div className={styles.toolbar}>
        <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
          <div className={styles.searchBox} style={{ flex: 1, minWidth: 240 }}>
            <span className={styles.searchIcon}>
              <FiSearch />
            </span>
            <input
              type="text"
              className={styles.searchInput}
              placeholder="Search by certificate number or standard..."
              value={searchTerm}
              onChange={(e) => {
                setSearchTerm(e.target.value);
                setCurrentPage(1);
              }}
            />
          </div>

          <select
            className={styles.filterSelect}
            value={statusFilter}
            onChange={(e) => {
              setStatusFilter(e.target.value);
              setCurrentPage(1);
            }}
          >
            {STATUS_OPTIONS.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>

          {hasActiveFilters && (
            <button className={styles.clearFiltersBtn} onClick={clearFilters}>
              ✕ Clear filters
            </button>
          )}
        </div>
      </div>

      {!loading && filtered.length > 0 && (
        <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>
              {(currentPage - 1) * rowsPerPage + 1}–
              {Math.min(currentPage * rowsPerPage, filtered.length)}
            </strong>{" "}
            of <strong>{filtered.length.toLocaleString()}</strong> certificates
          </span>
        </div>
      )}

      {loading ? (
        <div className={styles.errorContainer}>
          <p className={styles.errorMessage}>Loading certificates...</p>
        </div>
      ) : paginated.length === 0 ? (
        <div className={styles.emptyState}>
          <span>No certificates found</span>
        </div>
      ) : (
        <>
          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th className={styles.th}>Certificate</th>
                  <th className={styles.th}>Standard</th>
                  <th className={styles.th}>Issue date</th>
                  <th className={styles.th}>Expiry date</th>
                  <th className={styles.th}>Surveillance due</th>
                  <th className={styles.th}>Recertification due</th>
                  <th className={styles.th}>Status</th>
                  <th className={styles.actionsCol}>Actions</th>
                </tr>
              </thead>
              <tbody>
                {paginated.map((cert) => (
                  <CertificateRow key={cert.id} cert={cert} onDownload={handleDownload} />
                ))}
              </tbody>
            </table>
          </div>

          <div className={styles.pagination}>
            <div className={styles.paginationLeft}>
              <span className={styles.paginationText}>
                Showing <strong>{(currentPage - 1) * rowsPerPage + 1}</strong>–
                <strong>{Math.min(currentPage * rowsPerPage, filtered.length)}</strong> of{" "}
                <strong>{filtered.length}</strong>
              </span>
              <select
                className={styles.rowsPerPage}
                value={rowsPerPage}
                onChange={(e) => {
                  setRowsPerPage(Number(e.target.value));
                  setCurrentPage(1);
                }}
              >
                <option value={10}>10 / page</option>
                <option value={25}>25 / page</option>
                <option value={50}>50 / page</option>
              </select>
            </div>

            <div className={styles.paginationRight}>
              <button
                className={styles.pageBtn}
                disabled={currentPage === 1}
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
              >
                ‹
              </button>
              {getPageNumbers(currentPage, totalPages).map((p, idx) =>
                p === "..." ? (
                  <span key={`ellipsis-${idx}`} className={styles.pageEllipsis}>
                    ···
                  </span>
                ) : (
                  <button
                    key={p}
                    className={p === currentPage ? styles.activePageBtn : styles.pageBtn}
                    onClick={() => setCurrentPage(p)}
                  >
                    {p}
                  </button>
                )
              )}
              <button
                className={styles.pageBtn}
                disabled={currentPage === totalPages}
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
              >
                ›
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}