"use client";

/**
 * Companies → View company → 📁 Documents (2026-11-10).
 * Lists the Job Registrar document packs generated for this company (per audit + stage) and opens the
 * Generate documents popup. Packs generate in the background; the list polls until they finish.
 */
import React, { useCallback, useEffect, useState } from "react";
import toast from "react-hot-toast";
import { FiAlertTriangle, FiDownload, FiEye, FiFolder, FiLoader, FiPlus, FiRefreshCw } from "react-icons/fi";
import {
  getCompanyDocuments,
  openPackFile,
  type CompanyDocumentsResponse,
  type DocumentPack,
} from "@/lib/api/company-documents.api";
import GenerateDocumentsModal from "./GenerateDocumentsModal";

const STATUS: Record<DocumentPack["status"], { label: string; bg: string; fg: string; bd: string }> = {
  queued: { label: "Queued", bg: "#f8fafc", fg: "#475569", bd: "#e2e8f0" },
  generating: { label: "Generating…", bg: "#eff6ff", fg: "#1d4ed8", bd: "#bfdbfe" },
  done: { label: "Ready", bg: "#ecfdf5", fg: "#047857", bd: "#a7f3d0" },
  partial: { label: "Partly ready", bg: "#fffbeb", fg: "#b45309", bd: "#fde68a" },
  failed: { label: "Failed", bg: "#fef2f2", fg: "#b91c1c", bd: "#fecaca" },
};

const fmt = (d?: string | null) =>
  d ? new Date(d.length <= 10 ? d + "T00:00:00" : d).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }) : "—";

