"use client";

/**
 * 📁 Documents tab of a company (2026-11-10) — same as scheme.qrs.ae company Documents:
 * search · stage filter · Download All (zip of the selected stage) · table Stage / Document / Standards /
 * Job Codes / Date / Actions (View PDF). Plus the Create Job button.
 */
import React, { useCallback, useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { FiDownload, FiEye, FiFileText, FiPlus, FiSearch } from "react-icons/fi";
import { downloadJobDocx, downloadStageZip, getCompanyJobs, openAuthedFile, type CompanyJob } from "@/lib/api/company-documents.api";
import CreateJobModal from "./CreateJobModal";

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 CompanyJobDocuments({
  companyId,
  companyName,
  showCreate = true, // 2026-11-10: Create Job now lives in the Companies table (pass false to hide here)
}: {
  companyId: number;
  companyName: string;
  showCreate?: boolean;
}) {
  const [rows, setRows] = useState<CompanyJob[]>([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);
  const [q, setQ] = useState("");
  const [stage, setStage] = useState("");
  const [zipping, setZipping] = useState<"" | "pdf" | "docx">("");
  const [busyId, setBusyId] = useState<string | null>(null);
  const [create, setCreate] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setRows(await getCompanyJobs(companyId));
      setErr(null);
    } catch (e: any) {
      setErr(e?.message || "Could not load documents");
    } finally {
      setLoading(false);
    }
  }, [companyId]);
  useEffect(() => {
    load();
  }, [load]);

  const stages = useMemo(() => [...new Set(rows.map((r) => r.stage))], [rows]);
  const shown = useMemo(() => {
    const s = q.toLowerCase();
    return rows.filter(
      (r) =>
        (!stage || r.stage === stage) &&
        (!s || r.template.toLowerCase().includes(s) || r.stage.toLowerCase().includes(s) || r.jobCodes.join(" ").toLowerCase().includes(s)),
    );
  }, [rows, q, stage]);

  const downloadAll = async (format: "pdf" | "docx") => {
    if (!stage) return toast.error("Please select a stage to download documents.");
    setZipping(format);
    try {
      await downloadStageZip(companyId, stage, `Stage_${stage.replace(/\s+/g, "_")}_${format === "docx" ? "Word" : "PDF"}_Documents.zip`, format);
    } catch (e: any) {
      toast.error(e?.message || "Download failed");
    } finally {
      setZipping("");
    }
  };

  const view = async (r: CompanyJob) => {
    setBusyId(`pdf-${r.id}`);
    try {
      await openAuthedFile(r.pdf_url, `${r.template}.pdf`);
    } catch (e: any) {
      toast.error(e?.message || "Could not open the PDF");
    } finally {
      setBusyId(null);
    }
  };

  const word = async (r: CompanyJob) => {
    setBusyId(`doc-${r.id}`);
    try {
      await downloadJobDocx(r.id, `${r.template}.docx`);
    } catch (e: any) {
      toast.error(e?.message || "Could not create the Word file");
    } finally {
      setBusyId(null);
    }
  };

  if (err && /forbidden|only admin/i.test(err)) {
    return <div style={{ fontSize: 12.5, color: "#94a3b8" }}>Documents are available to admin, scheme and coordinator users.</div>;
  }

  return (
    <div>
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 10 }}>
        <div style={{ flex: "1 1 200px", display: "flex", alignItems: "center", gap: 6, padding: "0 10px", height: 36, border: "1px solid #e2e8f0", borderRadius: 8, background: "#fff" }}>
          <FiSearch size={14} color="#94a3b8" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search documents, stage, job code" style={{ flex: 1, border: "none", outline: "none", fontSize: 12.5 }} />
        </div>
        <select value={stage} onChange={(e) => setStage(e.target.value)} style={{ height: 36, borderRadius: 8, border: "1px solid #e2e8f0", padding: "0 10px", fontSize: 12.5, fontWeight: 600 }}>
          <option value="">All Stages</option>
          {stages.map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
        <button type="button" onClick={() => downloadAll("pdf")} disabled={!stage || !!zipping} title={stage ? `Download all ${stage} documents as PDF (zip)` : "Select a stage first"} style={btn(!stage || zipping ? "#fca5a5" : "#dc2626")}>
          <FiDownload size={14} /> {zipping === "pdf" ? "Preparing…" : "Download All PDF"}
        </button>
        <button type="button" onClick={() => downloadAll("docx")} disabled={!stage || !!zipping} title={stage ? `Download all ${stage} documents as Word (zip)` : "Select a stage first"} style={btn(!stage || zipping ? "#93c5fd" : "#1d4ed8")}>
          <FiDownload size={14} /> {zipping === "docx" ? "Preparing…" : "Download All Word"}
        </button>
        {showCreate && (
          <button type="button" onClick={() => setCreate(true)} style={btn("#760E9E")}>
            <FiPlus size={14} /> Create Job
          </button>
        )}
      </div>

      {loading ? (
        <div style={{ fontSize: 12.5, color: "#94a3b8", padding: 8 }}>Loading…</div>
      ) : rows.length === 0 ? (
        <div style={{ fontSize: 12.5, color: "#94a3b8", padding: "14px 4px" }}>No documents yet — use the <b>Create Job</b> icon in the Companies table to generate them.</div>
      ) : (
        <div style={{ overflowX: "auto", border: "1px solid #e2e8f0", borderRadius: 10 }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5, minWidth: 640 }}>
            <thead>
              <tr style={{ background: "#760E9E", color: "#fff" }}>
                {["Stage", "Document", "Standards", "Job Codes", "Date", "Actions"].map((h) => (
                  <th key={h} style={{ padding: "8px 10px", textAlign: "left", fontSize: 11.5, whiteSpace: "nowrap" }}>
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {shown.map((r, i) => (
                <tr key={r.id} style={{ background: i % 2 ? "#faf5ff" : "#fff", borderTop: "1px solid #f1f5f9" }}>
                  <td style={td}>{r.stage}</td>
                  <td style={{ ...td, fontWeight: 600, color: "#0f172a" }}>{r.template}</td>
                  <td style={td}>{r.standards.join(", ") || "—"}</td>
                  <td style={{ ...td, fontFamily: "monospace", fontSize: 11.5 }}>{r.jobCodes.join(", ")}</td>
                  <td style={{ ...td, whiteSpace: "nowrap" }}>{fmt(r.date)}</td>
                  <td style={td}>
                    <div style={{ display: "flex", gap: 5 }}>
                      <button type="button" onClick={() => view(r)} disabled={!!busyId} title="Open the PDF" style={act("#b91c1c", "#fef2f2", "#fecaca")}>
                        <FiEye size={12} /> {busyId === `pdf-${r.id}` ? "Opening…" : "PDF"}
                      </button>
                      <button type="button" onClick={() => word(r)} disabled={!!busyId} title="Download an editable Word file" style={act("#1d4ed8", "#eff6ff", "#bfdbfe")}>
                        <FiFileText size={12} /> {busyId === `doc-${r.id}` ? "Preparing…" : "Word"}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <CreateJobModal company={create ? { id: companyId, name: companyName } : null} onClose={() => setCreate(false)} onCreated={load} />
    </div>
  );
}

function act(fg: string, bg: string, bd: string): React.CSSProperties {
  return { display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 10px", borderRadius: 6, border: `1px solid ${bd}`, background: bg, color: fg, fontSize: 11.5, fontWeight: 700, cursor: "pointer", whiteSpace: "nowrap" };
}
const td: React.CSSProperties = { padding: "8px 10px", color: "#475569", verticalAlign: "top" };
function btn(bg: string): React.CSSProperties {
  return { display: "inline-flex", alignItems: "center", gap: 6, height: 36, padding: "0 14px", borderRadius: 8, border: "none", background: bg, color: "#fff", fontWeight: 700, fontSize: 12.5, cursor: "pointer", whiteSpace: "nowrap" };
}
