"use client";

import React, { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import {
  FiSearch, FiRefreshCw, FiAlertTriangle, FiCheckCircle,
  FiClock, FiShield, FiArrowRight,
} from "react-icons/fi";
import { clientPortalApi } from "@/lib/api/clientPortalApi";
import styles from "../../../(dashboard)/modules/commonstyle/dattabale.module.css";

interface Finding {
  id: number;
  nc_type?: string;
  ncr_statement?: string;
  criteria_clause?: string;
  corrective_action?: string;
  status?: string;
}

interface Nc {
  id: number;
  audit_id?: number;
  auditee_name?: string;
  audit_type?: string;
  nc_type?: string;
  status?: string;
  follow_up_date?: string;
  due_date?: string;
  closed_at?: string;
  created_at?: string;
  findings?: Finding[];
  // from /ncs/list — finding counts
  findings_total?: number;
  findings_open?: number;
  findings_pending?: number;
  findings_closed?: number;
}

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 [];
}

function ncCode(id: number): string {
  return "NC-" + String(id).padStart(5, "0");
}

function isOverdue(nc: Nc): boolean {
  if (nc.status === "closed" || !nc.due_date) return false;
  return new Date(nc.due_date).getTime() < Date.now();
}

function formatDate(dateStr?: string): string {
  if (!dateStr) return "\u2014";
  const d = new Date(dateStr);
  if (isNaN(d.getTime())) return "\u2014";
  return d.getDate() + " " + d.toLocaleString("en-US", { month: "short" }) + " " + d.getFullYear();
}

function typeMeta(ncType?: string): { bg: string; color: string } {
  const t = (ncType || "").toLowerCase();
  if (t.includes("major")) return { bg: "#fef2f2", color: "#991b1b" };
  if (t.includes("minor")) return { bg: "#fffbeb", color: "#92400e" };
  if (t.includes("observ")) return { bg: "#eff6ff", color: "#1e40af" };
  return { bg: "#f3f4f6", color: "#4b5563" };
}

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,
        padding: "18px",
        color: "#fff",
        minHeight: 100,
        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: 44, height: 44, 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, fontWeight: 600, color: "rgba(255,255,255,0.92)" }}>{label}</div>
        <div style={{ fontSize: 24, fontWeight: 800, fontFamily: "'Cabinet Grotesk', 'Plus Jakarta Sans', sans-serif", lineHeight: 1.2 }}>{animated}</div>
        <div style={{ fontSize: 11, color: "rgba(255,255,255,0.68)", fontWeight: 500 }}>{subtitle}</div>
      </div>
    </div>
  );
}

