"use client";

/**
 * "Digital Report" popup (2026-11-10) for the My Audit Reports table.
 * Lets the auditor download the generated report as Word (.docx) or PDF.
 * Both files come from the existing endpoints: GET /audit-reports/:id/docx and GET /audit-reports/:id/pdf
 * (approved / locked reports return the final version, anything else is marked DRAFT by the backend).
 */
import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { FiDownload, FiX } from "react-icons/fi";
import { FaFilePdf, FaFileWord } from "react-icons/fa";
import { downloadReportDocx, downloadReportPdf } from "@/lib/api/audit-report-builder.api";
import type { ReportListItem } from "@/lib/api/types/audit-report-builder.types";
import { STAGE_CONFIG, fmtDate } from "@/lib/api/mappers/audit-report-builder.mappers";

type Kind = "docx" | "pdf";

export default function DigitalReportModal({
  report,
  onClose,
}: {
  report: ReportListItem | null;
  onClose: () => void;
}) {
  const [busy, setBusy] = useState<Kind | null>(null);

  useEffect(() => {
    if (!report) return;
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [report, onClose]);

  if (!report) return null;

  const final = report.status === "approved" || report.status === "locked";
  const name = report.report_no ?? `report-${report.id}`;
  const stage = STAGE_CONFIG[report.stage_type]?.label ?? report.stage_type;

  const download = async (kind: Kind) => {
    setBusy(kind);
    try {
      if (kind === "docx") await downloadReportDocx(report.id, final ? name : `${name}-DRAFT`);
      else await downloadReportPdf(report.id, final ? name : `${name}-DRAFT`);
      toast.success(kind === "docx" ? "Word report downloaded" : "PDF report downloaded");
    } catch (e: any) {
      toast.error(e?.message || "Download failed");
    } finally {
      setBusy(null);
    }
  };

  const card = (kind: Kind) => {
    const word = kind === "docx";
    const color = word ? "#1d4ed8" : "#b91c1c";
    const bg = word ? "#eff6ff" : "#fef2f2";
    const border = word ? "#bfdbfe" : "#fecaca";
    const Icon = word ? FaFileWord : FaFilePdf;
    return (
      <button
        type="button"
        onClick={() => download(kind)}
        disabled={busy !== null}
        style={{
          flex: "1 1 200px",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: 10,
          padding: "22px 16px 18px",
          borderRadius: 12,
          border: `1.5px solid ${border}`,
          background: bg,
          cursor: busy ? "wait" : "pointer",
          opacity: busy && busy !== kind ? 0.55 : 1,
          transition: "transform .15s ease, box-shadow .15s ease",
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.transform = "translateY(-2px)";
          e.currentTarget.style.boxShadow = "0 10px 24px -14px rgba(15,23,42,.45)";
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.transform = "none";
          e.currentTarget.style.boxShadow = "none";
        }}
      >
        <Icon size={42} color={color} />
        <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>{word ? "Word Report" : "PDF Report"}</div>
        <div style={{ fontSize: 11, color: "#64748b" }}>{word ? "Editable .docx file" : "Print-ready .pdf file"}</div>
        <span
          style={{
            marginTop: 4,
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            padding: "6px 14px",
            borderRadius: 8,
            background: color,
            color: "#fff",
            fontSize: 12,
            fontWeight: 700,
          }}
        >
          <FiDownload size={13} /> {busy === kind ? "Preparing…" : "Download"}
        </span>
      </button>
    );
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Digital report downloads"
      onClick={onClose}
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 1000,
        background: "rgba(15,23,42,.55)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 16,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "min(520px, 100%)",
          background: "#fff",
          borderRadius: 14,
          boxShadow: "0 30px 60px -20px rgba(15,23,42,.5)",
          overflow: "hidden",
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "flex-start",
            justifyContent: "space-between",
            gap: 12,
            padding: "16px 18px",
            background: "linear-gradient(135deg,#0f766e,#115e59)",
            color: "#fff",
          }}
        >
          <div>
            <div style={{ fontSize: 16, fontWeight: 700 }}>Digital Report</div>
            <div style={{ fontSize: 12, opacity: 0.85, marginTop: 3 }}>
              {name} · {report.company_name ?? "—"} · {stage}
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            aria-label="Close"
            style={{ background: "rgba(255,255,255,.15)", border: 0, color: "#fff", borderRadius: 8, padding: 6, cursor: "pointer", display: "inline-flex" }}
          >
            <FiX size={16} />
          </button>
        </div>

        <div style={{ padding: 18 }}>
          {!final && (
            <div
              style={{
                marginBottom: 14,
                padding: "8px 12px",
                borderRadius: 8,
                background: "#fffbeb",
                border: "1px solid #fde68a",
                color: "#92400e",
                fontSize: 12,
              }}
            >
              This report is not approved yet — both files will be marked <strong>DRAFT</strong>.
            </div>
          )}
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
            {card("docx")}
            {card("pdf")}
          </div>
          <div style={{ marginTop: 14, fontSize: 11, color: "#94a3b8", textAlign: "center" }}>
            {final && report.approved_at ? `Approved ${fmtDate(report.approved_at)} · ` : ""}Version v{report.version}
          </div>
        </div>
      </div>
    </div>
  );
}