export default function CompanyDocumentsPanel({ companyId, companyName }: { companyId: number; companyName: string }) {
  const [data, setData] = useState<CompanyDocumentsResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [showGen, setShowGen] = useState(false);
  const [regen, setRegen] = useState<DocumentPack | null>(null);
  const [open, setOpen] = useState<number | null>(null);

  const load = useCallback(async () => {
    try {
      const r = await getCompanyDocuments(companyId);
      setData(r);
      setError(null);
    } catch (e: any) {
      setError(e?.message || "Could not load documents");
    } finally {
      setLoading(false);
    }
  }, [companyId]);

  useEffect(() => {
    setLoading(true);
    load();
  }, [load]);

  // poll while something is generating
  const busy = !!data?.packs.some((p) => p.status === "queued" || p.status === "generating");
  useEffect(() => {
    if (!busy) return;
    const t = setInterval(load, 3000);
    return () => clearInterval(t);
  }, [busy, load]);

  const file = async (p: DocumentPack, which: string, name: string, download = false) => {
    try {
      await openPackFile(p.id, which, name, download);
    } catch (e: any) {
      toast.error(e?.message || "Could not open the file");
    }
  };

  if (loading) return <div style={{ fontSize: 12.5, color: "#94a3b8", padding: "8px 2px" }}>Loading documents…</div>;
  if (error) {
    return (
      <div style={{ fontSize: 12.5, color: "#94a3b8", padding: "8px 2px" }}>
        {/forbidden|only admin/i.test(error) ? "Documents are available to admin, scheme and coordinator users." : error}
      </div>
    );
  }
  if (!data) return null;

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, marginBottom: 10, flexWrap: "wrap" }}>
        <span style={{ fontSize: 12.5, color: "#64748b" }}>
          {data.packs.length ? `${data.packs.length} document pack${data.packs.length > 1 ? "s" : ""}` : "No documents generated yet"} · {data.audits.length} audit{data.audits.length !== 1 ? "s" : ""} in Audit Schedule
        </span>
        <button
          onClick={() => {
            setRegen(null);
            setShowGen(true);
          }}
          style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 9, border: "none", background: "linear-gradient(135deg,#2563eb,#7c3aed)", color: "#fff", fontWeight: 800, fontSize: 12.5, cursor: "pointer", boxShadow: "0 4px 12px -6px rgba(37,99,235,.8)" }}
        >
          <FiPlus size={14} /> Generate documents
        </button>
      </div>

      <div style={{ display: "grid", gap: 8 }}>
        {data.packs.map((p) => {
          const st = STATUS[p.status] ?? STATUS.queued;
          const done = p.forms.filter((f) => f.status === "done").length;
          const isOpen = open === p.id;
          const working = p.status === "queued" || p.status === "generating";
          return (
            <div key={p.id} style={{ border: "1px solid #e2e8f0", borderRadius: 12, overflow: "hidden", background: "#fff" }}>
              <div onClick={() => setOpen(isOpen ? null : p.id)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", cursor: "pointer", background: isOpen ? "#f8fbff" : "#fff", flexWrap: "wrap" }}>
                <div style={{ width: 34, height: 34, borderRadius: 9, background: p.stage === "stage1" ? "linear-gradient(135deg,#0891b2,#2563eb)" : "linear-gradient(135deg,#7c3aed,#db2777)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  <FiFolder size={16} />
                </div>
                <div style={{ flex: 1, minWidth: 180 }}>
                  <div style={{ fontSize: 13, fontWeight: 800, color: "#0f172a" }}>
                    {p.stage === "stage1" ? "Stage 1" : "Stage 2"} pack · <span style={{ fontFamily: "monospace", color: "#1d4ed8" }}>{p.job_code || "job no. pending"}</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: "#64748b" }}>
                    {p.audit_code || `Audit #${p.audit_schedule_row_id}`} · audit {fmt(p.schedule_date)} · {done}/{p.forms.length} documents · v{p.version}
                    {p.created_by_name ? ` · by ${p.created_by_name}` : ""}
                  </div>
                </div>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 10px", borderRadius: 99, background: st.bg, color: st.fg, border: `1px solid ${st.bd}`, fontSize: 11, fontWeight: 800 }}>
                  {working && <FiLoader size={11} style={{ animation: "cdpspin 1s linear infinite" }} />} {st.label}
                </span>
                {p.has_zip && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      file(p, "zip", `${(p.job_code || "documents").replace(/[^A-Za-z0-9_-]+/g, "_")}_${p.stage}.zip`, true);
                    }}
                    style={btn("#047857", "#ecfdf5", "#a7f3d0")}
                  >
                    <FiDownload size={13} /> ZIP
                  </button>
                )}
                {!working && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setRegen(p);
                      setShowGen(true);
                    }}
                    style={btn("#334155", "#fff", "#e2e8f0")}
                    title="Change the details and generate again (same job number)"
                  >
                    <FiRefreshCw size={13} /> Regenerate
                  </button>
                )}
              </div>
              {working && (
                <div style={{ height: 4, background: "#eff6ff" }}>
                  <div style={{ height: 4, width: `${p.forms.length ? Math.max(6, (done / p.forms.length) * 100) : 6}%`, background: "linear-gradient(90deg,#2563eb,#7c3aed)", transition: "width .4s" }} />
                </div>
              )}
              {isOpen && (
                <div style={{ padding: "8px 12px 12px", borderTop: "1px solid #f1f5f9", display: "grid", gap: 6 }}>
                  {p.error && (
                    <div style={{ fontSize: 12, color: "#b91c1c", display: "flex", gap: 6, alignItems: "center" }}>
                      <FiAlertTriangle /> {p.error}
                    </div>
                  )}
                  {p.forms.map((f) => (
                    <div key={f.key} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 8px", borderRadius: 8, background: "#f8fafc" }}>
                      <span style={{ width: 8, height: 8, borderRadius: "50%", flexShrink: 0, background: f.status === "done" ? "#10b981" : f.status === "failed" ? "#ef4444" : "#cbd5e1" }} />
                      <span style={{ flex: 1, fontSize: 12.5, color: "#0f172a", minWidth: 0 }}>
                        {f.title} {f.form_no && <span style={{ color: "#94a3b8" }}>· Form {f.form_no}</span>}
                        {f.error && <span style={{ display: "block", fontSize: 11, color: "#b91c1c" }}>{f.error}</span>}
                      </span>
                      {f.status === "done" && f.file && (
                        <>
                          <button onClick={() => file(p, f.key, f.file!)} style={btn("#1d4ed8", "#eff6ff", "#bfdbfe")}>
                            <FiEye size={12} /> View
                          </button>
                          <button onClick={() => file(p, f.key, f.file!, true)} style={btn("#334155", "#fff", "#e2e8f0")}>
                            <FiDownload size={12} />
                          </button>
                        </>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>

      <style>{`@keyframes cdpspin{to{transform:rotate(360deg)}}`}</style>

      <GenerateDocumentsModal
        open={showGen}
        companyId={companyId}
        companyName={companyName}
        audits={data.audits}
        catalogue={data.catalogue}
        regenerate={regen}
        onClose={() => setShowGen(false)}
        onStarted={(pack) => {
          setOpen(pack.id);
          load();
        }}
      />
    </div>
  );
}

function btn(fg: string, bg: string, bd: string): React.CSSProperties {
  return { display: "inline-flex", alignItems: "center", gap: 5, padding: "5px 10px", borderRadius: 7, border: `1px solid ${bd}`, background: bg, color: fg, fontSize: 11.5, fontWeight: 700, cursor: "pointer", whiteSpace: "nowrap" };
}