export default function NcsPage() {
  const router = useRouter();
  const [ncs, setNcs] = useState<Nc[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

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

  const fetchNcs = async () => {
    try {
      setLoading(true);
      const response = await clientPortalApi.getNcsList();
      setNcs(extractArray(response));
    } catch (error) {
      toast.error("Failed to load non-conformities");
    } finally {
      setLoading(false);
    }
  };

  const filtered = useMemo(() => {
    const term = searchTerm.toLowerCase();
    return ncs.filter((nc) => {
      const matchesSearch =
        !term ||
        ncCode(nc.id).toLowerCase().includes(term) ||
        nc.nc_type?.toLowerCase().includes(term) ||
        nc.auditee_name?.toLowerCase().includes(term);
      const matchesStatus =
        statusFilter === "all" ||
        (statusFilter === "open" && nc.status === "open") ||
        (statusFilter === "closed" && nc.status === "closed") ||
        (statusFilter === "overdue" && isOverdue(nc));
      return matchesSearch && matchesStatus;
    });
  }, [ncs, searchTerm, statusFilter]);

  const openCount = ncs.filter((n) => n.status === "open").length;
  const closedCount = ncs.filter((n) => n.status === "closed").length;
  const overdueCount = ncs.filter((n) => isOverdue(n)).length;

  if (loading) {
    return (
      <div className={styles.errorContainer}>
        <p className={styles.errorMessage}>Loading non-conformities...</p>
      </div>
    );
  }

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

      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>Non-conformities</h1>
          <p className={styles.subtitle}>
            Findings raised during your audits, with required corrective actions
            {ncs.length > 0 ? " \u00b7 " + ncs.length + " total" : ""}
          </p>
        </div>
        <div className={styles.headerRight}>
          <button className={styles.btnSecondary} onClick={fetchNcs}>
            <FiRefreshCw className={styles.icon} /> Refresh
          </button>
        </div>
      </div>

      <div
        className="cp-rise"
        style={{
          background: "#fff",
          border: "1px solid #e2e8f0",
          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 }}>
            <FiShield size={14} />
          </span>
          <span style={{ fontSize: 13, fontWeight: 700, color: "#334155" }}>NC overview</span>
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 12, color: "#94a3b8" }}>{ncs.length} NCs loaded</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
          <Kpi label="Total NCs" value={ncs.length} icon={<FiShield size={18} />} gradient="linear-gradient(135deg, #9b1de9 0%, #6a0dad 48%, #2c0560 100%)" shadow="rgba(74,0,128,0.25)" subtitle="on file" delay={0} />
          <Kpi label="Open" value={openCount} icon={<FiAlertTriangle size={18} />} gradient="linear-gradient(135deg, #f59e0b 0%, #b45309 100%)" shadow="rgba(180,83,9,0.25)" subtitle="need corrective action" delay={1} />
          <Kpi label="Overdue" value={overdueCount} icon={<FiClock size={18} />} gradient="linear-gradient(135deg, #ef4444 0%, #991b1b 100%)" shadow="rgba(153,27,27,0.25)" subtitle="past due date" delay={2} />
          <Kpi label="Closed" value={closedCount} icon={<FiCheckCircle size={18} />} gradient="linear-gradient(135deg, #22c55e 0%, #15803d 100%)" shadow="rgba(21,128,61,0.25)" subtitle="resolved" delay={3} />
        </div>
      </div>

      <div className={styles.toolbar}>
        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          <div className={styles.searchBox} style={{ flex: 1 }}>
            <span className={styles.searchIcon}>
              <FiSearch />
            </span>
            <input
              type="text"
              className={styles.searchInput}
              placeholder="Search by NC number or type..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
          <select className={styles.filterSelect} value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
            <option value="all">All statuses</option>
            <option value="open">Open</option>
            <option value="overdue">Overdue</option>
            <option value="closed">Closed</option>
          </select>
        </div>
      </div>

      {filtered.length === 0 ? (
        <div className={styles.emptyState}>
          <span>{ncs.length === 0 ? "No non-conformities on file" : "No NCs match this filter"}</span>
        </div>
      ) : (
        <div className={styles.tableWrapper}>
          <table className={styles.table}>
            <thead>
              <tr>
                <th className={styles.th}>NC Code</th>
                <th className={styles.th}>Audit type</th>
                <th className={styles.th}>Date raised</th>
                <th className={styles.th}>NC type</th>
                <th className={styles.th}>Findings</th>
                <th className={styles.th}>Status</th>
                <th className={styles.actionsCol}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((nc) => {
                const tMeta = typeMeta(nc.nc_type);
                const overdue = isOverdue(nc);
                return (
                  <tr key={nc.id}>
                    <td className={styles.idCell}>
                      <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                        <span style={{ fontFamily: "'Fraunces', serif", fontWeight: 600, color: "#4a0080" }}>{ncCode(nc.id)}</span>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 4, width: "fit-content", fontSize: 10, fontWeight: 700, padding: "2px 8px", borderRadius: 6, background: "#f3eefb", color: "#6d28d9" }}>NEW</span>
                      </div>
                    </td>
                    <td>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, color: "#475569", background: "#f8fafc", border: "1px solid #e2e8f0", padding: "5px 11px", borderRadius: 8 }}>
                        {nc.audit_type || "Audit"}
                      </span>
                    </td>
                    <td>
                      <div style={{ fontSize: 13, fontWeight: 600, color: "#334155" }}>{formatDate(nc.created_at || nc.due_date)}</div>
                      {nc.auditee_name && <div style={{ fontSize: 11, color: "#94a3b8" }}>{nc.auditee_name}</div>}
                    </td>
                    <td>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 5, background: tMeta.bg, color: tMeta.color, fontSize: 11, fontWeight: 700, padding: "4px 11px", borderRadius: 99 }}>
                        <span style={{ width: 6, height: 6, borderRadius: 99, background: tMeta.color }} />
                        {nc.nc_type || "\u2014"}
                      </span>
                    </td>
                    <td>
                      <span style={{ fontWeight: 700, color: "#1e293b" }}>{nc.findings_total ?? (nc.findings || []).length}</span>
                      {(nc.findings_open || 0) + (nc.findings_pending || 0) > 0 && (
                        <span style={{ marginLeft: 7, fontSize: 10, fontWeight: 700, padding: "2px 8px", borderRadius: 99, background: "#fef3c7", color: "#92400e" }}>
                          {(nc.findings_open || 0) + (nc.findings_pending || 0)} to respond
                        </span>
                      )}
                    </td>
                    <td>
                      <span className={styles.statusBadge + " " + (nc.status === "closed" ? styles.statusCompleted : styles.statusReview)}>
                        <span className={styles.statusDot} />
                        {nc.status === "closed" ? "Closed" : "Open"}
                      </span>
                      {overdue && (
                        <span style={{ marginLeft: 6, fontSize: 10, fontWeight: 700, padding: "1px 6px", borderRadius: 99, background: "#dc2626", color: "#fff" }}>
                          OVERDUE
                        </span>
                      )}
                    </td>
                    <td className={styles.actionsCell}>
                      <div className={styles.actionGroup}>
                        <button
                          onClick={() => router.push("/client/dashboard/ncs/" + nc.id)}
                          title="View & respond"
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 6,
                            padding: "7px 15px",
                            borderRadius: 9,
                            border: "none",
                            cursor: "pointer",
                            fontSize: 12.5,
                            fontWeight: 700,
                            color: "#fff",
                            background: "linear-gradient(135deg, #7c3aed, #4a0080)",
                            boxShadow: "0 8px 18px -10px rgba(74,0,128,0.7)",
                            fontFamily: "inherit",
                          }}
                        >
                          View <FiArrowRight size={13} />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}