"use client";

// 🆕 Audit Report Approvals — full-column datatable (unchanged columns) with a
//   chevron on the Audit Code cell that opens a dropdown action menu
//   (View Stage 1/2/Attendance/Supporting · Approve · Reject). View opens files
//   through the scheme-scoped approvals route (no auditor-assignment 403).
//   Same Pagination + EnterpriseLoader as My Audits.

import React, { useEffect, useMemo, useRef, useState } from "react";
import toast from "react-hot-toast";
import styles from "../commonstyle/dattabale.module.css";
import { Pagination } from "../companies/Pagination";
import { EnterpriseLoader } from "../../../../components/loader/loader";
import {
  FiCheck, FiX, FiRefreshCw, FiFileText, FiExternalLink, FiFilter, FiChevronDown,
} from "react-icons/fi";
import { useAuditReportApprovals } from "@/lib/api/hooks/useAuditReportApprovals";
import { useModulePermissions } from "@/lib/api/hooks/useModulePermissions";
import { fetchApprovalReportBlob } from "@/lib/api/auditReportApproval.api";
import type { AuditReportRow, ReportApprovedFilter } from "@/lib/api/auditReportApproval.api";

type DocType = "stage1_report" | "stage2_report" | "attendance" | "support_docs";

const badge: React.CSSProperties = {
  display: "inline-block", padding: "3px 10px", borderRadius: 12, fontSize: 11,
  fontWeight: 700, letterSpacing: ".02em", lineHeight: 1.4, whiteSpace: "nowrap",
};
const fmtDate = (d: string | null) => {
  if (!d) return "—";
  const dt = new Date(d);
  return isNaN(dt.getTime()) ? d : dt.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" });
};
const monthName = (m: number) =>
  ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][m - 1] || "";

