"use client";

import React, { useEffect, useState, useRef } from "react";
import toast from "react-hot-toast";
import { FiXCircle, FiRefreshCw, FiPrinter, FiX, FiDownload, FiFileText } from "react-icons/fi";
import { getAuditSchedule } from "@/lib/api/audit-schedule.api";
import { formatDate } from "@/lib/api/mappers/audit-schedule.mappers";
import { RowStatusBadge } from "../components/AuditBadges";
import type {
  AuditSchedule,
  AuditRow,
} from "@/lib/api/types/audit-schedule.types";
// Pretty audit type for the CATEGORY column
function prettyType(t?: string | null): string {
  if (!t) return "—";
  const map: Record<string, string> = {
    INITIAL: "Initial",
    SURVEILLANCE: "Surveillance",
    RECERTIFICATION: "Re-Certification",
  };
  return map[String(t).toUpperCase()] ?? String(t);
}

// Pretty audit mode for the MODE column
function prettyMode(m?: string | null): string {
  if (!m) return "—";
  const map: Record<string, string> = {
    ONSITE: "📍 Onsite",
    OFFICE: "🏢 Office",
    REMOTE: "💻 Remote",
    HYBRID: "🔀 Hybrid",
    ONLINE: "💻 Online",
  };
  return map[String(m).toUpperCase()] ?? String(m);
}

// Build "NAME / GROUP" for the coordinator column.
// Initial → coordinator; Surveillance/Recert → submitter (fallback to coordinator).
function contactNameGroup(schedule: any, row: any): string {
  const fmt = (u: any) =>
    u
      ? `${u.firstName ?? ""} ${u.lastName ?? ""}`.trim() || u.email || ""
      : "";

  const coordinator = schedule?.coordinator ?? null;
  const submitter = (row as any)?.submitted_by ?? null;
  const group = schedule?.client_group ?? "";

  const type = String(row?.audit_type ?? "").toUpperCase();
  const useCoordinator = type === "INITIAL";

  // Initial → coordinator. Others → submitter, but fall back to coordinator.
  const person = useCoordinator
    ? coordinator
    : submitter ?? coordinator;

  const name = fmt(person);
  if (!name) return "—";
  return group ? `${name.toUpperCase()} / ${group}` : name.toUpperCase();
}
interface Props {
  isOpen: boolean;
  scheduleId: number | null;
  onClose: () => void;
  onCancelRow: (schedule: AuditSchedule, row: AuditRow) => void;
  onRescheduleRow: (schedule: AuditSchedule, row: AuditRow) => void;
  refreshFlag?: number;
}

/**
 * Detail View Modal — matches the architecture's "Print / Detail View" section
 * exactly. Shows audit rows in the printable A4 layout (same as the email
 * format) with per-row Cancel + Reschedule buttons.
 */
