"use client";

// 🆕 Certificate Approvals — same datatable look as the Certificates module.
//   • Uses dattabale.module.css (header + table) and StatusBadge.
//   • Action buttons reuse styles.actionBtnView (same as certificate rows).
//   • WHO opens it → module permission (certificate-approvals).
//   • WHICH certs (QRS/TQS) → backend scoping via primary_scheme.
//   • WHICH buttons → useModulePermissions actions (qaqc-approve / qaqc-reject).

import { useState } from "react";
import styles from "../commonstyle/dattabale.module.css";
import { FiCheck, FiX, FiEye, FiRefreshCw } from "react-icons/fi";
import { useCertificateQaqc } from "@/lib/api/hooks/useCertificates";
import { useModulePermissions } from "@/lib/api/hooks/useModulePermissions";
import { StatusBadge } from "../certificates/components/certificates/CertificateBadges";
import type {
  CertificateRow,
  CertStatus,
  QaqcApprovedFilter,
} from "@/lib/api/types/certificate.types";

const baseBadge: React.CSSProperties = {
  display: "inline-block",
  padding: "3px 10px",
  borderRadius: 12,
  fontSize: 11,
  fontWeight: 700,
  letterSpacing: ".02em",
  lineHeight: 1.4,
  whiteSpace: "nowrap",
};

export default function CertificateQaqcQueue() {
  const {
    rows, approve, reject, scope, seesAll,
    page, setPage, lastPage, total,
    search, setSearch, approvedFilter, setApprovedFilter,
    loading, error, actioningId, refresh,
  } = useCertificateQaqc();

  const { canPerform } = useModulePermissions("certificate-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 scopeLabel = seesAll ? "All schemes" : scope ?? "No scheme assigned";

  const filters: { key: QaqcApprovedFilter; label: string }[] = [
    { key: "all", label: "All" },
    { key: "approved", label: "Visible (approved)" },
    { key: "pending", label: "Needs approval" },
  ];

  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 (
    <>
      {/* ═══ Header (same purple bar as Certificates Module) ═══ */}
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>Certificate Approvals</h1>
          <p className={styles.subtitle}>
            Review & approve certificates for {scopeLabel}
          </p>
        </div>
        <div className={styles.headerRight}>
          <button className={styles.btnSecondary} onClick={refresh} title="Refresh">
            <FiRefreshCw size={14} style={{ marginRight: 6 }} /> Refresh
          </button>
        </div>
      </div>

      <div className={styles.container}>
        {/* ═══ Filter chips + search ═══ */}
        <div
          style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            gap: 12, flexWrap: "wrap", marginBottom: 12,
          }}
        >
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {filters.map((f) => {
              const active = approvedFilter === f.key;
              return (
                <button
                  key={f.key}
                  onClick={() => { setPage(1); setApprovedFilter(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>
          <input
            value={search}
            onChange={(e) => { setPage(1); setSearch(e.target.value); }}
            placeholder="Search cert no or company…"
            style={{ padding: "9px 14px", border: "1px solid #e4e7f0", borderRadius: 8, fontSize: 14, minWidth: 260 }}
          />
        </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>
        )}

        {/* Record count bar (same teal style as Certificates) */}
        <div
          style={{
            padding: "10px 16px", backgroundColor: "#f0fdfa", border: "1px solid #99f6e4",
            borderRadius: 8, marginBottom: 12, fontSize: 13, color: "#0f766e",
          }}
        >
          📊 <strong>{total.toLocaleString()}</strong> certificate(s) · Page {page} / {lastPage || 1}
        </div>

        {/* ═══ TABLE ═══ */}
        <div className={styles.tableWrapper}>
          <table className={styles.table}>
            <thead>
              <tr>
                <th className={styles.th}>Cert No</th>
                <th className={styles.th}>Company</th>
                <th className={styles.th}>Scheme</th>
                <th className={styles.th}>Standard</th>
                <th className={styles.th}>Status</th>
                <th className={styles.th}>Client Visibility</th>
                <th className={styles.th}>Scan</th>
                <th className={styles.actionsCol}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={8} style={{ textAlign: "center", padding: 60, 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>
              ) : rows.length === 0 ? (
                <tr>
                  <td colSpan={8} style={{ textAlign: "center", padding: 60 }}>
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10 }}>
                      <div style={{ fontSize: 34 }}>📜</div>
                      <h3 style={{ margin: 0, color: "#111827" }}>No Certificates</h3>
                      <p style={{ color: "#6b7280", margin: 0 }}>Nothing to show for this scheme/filter.</p>
                    </div>
                  </td>
                </tr>
              ) : (
                rows.map((row: CertificateRow) => {
                  const busy = actioningId === row.id;
                  const approved = row.qaqc_approved === true;
                  const rejected = row.qaqc_approved === false && !!row.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" };
                  return (
                    <tr key={row.sno} className={styles.tableRow}>
                      <td className={styles.nameCell}><b>{row.certificate_no}</b></td>
                      <td className={styles.nameCell}>{row.company_name}</td>
                      <td className={styles.nameCell}>
                        <span style={{ ...baseBadge, color: row.scheme === "TQS" ? "#1d4ed8" : "#0a6e3d", backgroundColor: row.scheme === "TQS" ? "#dbeafe" : "#dcfce7" }}>
                          {row.scheme ?? "—"}
                        </span>
                      </td>
                      <td className={styles.nameCell}>{row.standard_short || row.standard_name}</td>
                      <td className={styles.nameCell}><StatusBadge status={row.status as CertStatus} /></td>
                      <td className={styles.nameCell}>
                        <span style={{ ...baseBadge, color: vis.color, backgroundColor: vis.bg }}>{vis.label}</span>
                        {rejected && row.qaqc_rejected_reason && (
                          <div style={{ fontSize: 11, color: "#9ca3af", marginTop: 4, maxWidth: 220 }}>{row.qaqc_rejected_reason}</div>
                        )}
                      </td>
                      <td className={styles.nameCell}>
                        {row.scan_pdf_url
                          ? <a href={row.scan_pdf_url} target="_blank" rel="noreferrer" style={{ color: "#0f766e", fontWeight: 600 }}>View</a>
                          : <span style={{ color: "#9ca3af" }}>—</span>}
                      </td>
                      <td className={styles.actionsCell}>
                        <div className={styles.actionGroup}>
                          {row.scan_pdf_url && (
                            <a className={styles.actionBtnView} href={row.scan_pdf_url} target="_blank" rel="noreferrer" title="View scan">
                              <FiEye size={13} />
                            </a>
                          )}
                          {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>

        {/* Pagination */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 8, marginTop: 14 }}>
          <button className={styles.btnSecondary} disabled={page <= 1} onClick={() => setPage(page - 1)} style={{ opacity: page <= 1 ? 0.5 : 1 }}>Prev</button>
          <span style={{ fontSize: 13, color: "#6b7280" }}>Page {page} / {lastPage || 1}</span>
          <button className={styles.btnSecondary} disabled={page >= lastPage} onClick={() => setPage(page + 1)} style={{ opacity: page >= lastPage ? 0.5 : 1 }}>Next</button>
        </div>
      </div>

      {/* Reject reason modal */}
      {rejectingId !== null && (
        <div style={overlay} onClick={() => setRejectingId(null)}>
          <div style={modal} onClick={(e) => e.stopPropagation()}>
            <h3 style={{ margin: "0 0 10px", fontSize: 16 }}>Reject certificate</h3>
            <p style={{ margin: "0 0 10px", fontSize: 13, color: "#6b7280" }}>This hides the certificate 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>
      )}
    </>
  );
}

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)" };