export default function AuditReportApprovalsPage() {
  const {
    rows, approve, reject, scope, seesAll,
    page, setPage, itemsPerPage, setItemsPerPage, lastPage, total,
    filters, setFilter, clearFilters,
    loading, error, actioningId, refresh,
  } = useAuditReportApprovals();

  const { canPerform } = useModulePermissions("audit-report-approvals");
  const mayApprove = seesAll || canPerform("qaqc-approve");
  const mayReject = seesAll || canPerform("qaqc-reject");

  const [rejectingId, setRejectingId] = useState<number | null>(null);
  const [reason, setReason] = useState<string>("");
  const [opening, setOpening] = useState<string | null>(null);

  // row action dropdown (screenshot-3 style, floating)
  const [menu, setMenu] = useState<{ id: number; x: number; y: number } | null>(null);
  const menuRef = useRef<HTMLDivElement | null>(null);
  useEffect(() => {
    if (!menu) return;
    const close = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) setMenu(null);
    };
    const onScroll = () => setMenu(null);
    document.addEventListener("mousedown", close);
    window.addEventListener("scroll", onScroll, true);
    window.addEventListener("resize", onScroll);
    return () => {
      document.removeEventListener("mousedown", close);
      window.removeEventListener("scroll", onScroll, true);
      window.removeEventListener("resize", onScroll);
    };
  }, [menu]);

  const [auditors, setAuditors] = useState<{ user_id: number; name: string }[]>([]);
  useEffect(() => {
    import("@/lib/api/audit-report.api")
      .then(({ getTransferAuditors }) => getTransferAuditors())
      .then((list) => setAuditors(list.map((u: any) => ({ user_id: u.user_id, name: u.name }))))
      .catch(() => {});
  }, []);

  const years = useMemo(() => {
    const y = new Date().getFullYear();
    return Array.from({ length: 7 }, (_, i) => y + 1 - i);
  }, []);

  const scopeLabel = seesAll ? "All schemes" : scope ?? "No scheme assigned";
  const chips: { key: ReportApprovedFilter; label: string }[] = [
    { key: "all", label: "All" },
    { key: "approved", label: "Visible (approved)" },
    { key: "pending", label: "Needs approval" },
  ];

  const openFile = async (rowId: number, docType: DocType) => {
    const key = `${rowId}-${docType}`;
    setOpening(key);
    try {
      const url = await fetchApprovalReportBlob(rowId, docType);
      window.open(url, "_blank", "noopener");
    } catch (e: any) {
      toast.error(e?.message ?? "Could not open file");
    } finally {
      setOpening(null);
    }
  };

  const hasFilters = !!(filters.search || filters.auditorId || filters.auditType || filters.status || filters.year || filters.month || filters.from || filters.to);
  const COLS = 12;

  const openMenu = (e: React.MouseEvent, id: number) => {
    e.stopPropagation();
    const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
    const width = 240;
    setMenu((m) => (m?.id === id ? null : { id, x: Math.min(r.left, window.innerWidth - width - 12), y: r.bottom + 4 }));
  };
  const menuRow = menu ? rows.find((r) => r.id === menu.id) : null;

  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.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>Audit Report Approvals</h1>
          <p className={styles.subtitle}>Review & approve audit reports for {scopeLabel}</p>
        </div>
        <div className={styles.headerRight}>
          <button className={styles.btnSecondary} onClick={refresh} title="Refresh"
            style={{ background: "rgba(255,255,255,0.15)", color: "#fff", border: "1px solid rgba(255,255,255,0.3)" }}>
            <FiRefreshCw size={14} style={{ marginRight: 6 }} /> Refresh
          </button>
        </div>
      </div>

      <div className={styles.container}>
        {/* ── Filter bar ── */}
        <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 12, padding: "14px 16px", marginBottom: 12 }}>
          <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 10 }}>
            <input
              value={filters.search ?? ""}
              onChange={(e) => setFilter({ search: e.target.value })}
              placeholder="Search audit code or company…"
              style={{ flex: 1, padding: "10px 12px", border: "1px solid #e2e8f0", borderRadius: 8, fontSize: 13, outline: "none" }}
            />
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 700, color: "#0f766e" }}>
              <FiFilter size={13} /> FILTERS
            </span>
            <Sel value={String(filters.auditorId ?? "")} onChange={(v) => setFilter({ auditorId: v || undefined })}
              placeholder={`All Auditors${auditors.length ? ` (${auditors.length})` : ""}`}
              options={auditors.map((a) => ({ value: String(a.user_id), label: a.name }))} minWidth={190} />
            <Sel value={filters.auditType ?? ""} onChange={(v) => setFilter({ auditType: v || undefined })}
              placeholder="All Types"
              options={[{ value: "INITIAL", label: "Initial" }, { value: "SURVEILLANCE", label: "Surveillance" }, { value: "RECERTIFICATION", label: "Recertification" }]} />
            <Sel value={filters.status ?? ""} onChange={(v) => setFilter({ status: v || undefined })}
              placeholder="Any Report Status"
              options={[
                { value: "s1_uploaded", label: "Stage 1 uploaded" },
                { value: "s1_missing", label: "Stage 1 missing" },
                { value: "s2_uploaded", label: "Stage 2 uploaded" },
                { value: "s2_missing", label: "Stage 2 missing" },
              ]} minWidth={160} />
            <Sel value={String(filters.year ?? "")} onChange={(v) => setFilter({ year: v || undefined })}
              placeholder="All Years" options={years.map((y) => ({ value: String(y), label: String(y) }))} minWidth={110} />
            <Sel value={String(filters.month ?? "")} onChange={(v) => setFilter({ month: v || undefined })}
              placeholder="All Months" options={Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1), label: monthName(i + 1) }))} minWidth={120} />
            <label style={{ fontSize: 12, color: "#64748b" }}>From&nbsp;
              <input type="date" value={filters.from ?? ""} onChange={(e) => setFilter({ from: e.target.value || undefined })}
                style={{ padding: "7px 8px", border: "1px solid #e2e8f0", borderRadius: 8, fontSize: 12.5 }} />
            </label>
            <label style={{ fontSize: 12, color: "#64748b" }}>To&nbsp;
              <input type="date" value={filters.to ?? ""} onChange={(e) => setFilter({ to: e.target.value || undefined })}
                style={{ padding: "7px 8px", border: "1px solid #e2e8f0", borderRadius: 8, fontSize: 12.5 }} />
            </label>
            {hasFilters && (
              <button onClick={clearFilters}
                style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "8px 12px", border: "1px solid #e2e8f0", borderRadius: 8, background: "#fff", color: "#64748b", fontSize: 12, fontWeight: 700, cursor: "pointer" }}>
                <FiX size={12} /> Clear
              </button>
            )}
          </div>
        </div>

        {/* approval chips */}
        <div style={{ display: "flex", gap: 8, marginBottom: 12, flexWrap: "wrap" }}>
          {chips.map((f) => {
            const active = (filters.approved ?? "all") === f.key;
            return (
              <button key={f.key} onClick={() => setFilter({ approved: f.key })}
                style={{
                  padding: "7px 14px", borderRadius: 999, fontSize: 13, fontWeight: 600, cursor: "pointer",
                  border: active ? "1px solid #0f766e" : "1px solid #e4e7f0",
                  background: active ? "#0f766e" : "#fff", color: active ? "#fff" : "#374151",
                }}>
                {f.label}
              </button>
            );
          })}
        </div>

        {!seesAll && !scope && (
          <div style={{ padding: 12, borderRadius: 8, background: "#fffbeb", border: "1px solid #fde68a", color: "#92400e", marginBottom: 12, fontSize: 13 }}>
            Your account has no scheme assigned, so there is nothing to manage. Ask an admin to set your scheme (QRS or TQS).
          </div>
        )}

        <div style={{ padding: "10px 16px", backgroundColor: "#f0fdfa", border: "1px solid #99f6e4", borderRadius: 8, marginBottom: 12, fontSize: 13, color: "#0f766e" }}>
          📋 <strong>{total.toLocaleString()}</strong> audit(s) · Page {page} / {lastPage || 1}{hasFilters ? " · Filtered" : ""}
        </div>

        <div className={styles.tableWrapper}>
          <table className={styles.table}>
            <thead>
              <tr>
                <th className={styles.th}>Audit Code</th>
                <th className={styles.th}>Company</th>
                <th className={styles.th}>Auditor</th>
                <th className={styles.th}>Audit Date</th>
                <th className={styles.th}>Type</th>
                <th className={styles.th} style={{ textAlign: "center" }}>Stage 1</th>
                <th className={styles.th} style={{ textAlign: "center" }}>Stage 2</th>
                <th className={styles.th} style={{ textAlign: "center" }}>Attendance</th>
                <th className={styles.th} style={{ textAlign: "center" }}>Supporting</th>
                <th className={styles.th}>Scheme</th>
                <th className={styles.th}>Client Visibility</th>
                <th className={styles.actionsCol}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={COLS} style={{ textAlign: "center", padding: 60 }}><EnterpriseLoader /></td></tr>
              ) : rows.length === 0 ? (
                <tr><td colSpan={COLS} style={{ textAlign: "center", padding: 60 }}>
                  <div style={{ fontSize: 34 }}>📄</div>
                  <h3 style={{ margin: "10px 0 2px", color: "#111827" }}>No Audits</h3>
                  <p style={{ color: "#6b7280", margin: 0 }}>Nothing matches this scheme/filter.</p>
                </td></tr>
              ) : (
                rows.map((row: AuditReportRow) => {
                  const busy = actioningId === row.id;
                  const approved = row.report_qaqc_approved === true || row.report_qaqc_approved === 1;
                  const rejected = !approved && !!row.report_qaqc_rejected_reason;
                  const vis = approved
                    ? { label: "Visible", color: "#166534", bg: "#dcfce7" }
                    : rejected
                    ? { label: "Hidden — rejected", color: "#991b1b", bg: "#fef2f2" }
                    : { label: "Hidden — pending", color: "#92400e", bg: "#fef3c7" };
                  const active = menu?.id === row.id;
                  return (
                    <tr key={row.id} className={styles.tableRow}>
                      <td className={styles.nameCell}>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                          <button onClick={(e) => openMenu(e, row.id)} title="Actions"
                            style={{ border: `1px solid ${active ? "#7c3aed" : "#e2e8f0"}`, background: active ? "#f5f3ff" : "#fff", borderRadius: 6, width: 24, height: 24, display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0 }}>
                            <FiChevronDown size={13} style={{ color: active ? "#7c3aed" : "#64748b", transition: "transform .15s", transform: active ? "rotate(180deg)" : "none" }} />
                          </button>
                          <b>{row.audit_code}</b>
                        </span>
                      </td>
                      <td className={styles.nameCell}>{row.company_name}</td>
                      <td className={styles.nameCell}>{row.auditor_name}</td>
                      <td className={styles.nameCell}>{fmtDate(row.audit_date)}</td>
                      <td className={styles.nameCell}>{row.audit_type ?? "—"}</td>
                      <td className={styles.nameCell} style={{ textAlign: "center" }}>
                        <FileCell path={row.stg1_audit_report} busy={opening === `${row.id}-stage1_report`} onOpen={() => openFile(row.id, "stage1_report")} missingLabel />
                      </td>
                      <td className={styles.nameCell} style={{ textAlign: "center" }}>
                        <FileCell path={row.stg2_audit_report} busy={opening === `${row.id}-stage2_report`} onOpen={() => openFile(row.id, "stage2_report")} missingLabel />
                      </td>
                      <td className={styles.nameCell} style={{ textAlign: "center" }}>
                        <FileCell path={row.attendance_doc} busy={opening === `${row.id}-attendance`} onOpen={() => openFile(row.id, "attendance")} />
                      </td>
                      <td className={styles.nameCell} style={{ textAlign: "center" }}>
                        <FileCell path={row.support_docs} busy={opening === `${row.id}-support_docs`} onOpen={() => openFile(row.id, "support_docs")} />
                      </td>
                      <td className={styles.nameCell}>
                        <span style={{ ...badge, color: row.scheme === "TQS" ? "#1d4ed8" : "#0a6e3d", backgroundColor: row.scheme === "TQS" ? "#dbeafe" : "#dcfce7" }}>{row.scheme ?? "—"}</span>
                      </td>
                      <td className={styles.nameCell}>
                        <span style={{ ...badge, color: vis.color, backgroundColor: vis.bg }}>{vis.label}</span>
                        {rejected && row.report_qaqc_rejected_reason && (
                          <div style={{ fontSize: 11, color: "#9ca3af", marginTop: 4, maxWidth: 200 }}>{row.report_qaqc_rejected_reason}</div>
                        )}
                      </td>
                      <td className={styles.actionsCell}>
                        <div className={styles.actionGroup}>
                          {mayApprove && (
                            <button className={styles.actionBtnView}
                              style={{ color: "#166534", borderColor: "#86efac", background: "#f0fdf4", opacity: approved || busy ? 0.5 : 1, cursor: approved || busy ? "not-allowed" : "pointer" }}
                              disabled={approved || busy} onClick={() => approve(row.id)}
                              title={approved ? "Already approved" : "Approve (show to client)"}>
                              <FiCheck size={13} />
                            </button>
                          )}
                          {mayReject && (
                            <button className={styles.actionBtnView}
                              style={{ color: "#b91c1c", borderColor: "#fca5a5", background: "#fef2f2", opacity: !approved || busy ? 0.5 : 1, cursor: !approved || busy ? "not-allowed" : "pointer" }}
                              disabled={!approved || busy} onClick={() => { setRejectingId(row.id); setReason(""); }}
                              title={!approved ? "Already hidden" : "Reject (hide from client)"}>
                              <FiX size={13} />
                            </button>
                          )}
                          {!mayApprove && !mayReject && (
                            <span style={{ fontSize: 11, color: "#9ca3af", fontStyle: "italic" }}>view only</span>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

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

      {/* ── floating action dropdown (screenshot-3 style) ── */}
      {menu && menuRow && (() => {
        const approved = menuRow.report_qaqc_approved === true || menuRow.report_qaqc_approved === 1;
        const items: { label: string; type: DocType }[] = [
          { label: "Stage 1 Report", type: "stage1_report" },
          { label: "Stage 2 Report", type: "stage2_report" },
          { label: "Attendance", type: "attendance" },
          { label: "Supporting Docs", type: "support_docs" },
        ];
        const pathOf = (t: DocType) =>
          t === "stage1_report" ? menuRow.stg1_audit_report
          : t === "stage2_report" ? menuRow.stg2_audit_report
          : t === "attendance" ? menuRow.attendance_doc
          : menuRow.support_docs;
        return (
          <div ref={menuRef} style={{ position: "fixed", left: menu.x, top: menu.y, width: 240, background: "#fff", borderRadius: 12, boxShadow: "0 12px 34px rgba(0,0,0,0.18)", border: "1px solid #eef0f4", zIndex: 1200, overflow: "hidden" }}>
            <div style={menuHead}>VIEW REPORTS</div>
            {items.map((it) => {
              const has = !!pathOf(it.type);
              return (
                <button key={it.type} disabled={!has}
                  onClick={() => { openFile(menuRow.id, it.type); setMenu(null); }}
                  style={{ ...menuItem, color: has ? "#111827" : "#c0c4cc", cursor: has ? "pointer" : "not-allowed" }}>
                  <FiFileText size={15} style={{ color: has ? "#6d28d9" : "#cbd5e1" }} />
                  <span style={{ flex: 1, textAlign: "left" }}>{it.label}</span>
                  {has ? <FiExternalLink size={12} style={{ opacity: 0.6 }} /> : <span style={{ fontSize: 10, fontWeight: 700, color: "#dc2626" }}>Missing</span>}
                </button>
              );
            })}
            {(mayApprove || mayReject) && <div style={menuHead}>ACTIONS</div>}
            {mayApprove && (
              <button disabled={approved} onClick={() => { approve(menuRow.id); setMenu(null); }}
                style={{ ...menuItem, color: approved ? "#c0c4cc" : "#166534", cursor: approved ? "not-allowed" : "pointer" }}>
                <FiCheck size={15} style={{ color: approved ? "#cbd5e1" : "#16a34a" }} />
                <span style={{ flex: 1, textAlign: "left" }}>Approve</span>
              </button>
            )}
            {mayReject && (
              <button disabled={!approved} onClick={() => { setRejectingId(menuRow.id); setReason(""); setMenu(null); }}
                style={{ ...menuItem, color: !approved ? "#c0c4cc" : "#b91c1c", cursor: !approved ? "not-allowed" : "pointer" }}>
                <FiX size={15} style={{ color: !approved ? "#cbd5e1" : "#dc2626" }} />
                <span style={{ flex: 1, textAlign: "left" }}>Reject</span>
              </button>
            )}
          </div>
        );
      })()}

      {rejectingId !== null && (
        <div style={overlay} onClick={() => setRejectingId(null)}>
          <div style={modal} onClick={(e) => e.stopPropagation()}>
            <h3 style={{ margin: "0 0 10px", fontSize: 16 }}>Reject audit report</h3>
            <p style={{ margin: "0 0 10px", fontSize: 13, color: "#6b7280" }}>This hides the report from the client portal.</p>
            <textarea value={reason} onChange={(e) => setReason(e.target.value)} placeholder="Reason (optional)…" rows={4}
              style={{ width: "100%", padding: 10, border: "1px solid #e4e7f0", borderRadius: 8, fontSize: 14, resize: "vertical" }} />
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
              <button className={styles.btnSecondary} onClick={() => setRejectingId(null)}>Cancel</button>
              <button className={styles.btnPrimary} style={{ background: "linear-gradient(135deg,#ef4444,#b91c1c)", border: "none" }}
                onClick={async () => { if (rejectingId !== null) { await reject(rejectingId, reason); } setRejectingId(null); }}>
                Confirm reject
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function FileCell({ path, busy, onOpen, missingLabel }: { path: string | null; busy: boolean; onOpen: () => void; missingLabel?: boolean }) {
  if (path) {
    return (
      <button onClick={onOpen} disabled={busy} title="Open report"
        style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 10px", borderRadius: 6, border: "1px solid #86efac", background: "#f0fdf4", color: "#15803d", fontSize: 11, fontWeight: 700, cursor: busy ? "wait" : "pointer" }}>
        <FiFileText size={12} /> {busy ? "…" : "View"} <FiExternalLink size={10} style={{ opacity: 0.7 }} />
      </button>
    );
  }
  if (missingLabel) {
    return <span style={{ display: "inline-flex", padding: "4px 10px", borderRadius: 6, border: "1px solid #fecaca", background: "#fef2f2", color: "#dc2626", fontSize: 11, fontWeight: 700 }}>Missing</span>;
  }
  return <span style={{ color: "#9ca3af" }}>—</span>;
}

function Sel({ value, onChange, options, placeholder, minWidth = 140 }: { value: string; onChange: (v: string) => void; options: { value: string; label: string }[]; placeholder: string; minWidth?: number }) {
  const active = !!value;
  return (
    <select value={value} onChange={(e) => onChange(e.target.value)}
      style={{ appearance: "none", backgroundColor: active ? "#f0fdfa" : "#fff", border: `1px solid ${active ? "#0f766e" : "#e2e8f0"}`, borderRadius: 8, padding: "8px 11px", fontSize: 12.5, fontWeight: 600, color: active ? "#0f766e" : "#374151", cursor: "pointer", minWidth, height: 38, outline: "none" }}>
      <option value="">{placeholder}</option>
      {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
  );
}

const menuHead: React.CSSProperties = { padding: "9px 14px 5px", fontSize: 10.5, fontWeight: 800, color: "#9aa2b1", letterSpacing: "0.06em", textTransform: "uppercase" };
const menuItem: React.CSSProperties = { width: "100%", display: "flex", alignItems: "center", gap: 10, padding: "9px 14px", border: "none", background: "transparent", fontSize: 13.5, fontWeight: 600 };
const overlay: React.CSSProperties = { position: "fixed", inset: 0, background: "rgba(0,0,0,0.4)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1000 };
const modal: React.CSSProperties = { background: "#fff", borderRadius: 12, padding: 20, width: "min(440px, 92vw)", boxShadow: "0 20px 50px rgba(0,0,0,0.25)" };