export default function AuditScheduleDetailModal({
  isOpen,
  scheduleId,
  onClose,
  onCancelRow,
  onRescheduleRow,
  refreshFlag,
}: Props) {
  const [schedule, setSchedule] = useState<AuditSchedule | null>(null);
  const [loading, setLoading] = useState(false);
  const printRef = useRef<HTMLDivElement>(null);

  // Load schedule with rows on open
  useEffect(() => {
    if (!isOpen || !scheduleId) return;
    setLoading(true);
    getAuditSchedule(scheduleId)
      .then(setSchedule)
      .catch((err) => toast.error(err?.message || "Failed to load schedule"))
      .finally(() => setLoading(false));
  }, [isOpen, scheduleId, refreshFlag]);

  // Reset on close
  useEffect(() => {
    if (!isOpen) {
      setSchedule(null);
    }
  }, [isOpen]);

  const handlePrint = () => {
    if (!printRef.current) return;
    const printWindow = window.open("", "_blank", "width=1200,height=800");
    if (!printWindow) {
      toast.error("Please allow popups to print");
      return;
    }
    const clone = printRef.current.cloneNode(true) as HTMLElement;
    clone.querySelectorAll(".no-print").forEach((el) => el.remove());
    const content = clone.innerHTML;
    printWindow.document.write(`<!doctype html>
<html>
<head>
  <title>Audit Schedule${schedule ? ` — ${schedule.title}` : ""}</title>
  <style>
    * { box-sizing: border-box; }
    body {
      font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
      padding: 24px;
      color: #0f172a;
      background: #fff;
    }
    h2 {
      text-align: center;
      text-decoration: underline;
      font-size: 20px;
      margin: 0 0 18px 0;
      letter-spacing: 0.5px;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 14px;
      font-size: 11px;
    }
    th, td {
      border: 1px solid #94a3b8;
      padding: 8px 10px;
      text-align: left;
      vertical-align: top;
    }
    th {
      background: #f1f5f9;
      text-transform: uppercase;
      font-weight: 700;
      font-size: 10px;
      letter-spacing: 0.5px;
    }
    .audit-code {
      font-family: 'IBM Plex Mono', monospace;
      font-size: 10px;
      font-weight: 600;
    }
    .footer-meta {
      margin-top: 16px;
      font-size: 11px;
      color: #64748b;
    }
    .cancelled-row { background: #fef2f2; color: #991b1b; text-decoration: line-through; }
    @media print {
      body { padding: 0; }
      .no-print { display: none !important; }
    }
  </style>
</head>
<body>${content}</body>
</html>`);
    printWindow.document.close();
    // Wait for content to render then print
    setTimeout(() => {
      printWindow.focus();
      printWindow.print();
    }, 300);
  };

  if (!isOpen) return null;
  const formatLongDate = (dateStr?: string): string => {
    if (!dateStr) return "—";
    return new Date(dateStr).toLocaleDateString("en-GB", {
      day: "numeric",
      month: "long",
      year: "numeric",
    }); // → "30 June 2026"
  };
  // Format the date the way the email shows it ("08TH MAY 2026")
  const formatScheduleHeader = (dateStr?: string): string => {
    if (!dateStr) return "";
    const d = new Date(dateStr);
    const day = d.getDate();
    const suffix =
      day === 1 || day === 21 || day === 31
        ? "ST"
        : day === 2 || day === 22
          ? "ND"
          : day === 3 || day === 23
            ? "RD"
            : "TH";
    const month = d
      .toLocaleDateString("en-GB", { month: "long" })
      .toUpperCase();
    const year = d.getFullYear();
    return `AUDIT SCHEDULE FOR ${day}${suffix} ${month} ${year}`;
  };

  // ── Shared export data ───────────────────────────────────────────────
  const HEADERS = [
    "S#", "Audit Code", "Audit Type", "Company Name", "Standard",
    "Accreditation", "Stage", "Mode", "Coordinator", "Audit Date",
    "Time", "Lead Auditor", "Status",
  ];

  const buildExportRows = () => {
    if (!schedule) return [];
    return (schedule.rows ?? []).map((row, i) => [
      row.row_no || i + 1,
      row.audit_code,
      prettyType(row.audit_type),
      row.company?.name ?? "—",
      (row.standards ?? []).map((s) => s.name).join(", ") || "—",
      row.accreditation ?? "—",
      row.audit_stage ?? "—",
      prettyMode(row.audit_mode).replace(/^[^\w]+\s*/, ""), // strip emoji
      contactNameGroup(schedule, row),
      formatLongDate(schedule.schedule_date),
      row.audit_time_label ?? row.audit_time ?? "—",
      row.lead_auditor
        ? `${row.lead_auditor.firstName} ${row.lead_auditor.lastName}`.toUpperCase()
        : "—",
      row.status,
    ]);
  };

  const exportTitle = () =>
    schedule ? formatScheduleHeader(schedule.schedule_date) : "AUDIT SCHEDULE";

  // ── Excel ────────────────────────────────────────────────────────────
  // ── Excel — matches the on-screen table exactly ──────────────────────
  const exportExcel = async () => {
    if (!schedule) return;
    const XLSX = await import("xlsx");
    const rows = buildExportRows();

    const coord = schedule.coordinator
      ? `${schedule.coordinator.firstName} ${schedule.coordinator.lastName}`.toUpperCase()
      : "—";

    const aoa = [
      [exportTitle()],                                  // row 1: title
      [],                                               // row 2: spacer
      HEADERS,                                          // row 3: header
      ...rows,                                          // data
      [],                                               // spacer
      [`Coordinator: ${coord}  ·  Group: ${schedule.client_group}  ·  Generated from QRS Certification System`],
    ];

    const ws = XLSX.utils.aoa_to_sheet(aoa);

    // Column widths matching the screen proportions
    ws["!cols"] = [
      { wch: 5 }, { wch: 20 }, { wch: 15 }, { wch: 26 }, { wch: 32 },
      { wch: 14 }, { wch: 14 }, { wch: 10 }, { wch: 22 }, { wch: 16 },
      { wch: 10 }, { wch: 20 }, { wch: 12 },
    ];

    const lastCol = HEADERS.length - 1;
    const lastRow = aoa.length - 1;
    ws["!merges"] = [
      { s: { r: 0, c: 0 }, e: { r: 0, c: lastCol } },        // title across all cols
      { s: { r: lastRow, c: 0 }, e: { r: lastRow, c: lastCol } }, // footer across all cols
    ];

    // Style every cell: borders + header fill + title styling
    const thin = { style: "thin", color: { rgb: "FF94A3B8" } };
    const border = { top: thin, bottom: thin, left: thin, right: thin };

    const range = XLSX.utils.decode_range(ws["!ref"]!);
    for (let R = range.s.r; R <= range.e.r; R++) {
      for (let C = range.s.c; C <= range.e.c; C++) {
        const addr = XLSX.utils.encode_cell({ r: R, c: C });
        const cell = ws[addr];
        if (!cell) continue;

        if (R === 0) {
          // Title row
          cell.s = {
            font: { bold: true, sz: 14, color: { rgb: "FF0F172A" } },
            alignment: { horizontal: "center", vertical: "center" },
          };
        } else if (R === 2) {
          // Header row — grey fill, bold, bordered
          cell.s = {
            font: { bold: true, sz: 9, color: { rgb: "FF0F172A" } },
            fill: { fgColor: { rgb: "FFF1F5F9" } },
            alignment: { horizontal: "left", vertical: "center", wrapText: true },
            border,
          };
        } else if (R >= 3 && R <= 2 + rows.length) {
          // Data rows — bordered
          cell.s = {
            font: { sz: 9 },
            alignment: { vertical: "top", wrapText: true },
            border,
          };
        } else if (R === lastRow) {
          // Footer
          cell.s = { font: { sz: 9, italic: true, color: { rgb: "FF64748B" } } };
        }
      }
    }

    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Audit Schedule");
    XLSX.writeFile(wb, `${exportTitle().replace(/\s+/g, "_")}.xlsx`);
  };

  // ── PDF ──────────────────────────────────────────────────────────────
  // ── PDF — matches the on-screen table exactly ────────────────────────
  const exportPdf = async () => {
    if (!schedule) return;
    const { jsPDF } = await import("jspdf");
    const autoTable = (await import("jspdf-autotable")).default;

    const doc = new jsPDF({ orientation: "landscape", unit: "pt", format: "a4" });
    const pageW = doc.internal.pageSize.getWidth();

    // Centered underlined title — same as the screen header
    const title = exportTitle();
    doc.setFontSize(16);
    doc.setFont("helvetica", "bold");
    doc.setTextColor(15, 23, 42); // #0f172a
    doc.text(title, pageW / 2, 36, { align: "center" });
    const tw = doc.getTextWidth(title);
    doc.setLineWidth(1);
    doc.line(pageW / 2 - tw / 2, 40, pageW / 2 + tw / 2, 40); // underline

    autoTable(doc, {
      head: [HEADERS],
      body: buildExportRows(),
      startY: 56,
      styles: {
        fontSize: 7,
        cellPadding: 4,
        valign: "top",
        lineColor: [148, 163, 184], // #94a3b8 borders like the screen
        lineWidth: 0.5,
        textColor: [15, 23, 42],
      },
      headStyles: {
        fillColor: [241, 245, 249], // #f1f5f9 light grey header (matches screen)
        textColor: [15, 23, 42],
        fontStyle: "bold",
        fontSize: 7,
        lineColor: [148, 163, 184],
        lineWidth: 0.5,
      },
      theme: "grid",
      columnStyles: {
        0: { cellWidth: 22 },  // S#
        1: { cellWidth: 70, font: "courier" }, // Audit Code (mono)
      },
      didDrawPage: () => {
        const h = doc.internal.pageSize.getHeight();
        doc.setFontSize(8);
        doc.setFont("helvetica", "normal");
        doc.setTextColor(100, 116, 139); // #64748b
        const coord = schedule.coordinator
          ? `${schedule.coordinator.firstName} ${schedule.coordinator.lastName}`.toUpperCase()
          : "—";
        doc.text(
          `Coordinator: ${coord}  ·  Group: ${schedule.client_group}  ·  Generated from QRS Audit & Certification System`,
          14,
          h - 14,
        );
      },
    });

    doc.save(`${title.replace(/\s+/g, "_")}.pdf`);
  };

  return (
    <div
      style={overlayStyle}
      onClick={onClose}
    >
      <div
        style={modalStyle}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header (not printed) */}
        <div style={headerStyle} className="no-print">
          <div>
            <h2 style={{ margin: 0, fontSize: 18, color: "#fff" }}>
              📋 Audit Schedule Details
            </h2>
            <p style={{ margin: "4px 0 0", fontSize: 12, color: "rgba(255,255,255,0.85)" }}>
              Print / detail view
            </p>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={onClose} style={btnClose} title="Close">
              <button
                onClick={handlePrint}
                disabled={!schedule}
                style={btnPrint}
                title="Print this schedule"
              >
                <FiPrinter size={14} /> Print
              </button>
              <button
                onClick={exportPdf}
                disabled={!schedule}
                style={btnPrint}
                title="Export as PDF"
              >
                <FiFileText size={14} /> PDF
              </button>
              <button
                onClick={exportExcel}
                disabled={!schedule}
                style={btnPrint}
                title="Export as Excel"
              >
                <FiDownload size={14} /> Excel
              </button>
              <button onClick={onClose} style={btnClose} title="Close"></button>
              <FiX size={18} />
            </button>
          </div>
        </div>

        {/* Body */}
        <div style={bodyStyle}>
          {loading ? (
            <div style={{ padding: 60, textAlign: "center", color: "#9ca3af" }}>
              <div style={spinner} />
              <p style={{ margin: "10px 0 0" }}>Loading schedule details...</p>
            </div>
          ) : !schedule ? (
            <div style={{ padding: 60, textAlign: "center", color: "#9ca3af" }}>
              Schedule not found.
            </div>
          ) : (
            <div ref={printRef}>
              {/* Print-format header */}
              <h2
                style={{
                  textAlign: "center",
                  textDecoration: "underline",
                  fontSize: 20,
                  margin: "0 0 18px 0",
                  letterSpacing: 0.5,
                  color: "#0f172a",
                }}
              >
                {formatScheduleHeader(schedule.schedule_date)}
              </h2>

              {/* The audit-row table — matches print/email layout exactly */}
              <div style={{ overflowX: "auto" }}>
                <table style={tableStyle}>
                  <thead>
                    <tr>
                      <th style={thStyle}>S#</th>
                      <th style={thStyle}>AUDIT CODE</th>
                      <th style={thStyle}>AUDIT TYPE</th>
                      <th style={thStyle}>COMPANY NAME</th>
                      <th style={thStyle}>STANDARD</th>
                      <th style={thStyle}>ACCREDITATION</th>
                      <th style={thStyle}>STAGE</th>
                      <th style={thStyle}>MODE</th>
                      <th style={thStyle}>COORDINATOR</th>
                      <th style={thStyle}>AUDIT DATE</th>
                      <th style={thStyle}>TIME</th>
                      <th style={thStyle}>LEAD AUDITOR</th>
                      <th style={thStyle}>STATUS</th>
                      <th
                        style={{ ...thStyle, minWidth: 100 }}
                        className="no-print"
                      >
                        ACTIONS
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {(schedule.rows ?? []).length === 0 ? (
                      <tr>
                        <td
                          colSpan={14}
                          style={{
                            ...tdStyle,
                            textAlign: "center",
                            padding: 30,
                            color: "#9ca3af",
                          }}
                        >
                          No audit rows in this schedule yet. Edit to add audits.
                        </td>
                      </tr>
                    ) : (
                      (schedule.rows ?? []).map((row, i) => {
                        const isCancelled = row.status === "CANCELLED";
                        const isCompleted = row.status === "COMPLETED";
                        const isClosed = isCancelled || isCompleted;

                        return (
                          <tr
                            key={row.id}
                            style={{
                              background: isCancelled ? "#fef2f2" : "#fff",
                            }}
                            className={isCancelled ? "cancelled-row" : ""}
                          >
                            <td style={tdStyle}>{row.row_no || i + 1}</td>
                            <td style={{ ...tdStyle, fontFamily: "monospace", fontSize: 10, fontWeight: 600, whiteSpace: "nowrap" }}>
                              {row.audit_code}
                            </td>
                            <td style={tdStyle}>{prettyType(row.audit_type)}</td>
                            <td style={{ ...tdStyle, fontWeight: 500 }}>
                              {row.company?.name ?? "—"}
                            </td>
                            <td style={tdStyle}>
                              {(row.standards ?? []).map((s) => s.name).join(", ") ||
                                "—"}
                            </td>
                            <td style={tdStyle}>{row.accreditation ?? "—"}</td>
                            <td style={tdStyle}>{row.audit_stage ?? "—"}</td>
                            <td style={tdStyle}>{prettyMode(row.audit_mode)}</td>
                            <td style={{ ...tdStyle, fontWeight: 500 }}>
                              {contactNameGroup(schedule, row)}
                            </td>
                            <td style={tdStyle}>
                              {formatLongDate(schedule.schedule_date)}
                            </td>
                            <td style={tdStyle}>
                              {row.audit_time_label ?? row.audit_time ?? "—"}
                            </td>
                            <td style={tdStyle}>
                              {row.lead_auditor
                                ? `${row.lead_auditor.firstName} ${row.lead_auditor.lastName}`.toUpperCase()
                                : "—"}
                            </td>
                            <td style={tdStyle}>
                              <RowStatusBadge status={row.status} />
                            </td>
                            <td style={{ ...tdStyle, padding: 6 }} className="no-print">
                              {isCompleted ? (
                                <span style={{ fontSize: 11, color: "#9ca3af" }}>
                                  ✓ Done
                                </span>
                              ) : (
                                <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                                  {!isCancelled && (
                                    <button
                                      onClick={() => onCancelRow(schedule, row)}
                                      style={actionBtnCancel}
                                      title="Cancel this audit"
                                    >
                                      <FiXCircle size={12} /> Cancel
                                    </button>
                                  )}
                                  {isCancelled && (
                                    <button
                                      onClick={() => onRescheduleRow(schedule, row)}
                                      style={actionBtnReschedule}
                                      title="Reschedule this audit"
                                    >
                                      <FiRefreshCw size={12} /> Reschedule
                                    </button>
                                  )}
                                  {!isClosed && (
                                    <button
                                      onClick={() => onRescheduleRow(schedule, row)}
                                      style={actionBtnReschedule}
                                      title="Reschedule this audit"
                                    >
                                      <FiRefreshCw size={12} />
                                    </button>
                                  )}
                                </div>
                              )}
                            </td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>

              {/* Footer meta */}
              <p
                style={{
                  marginTop: 16,
                  fontSize: 11,
                  color: "#64748b",
                }}
              >
                Coordinator:{" "}
                <strong>
                  {schedule.coordinator
                    ? `${schedule.coordinator.firstName} ${schedule.coordinator.lastName}`.toUpperCase()
                    : "—"}
                </strong>{" "}
                · Group: <strong>{schedule.client_group}</strong> · Generated
                from QRS Certification System
              </p>

              {schedule.notes && (
                <div
                  style={{
                    marginTop: 14,
                    padding: 10,
                    background: "#fffbeb",
                    border: "1px solid #fef3c7",
                    borderRadius: 6,
                    fontSize: 12,
                    color: "#854d0e",
                  }}
                >
                  <strong>Notes:</strong> {schedule.notes}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Inline styles (matches your modal pattern) ──────────────────────────
const overlayStyle: React.CSSProperties = {
  position: "fixed",
  inset: 0,
  background: "rgba(0,0,0,0.55)",
  display: "flex",
  alignItems: "flex-start",
  justifyContent: "center",
  zIndex: 1000,
  padding: 20,
  overflow: "auto",
};

const modalStyle: React.CSSProperties = {
  background: "#fff",
  borderRadius: 12,
  maxWidth: 1300,
  width: "100%",
  margin: "20px auto",
  boxShadow: "0 20px 60px rgba(0,0,0,0.3)",
  display: "flex",
  flexDirection: "column",
  maxHeight: "90vh",
};

const headerStyle: React.CSSProperties = {
  padding: "16px 20px",
  borderBottom: "1px solid #e5e7eb",
  display: "flex",
  justifyContent: "space-between",
  alignItems: "center",
  background: "linear-gradient(135deg, #0f766e 0%, #14b8a6 100%)",
  color: "#fff",
  borderTopLeftRadius: 12,
  borderTopRightRadius: 12,
};

// Title in white inside the gradient header — override the inline color
Object.assign(headerStyle, {});

const bodyStyle: React.CSSProperties = {
  padding: 24,
  overflowY: "auto",
  flex: 1,
};

const tableStyle: React.CSSProperties = {
  width: "100%",
  borderCollapse: "collapse",
  fontSize: 11,
};

const thStyle: React.CSSProperties = {
  border: "1px solid #94a3b8",
  padding: "8px 10px",
  textAlign: "left",
  background: "#f1f5f9",
  textTransform: "uppercase",
  fontWeight: 700,
  fontSize: 10,
  letterSpacing: 0.5,
};

const tdStyle: React.CSSProperties = {
  border: "1px solid #94a3b8",
  padding: "8px 10px",
  verticalAlign: "top",
};

const btnPrint: React.CSSProperties = {
  display: "inline-flex",
  alignItems: "center",
  gap: 6,
  padding: "8px 14px",
  background: "#fff",
  color: "#0f766e",
  border: "1px solid #fff",
  borderRadius: 6,
  fontSize: 13,
  fontWeight: 600,
  cursor: "pointer",
};

const btnClose: React.CSSProperties = {
  background: "rgba(255,255,255,0.2)",
  border: "none",
  color: "#fff",
  padding: 8,
  borderRadius: 6,
  cursor: "pointer",
  display: "inline-flex",
  alignItems: "center",
  justifyContent: "center",
};

const actionBtnCancel: React.CSSProperties = {
  display: "inline-flex",
  alignItems: "center",
  gap: 3,
  padding: "3px 8px",
  background: "#fef2f2",
  border: "1px solid #fca5a5",
  color: "#b91c1c",
  borderRadius: 4,
  fontSize: 11,
  fontWeight: 600,
  cursor: "pointer",
};

const actionBtnReschedule: React.CSSProperties = {
  display: "inline-flex",
  alignItems: "center",
  gap: 3,
  padding: "3px 8px",
  background: "#fff7ed",
  border: "1px solid #fdba74",
  color: "#9a3412",
  borderRadius: 4,
  fontSize: 11,
  fontWeight: 600,
  cursor: "pointer",
};

const spinner: React.CSSProperties = {
  display: "inline-block",
  width: 28,
  height: 28,
  border: "3px solid #e5e7eb",
  borderTopColor: "#14b8a6",
  borderRadius: "50%",
  animation: "spin 0.7s linear infinite",
};

// Title in the header should be white
(headerStyle as any)["--title-color"] = "#fff";
