"use client";

/**
 * "Digital Report" cell (2026-11-10) for the My Audits table.
 * Approved report with a final PDF → "Digital Report" button (opens DigitalReportModal: Word + PDF download);
 * report still in progress → its status; no report for the audit → "Not generated".
 */
import React from "react";
import { FiCheckCircle, FiClock, FiFileText } from "react-icons/fi";
import type { ReportListItem } from "@/lib/api/types/audit-report-builder.types";
import type { DigitalReportRef } from "@/lib/api/audit-report.api";

const STATUS: Record<string, { label: string; bg: string; color: string; border: string }> = {
  draft: { label: "Draft", bg: "#f8fafc", color: "#475569", border: "#cbd5e1" },
  submitted: { label: "Under review", bg: "#eff6ff", color: "#1d4ed8", border: "#bfdbfe" },
  returned: { label: "Returned", bg: "#fff7ed", color: "#c2410c", border: "#fed7aa" },
  approved: { label: "Approved — PDF pending", bg: "#fefce8", color: "#a16207", border: "#fde68a" },
};

/** Build the object DigitalReportModal expects from a row's report reference. */
export function toReportListItem(rep: DigitalReportRef, rowId: number, companyName: string | null): ReportListItem {
  return {
    id: rep.id,
    report_no: rep.report_no,
    audit_schedule_row_id: rowId,
    company_id: 0,
    company_name: companyName,
    standard_id: rep.standard_id,
    stage_type: rep.stage_type as ReportListItem["stage_type"],
    status: rep.status as ReportListItem["status"],
    conclusion: null,
    version: rep.version,
    has_pdf: rep.has_pdf,
    created_by: null,
    submitted_at: null,
    approved_at: rep.approved_at,
    updated_at: rep.updated_at ?? "",
  };
}

export default function DigitalReportCell({
  reports,
  onOpen,
}: {
  reports: DigitalReportRef[] | undefined;
  onOpen: (rep: DigitalReportRef) => void;
}) {
  const reps = reports ?? [];
  if (reps.length === 0) {
    return (
      <span
        title="No digital report has been created for this audit"
        style={{ display: "inline-flex", padding: "4px 10px", borderRadius: 6, border: "1px dashed #cbd5e1", background: "#fff", color: "#94a3b8", fontSize: 11, fontWeight: 700, whiteSpace: "normal", maxWidth: "100%", boxSizing: "border-box", textAlign: "left", lineHeight: 1.3, wordBreak: "break-word" }}
      >
        Not generated
      </span>
    );
  }
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "stretch", gap: 4, width: "100%", minWidth: 0 }}>
      {reps.map((rep) => {
        const ready = (rep.status === "approved" || rep.status === "locked") && rep.has_pdf;
        if (ready) {
          return (
            <button
              key={rep.id}
              onClick={() => onOpen(rep)}
              title={`Download ${rep.report_no ?? "report"} as Word or PDF`}
              style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "5px 10px", borderRadius: 6, border: "1px solid #5eead4", background: "linear-gradient(135deg,#f0fdfa,#ccfbf1)", color: "#0f766e", fontSize: 11, fontWeight: 700, cursor: "pointer", whiteSpace: "normal", maxWidth: "100%", boxSizing: "border-box", textAlign: "left", lineHeight: 1.3, wordBreak: "break-word" }}
            >
              <FiFileText size={12} style={{ flexShrink: 0 }} /> Digital Report{reps.length > 1 && rep.report_no ? ` · ${rep.report_no}` : ""}
            </button>
          );
        }
        const st = STATUS[rep.status] ?? STATUS.draft;
        return (
          <span
            key={rep.id}
            title={`${rep.report_no ?? "Report"} — not generated yet (${st.label.toLowerCase()})`}
            style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "4px 10px", borderRadius: 6, border: `1px solid ${st.border}`, background: st.bg, color: st.color, fontSize: 11, fontWeight: 700, whiteSpace: "normal", maxWidth: "100%", boxSizing: "border-box", textAlign: "left", lineHeight: 1.3, wordBreak: "break-word" }}
          >
            <FiClock size={11} style={{ flexShrink: 0 }} /> {st.label}
          </span>
        );
      })}
    </div>
  );
}

/**
 * "Approve" cell (2026-11-10) — rendered only for coordinators / super-admins.
 * Submitted report → green Approve button (POST /audit-reports/:id/approve, builds the final Word + PDF);
 * approved / locked → "Approved"; draft / returned → "Not submitted"; no report → "—".
 */
export function ApproveReportCell({
  reports,
  approvingId,
  onApprove,
}: {
  reports: DigitalReportRef[] | undefined;
  approvingId: number | null;
  onApprove: (rep: DigitalReportRef) => void;
}) {
  const reps = reports ?? [];
  const pill = (key: string | number, text: React.ReactNode, c: { bg: string; color: string; border: string }, title?: string) => (
    <span key={key} title={title}
      style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "4px 10px", borderRadius: 6, border: `1px solid ${c.border}`, background: c.bg, color: c.color, fontSize: 11, fontWeight: 700, whiteSpace: "normal", maxWidth: "100%", boxSizing: "border-box", textAlign: "left", lineHeight: 1.3, wordBreak: "break-word" }}>
      {text}
    </span>
  );
  if (reps.length === 0) return pill("none", "—", { bg: "#f8fafc", color: "#94a3b8", border: "#e2e8f0" }, "No report created for this audit");
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "stretch", gap: 4, width: "100%", minWidth: 0 }}>
      {reps.map((rep) => {
        const suffix = reps.length > 1 && rep.report_no ? ` · ${rep.report_no}` : "";
        if (rep.status === "submitted") {
          const busy = approvingId === rep.id;
          return (
            <button key={rep.id} onClick={() => onApprove(rep)} disabled={busy || approvingId !== null}
              title={`Approve ${rep.report_no ?? "report"} — builds the final Word + PDF`}
              style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "5px 10px", borderRadius: 6, border: "1px solid #16a34a", background: busy ? "#86efac" : "#16a34a", color: "#fff", fontSize: 11, fontWeight: 700, cursor: busy ? "wait" : approvingId !== null ? "not-allowed" : "pointer", whiteSpace: "normal", maxWidth: "100%", boxSizing: "border-box", textAlign: "left", lineHeight: 1.3, wordBreak: "break-word", opacity: approvingId !== null && !busy ? 0.6 : 1 }}>
              <FiCheckCircle size={12} style={{ flexShrink: 0 }} /> {busy ? "Approving…" : `Approve${suffix}`}
            </button>
          );
        }
        if (rep.status === "approved" || rep.status === "locked") {
          return pill(rep.id, <><FiCheckCircle size={11} style={{ flexShrink: 0 }} /> Approved{suffix}</>, { bg: "#f0fdf4", color: "#15803d", border: "#86efac" });
        }
        return pill(rep.id, <><FiClock size={11} style={{ flexShrink: 0 }} /> {rep.status === "returned" ? "Returned" : "Not submitted"}{suffix}</>,
          { bg: "#f8fafc", color: "#64748b", border: "#e2e8f0" }, "The auditor has not submitted this report yet");
      })}
    </div>
  );
}
