"use client";

import React, { useEffect, useState, useCallback, useMemo } from "react";
import toast from "react-hot-toast";
import { FiDownload, FiFileText, FiRefreshCw, FiSearch, FiPrinter } from "react-icons/fi";
import styles from "../commonstyle/dattabale.module.css";
import { Pagination } from "../companies/Pagination";
import {
  getMyScheduleMaster,
  downloadMyScheduleMasterExcel,
  downloadMyScheduleMasterPdf,
  type MyScheduleMasterResponse,
} from "@/lib/api/my-audits.api";
import type { MyAuditRow } from "@/lib/api/types/my-audits.types";
import { generateAuditScheduleExcelJS } from "@/lib/utils/excelExportUtilExcelJS";


/**
 * My Schedule Master with Date-Specific Print & Excel Export
 * 
 * NEW FEATURES:
 * - Print button to open a date-specific audit schedule (like the screenshot)
 * - Excel export for a specific date's audits
 * - Print modal with professional formatting (no Actions column in export)
 */

const PAGE_SIZE = 10;

// ── display helpers ───────────────────────────────────────────────────────
function prettyType(t?: string | null): string {
  const map: Record<string, string> = {
    INITIAL: "Initial",
    SURVEILLANCE: "Surveillance",
    RECERTIFICATION: "Re-Certification",
  };
  return map[String(t || "").toUpperCase()] || (t ? String(t) : "—");
}

function prettyMode(m?: string | null): string {
  const map: Record<string, string> = {
    ONSITE: "Onsite",
    OFFICE: "Office",
    REMOTE: "Remote",
    HYBRID: "Hybrid",
    ONLINE: "Online",
  };
  return map[String(m || "").toUpperCase()] || (m ? String(m) : "—");
}

function fullName(u: any): string {
  if (!u) return "";
  const f = u.firstName || u.first_name || "";
  const l = u.lastName || u.last_name || "";
  const both = `${f} ${l}`.trim();
  return both || u.email || "";
}

function contactName(row: any): string {
  const type = String(row.audit_type || "").toUpperCase();
  if (type === "INITIAL") {
    return row.schedule?.coordinator ? fullName(row.schedule.coordinator) : "—";
  }
  const sub = row.submitted_by;
  if (sub) return fullName(sub) || "—";
  return row.schedule?.coordinator ? fullName(row.schedule.coordinator) : "—";
}

// ── Status pill ───────────────────────────────────────────────────────────
function StatusPill({ status }: { status?: string }) {
  const s = String(status || "").toUpperCase();
  const map: Record<string, { bg: string; fg: string; label: string }> = {
    PENDING: { bg: "#fef9c3", fg: "#854d0e", label: "Pending" },
    CONFIRMED: { bg: "#dbeafe", fg: "#1e40af", label: "Scheduled" },
    IN_PROGRESS: { bg: "#e0e7ff", fg: "#3730a3", label: "In Progress" },
    COMPLETED: { bg: "#dcfce7", fg: "#166534", label: "Completed" },
    CANCELLED: { bg: "#fee2e2", fg: "#991b1b", label: "Cancelled" },
    RESCHEDULED: { bg: "#ffedd5", fg: "#9a3412", label: "Rescheduled" },
  };
  const c = map[s] || { bg: "#f1f5f9", fg: "#475569", label: status || "—" };
  return (
    <span
      style={{
        display: "inline-block",
        padding: "3px 10px",
        borderRadius: 999,
        background: c.bg,
        color: c.fg,
        fontSize: 11,
        fontWeight: 700,
        whiteSpace: "nowrap",
      }}
    >
      {c.label}
    </span>
  );
}

const MONTHS = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

// ── Print Modal Component ─────────────────────────────────────────────────
function PrintScheduleModal({
  isOpen,
  onClose,
  date,
  rows,
  onExcelClick,
  exporting,
}: {
  isOpen: boolean;
  onClose: () => void;
  date: string;
  rows: MyAuditRow[];
  onExcelClick: () => void;
  exporting: boolean;
}) {
  if (!isOpen) return null;

  // Format date: "2026-07-14" → "14TH JULY 2026"
  const formatDate = (d: string) => {
    if (!d) return "AUDIT SCHEDULE";
    const [y, m, day] = d.split("-");
    const dayNum = parseInt(day, 10);
    const suffix = ["th", "st", "nd", "rd"][
      dayNum % 100 > 20 ? dayNum % 10 : dayNum % 100
    ] || "th";
    const month = MONTHS[parseInt(m, 10) - 1] || "";
    return `AUDIT SCHEDULE FOR ${dayNum}${suffix.toUpperCase()} ${month.toUpperCase()} ${y}`;
  };

  const thStyle: React.CSSProperties = {
    padding: "12px 10px",
    textAlign: "left",
    fontSize: 11,
    fontWeight: 700,
    color: "#1f2937",
    textTransform: "uppercase",
    letterSpacing: "0.05em",
    borderBottom: "2px solid #0f766e",
    backgroundColor: "#f3f4f6",
  };

  const tdStyle: React.CSSProperties = {
    padding: "12px 10px",
    fontSize: 12,
    color: "#374151",
    verticalAlign: "top",
    borderBottom: "1px solid #e5e7eb",
  };

  const handlePrint = () => {
    window.print();
  };

  return (
    <div
      style={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: "rgba(0,0,0,0.5)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 1000,
      }}
      onClick={onClose}
    >
      <div
        style={{
          backgroundColor: "#fff",
          borderRadius: 12,
          boxShadow: "0 20px 25px -5px rgba(0,0,0,0.1)",
          maxWidth: 1400,
          width: "95%",
          maxHeight: "90vh",
          overflowY: "auto",
          padding: 0,
        }}
        onClick={(e) => e.stopPropagation()}
        className="print-area"
      >
        {/* Header with Print/Excel buttons (hidden on print) */}
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "16px 24px",
            borderBottom: "1px solid #e5e7eb",
            backgroundColor: "#f9fafb",
          }}
          className="no-print"
        >
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: "#1f2937" }}>
            {formatDate(date)}
          </h2>
          <div style={{ display: "flex", gap: 8 }}>
            <button
              onClick={onExcelClick}
              disabled={exporting}
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
                padding: "9px 16px",
                borderRadius: 8,
                border: "1px solid #0f766e",
                background: "#fff",
                color: "#0f766e",
                fontSize: 13,
                fontWeight: 700,
                cursor: "pointer",
              }}
              title="Export this date to Excel"
            >
              <FiDownload size={15} /> {exporting ? "..." : "Excel"}
            </button>
            <button
              onClick={handlePrint}
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
                padding: "9px 16px",
                borderRadius: 8,
                border: "1px solid #7c3aed",
                background: "#fff",
                color: "#7c3aed",
                fontSize: 13,
                fontWeight: 700,
                cursor: "pointer",
              }}
              title="Print this schedule"
            >
              <FiPrinter size={15} /> Print
            </button>
            <button
              onClick={onClose}
              style={{
                padding: "9px 14px",
                borderRadius: 8,
                border: "1px solid #d1d5db",
                background: "#fff",
                color: "#6b7280",
                fontSize: 13,
                fontWeight: 700,
                cursor: "pointer",
              }}
              title="Close"
            >
              ✕
            </button>
          </div>
        </div>

        {/* Print-friendly title (shown only on print) */}
        <div style={{ textAlign: "center", padding: "24px", fontSize: 18, fontWeight: 700 }} className="print-only">
          {formatDate(date)}
        </div>

        {/* Table */}
        <div style={{ overflowX: "auto", padding: "0 24px 24px" }}>
          <table
            style={{
              width: "100%",
              borderCollapse: "collapse",
              fontSize: 13,
            }}
          >
            <thead>
              <tr style={{ backgroundColor: "#f3f4f6" }}>
                <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>
              </tr>
            </thead>
            <tbody>
              {rows.length === 0 ? (
                <tr>
                  <td colSpan={13} style={{ textAlign: "center", padding: 24, color: "#9ca3b8" }}>
                    No audits scheduled for this date.
                  </td>
                </tr>
              ) : (
                rows.map((row, i) => {
                  const group = (row as any).schedule?.client_group ?? "";
                  const name = contactName(row);
                  return (
                    <tr key={row.id}>
                      <td style={tdStyle}>{i + 1}</td>
                      <td style={{ ...tdStyle, fontFamily: "monospace", fontWeight: 600, fontSize: 11 }}>
                        {row.audit_code}
                      </td>
                      <td style={tdStyle}>{prettyType(row.audit_type)}</td>
                      <td style={{ ...tdStyle, fontWeight: 500 }}>
                        {(row as any).company?.name ?? "—"}
                      </td>
                      <td style={tdStyle}>
                        {((row as any).standards ?? []).map((s: any) => s.name).join(", ") || "—"}
                      </td>
                      <td style={tdStyle}>{(row as any).accreditation ?? "—"}</td>
                      <td style={tdStyle}>{(row as any).audit_stage ?? "—"}</td>
                      <td style={tdStyle}>{prettyMode((row as any).audit_mode)}</td>
                      <td style={tdStyle}>
                        {name}
                        {group ? <span style={{ color: "#9ca3b8" }}> / {group}</span> : null}
                      </td>
                      <td style={tdStyle}>{(row as any).schedule?.schedule_date ?? "—"}</td>
                      <td style={tdStyle}>
                        {(row as any).audit_time_label ?? (row as any).audit_time ?? "—"}
                      </td>
                      <td style={tdStyle}>
                        {(row as any).lead_auditor ? fullName((row as any).lead_auditor) : "—"}
                      </td>
                      <td style={tdStyle}>
                        <StatusPill status={row.status} />
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Footer info */}
        <div
          style={{
            padding: "12px 24px",
            fontSize: 11,
            color: "#6b7280",
            borderTop: "1px solid #e5e7eb",
            backgroundColor: "#f9fafb",
          }}
        >
          Total Audits: <strong>{rows.length}</strong> | Generated from QRS Certification System
        </div>
      </div>

      {/* Print styles */}
      <style>{`
        @media print {
          .no-print {
            display: none !important;
          }
          .print-area {
            max-width: 100% !important;
            box-shadow: none !important;
            border-radius: 0 !important;
            padding: 0 !important;
          }
          body {
            margin: 0;
            padding: 0;
            background: white;
          }
          table {
            page-break-inside: avoid;
          }
          tr {
            page-break-inside: avoid;
          }
        }
      `}</style>
    </div>
  );
}

// ── Main Component ────────────────────────────────────────────────────────
export default function MyScheduleMaster() {
  const [resp, setResp] = useState<MyScheduleMasterResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [exporting, setExporting] = useState<"excel" | "pdf" | null>(null);

  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [searchInput, setSearchInput] = useState("");
  const [status, setStatus] = useState<string>("all");

  const [year, setYear] = useState<string>("all");
  const [month, setMonth] = useState<string>("all");

  // NEW: Custom date range and print modal
  const [dateFrom, setDateFrom] = useState<string>("");
  const [dateTo, setDateTo] = useState<string>("");
  const [printModalOpen, setPrintModalOpen] = useState(false);
  const [printDate, setPrintDate] = useState<string>("");

  const yearOptions = useMemo(() => {
    const now = new Date().getFullYear();
    const out: number[] = [];
    for (let y = now + 1; y >= now - 3; y--) out.push(y);
    return out;
  }, []);

  const dateRange = useMemo(() => {
    if (dateFrom || dateTo) {
      return {
        date_from: dateFrom || undefined,
        date_to: dateTo || undefined,
      };
    }

    if (year === "all") return {};
    const y = Number(year);
    if (month === "all") {
      return { date_from: `${y}-01-01`, date_to: `${y}-12-31` };
    }
    const m = Number(month);
    const last = new Date(y, m, 0).getDate();
    const mm = String(m).padStart(2, "0");
    return {
      date_from: `${y}-${mm}-01`,
      date_to: `${y}-${mm}-${String(last).padStart(2, "0")}`,
    };
  }, [year, month, dateFrom, dateTo]);

  const params = useMemo(
    () => ({
      page,
      limit: PAGE_SIZE,
      search: search || undefined,
      status: status !== "all" ? status : undefined,
      ...dateRange,
    }),
    [page, search, status, dateRange],
  );

  const load = useCallback(() => {
    setLoading(true);
    getMyScheduleMaster(params)
      .then(setResp)
      .catch((e) => toast.error(e?.message || "Failed to load schedule"))
      .finally(() => setLoading(false));
  }, [params]);

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

  useEffect(() => {
    const t = setTimeout(() => {
      setSearch(searchInput);
      setPage(1);
    }, 400);
    return () => clearTimeout(t);
  }, [searchInput]);

  const counts = resp?.counts ?? {
    initial: 0,
    surveillance: 0,
    recertification: 0,
    total: 0,
  };
  const rows = resp?.data ?? [];
  const meta = resp?.meta;

  const doExport = async (kind: "excel" | "pdf") => {
    setExporting(kind);
    try {
      const exportParams = {
        search: search || undefined,
        status: status !== "all" ? status : undefined,
        ...dateRange,
      };
      if (kind === "excel") await downloadMyScheduleMasterExcel(exportParams);
      else await downloadMyScheduleMasterPdf(exportParams);
      toast.success(`${kind.toUpperCase()} exported successfully`);
    } catch (e: any) {
      toast.error(e?.message || `Failed to export ${kind}`);
    } finally {
      setExporting(null);
    }
  };

  // NEW: Export audits for a specific date using ExcelJS with proper formatting
  const doDateSpecificExcel = async () => {
    if (!printDate) {
      toast.error("Please select a date");
      return;
    }

    setExporting("excel");
    try {
      // Get the audits for the selected date from the current view
      const auditsByDateRows = rows.filter(
        (r) => (r as any).schedule?.schedule_date === printDate
      );

      if (auditsByDateRows.length === 0) {
        toast.error("No audits found for this date");
        setExporting(null);
        return;
      }

      // Use ExcelJS for proper formatting
      await generateAuditScheduleExcelJS(printDate, auditsByDateRows);
      toast.success("Excel exported successfully with professional formatting");
    } catch (e: any) {
      toast.error(e?.message || "Failed to export");
    } finally {
      setExporting(null);
    }
  };

  // NEW: Get audits for a specific date
  const auditsByDate = useCallback(async (dateStr: string) => {
    try {
      const res = await getMyScheduleMaster({
        date_from: dateStr,
        date_to: dateStr,
        limit: 1000, // Get all for this date
      });
      return res.data ?? [];
    } catch (e) {
      toast.error("Failed to load audits for this date");
      return [];
    }
  }, []);

  // NEW: Handle print button click
  const handlePrintClick = async () => {
    if (!printDate) {
      toast.error("Please select a date to print");
      return;
    }

    const auditRows = await auditsByDate(printDate);
    setPrintModalOpen(true);
  };

  const clearFilters = () => {
    setSearchInput("");
    setSearch("");
    setStatus("all");
    setYear("all");
    setMonth("all");
    setDateFrom("");
    setDateTo("");
    setPage(1);
  };

  const activeFilters =
    (search ? 1 : 0) +
    (status !== "all" ? 1 : 0) +
    (year !== "all" ? 1 : 0) +
    (month !== "all" ? 1 : 0) +
    (dateFrom ? 1 : 0) +
    (dateTo ? 1 : 0);

  const tiles = [
    { label: "INITIAL", value: counts.initial, color: "#2563eb", bg: "#eff6ff" },
    { label: "SURVEILLANCE", value: counts.surveillance, color: "#0f766e", bg: "#f0fdfa" },
    { label: "RE-CERTIFICATION", value: counts.recertification, color: "#7c3aed", bg: "#f5f3ff" },
    { label: "TOTAL", value: counts.total, color: "#4a0080", bg: "#faf5ff" },
  ];

  const thStyle: React.CSSProperties = {
    padding: "10px",
    textAlign: "left",
    fontSize: 10,
    fontWeight: 700,
    color: "#6b7280",
    textTransform: "uppercase",
    letterSpacing: "0.05em",
    whiteSpace: "normal",
    wordBreak: "break-word",
  };
  const tdStyle: React.CSSProperties = {
    padding: "10px",
    fontSize: 12,
    color: "#374151",
    verticalAlign: "top",
    whiteSpace: "normal",
    wordBreak: "break-word",
    overflowWrap: "anywhere",
  };

  return (
    <div className={styles.container}>
      {/* ── Header ── */}
      <div
        style={{
          display: "flex",
          alignItems: "flex-start",
          justifyContent: "space-between",
          flexWrap: "wrap",
          gap: 12,
          marginBottom: 16,
        }}
      >
        <div>
          <h1 style={{ fontSize: 26, fontWeight: 800, color: "#1a0440", margin: 0 }}>
            My Audit Schedule — Master
          </h1>
          <p style={{ color: "#64748b", margin: "4px 0 0", fontSize: 13 }}>
            Audits assigned to you and audits you submitted
          </p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button
            onClick={() => doExport("excel")}
            disabled={exporting !== null}
            style={exportBtn("#0f766e")}
            title="Export all filtered results to Excel"
          >
            <FiDownload size={15} /> {exporting === "excel" ? "..." : "Excel"}
          </button>
          <button
            onClick={() => doExport("pdf")}
            disabled={exporting !== null}
            style={exportBtn("#7c3aed")}
            title="Export all filtered results to PDF"
          >
            <FiFileText size={15} /> {exporting === "pdf" ? "..." : "PDF"}
          </button>
          {/* NEW: Print button */}
          <button
            onClick={() => {
              if (!printDate) {
                toast.error("Select a date below to print");
              } else {
                handlePrintClick();
              }
            }}
            style={exportBtn("#059669")}
            title="Print/Export audits for a specific date"
          >
            <FiPrinter size={15} /> Print
          </button>
        </div>
      </div>

      {/* ── Count tiles ── */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
          gap: 12,
          marginBottom: 16,
        }}
      >
        {tiles.map((t) => (
          <div
            key={t.label}
            style={{
              background: t.bg,
              border: `1px solid ${t.color}22`,
              borderLeft: `4px solid ${t.color}`,
              borderRadius: 10,
              padding: "14px 18px",
            }}
          >
            <div style={{ fontSize: 11, fontWeight: 700, color: "#64748b", letterSpacing: "0.05em" }}>
              {t.label}
            </div>
            <div style={{ fontSize: 28, fontWeight: 800, color: t.color, marginTop: 2 }}>
              {t.value}
            </div>
          </div>
        ))}
      </div>

      {/* ── Filter bar ── */}
      <div
        style={{
          display: "flex",
          flexWrap: "wrap",
          alignItems: "center",
          gap: 10,
          padding: "12px 14px",
          background: "#f8fafc",
          border: "1px solid #e2e8f0",
          borderRadius: 10,
          marginBottom: 14,
        }}
      >
        <div style={{ position: "relative", flex: "1 1 240px", minWidth: 200 }}>
          <FiSearch
            size={15}
            style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "#94a3b8" }}
          />
          <input
            placeholder="Search code, company, standard…"
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            style={{
              width: "100%",
              padding: "8px 12px 8px 34px",
              borderRadius: 8,
              border: "1px solid #cbd5e1",
              fontSize: 13,
              outline: "none",
            }}
          />
        </div>

        <select
          value={status}
          onChange={(e) => {
            setStatus(e.target.value);
            setPage(1);
          }}
          style={selectStyle(status !== "all")}
        >
          <option value="all">All Statuses</option>
          <option value="PENDING">Pending</option>
          <option value="CONFIRMED">Scheduled</option>
          <option value="IN_PROGRESS">In Progress</option>
          <option value="COMPLETED">Completed</option>
          <option value="CANCELLED">Cancelled</option>
          <option value="RESCHEDULED">Rescheduled</option>
        </select>

        {/* NEW: Print date picker */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 6,
            padding: "4px 10px",
            borderRadius: 8,
            background: printDate ? "#dcfce7" : "transparent",
            border: printDate ? "1px solid #86efac" : "1px solid transparent",
          }}
          title="Select date for print/export"
        >
          <span style={{ fontSize: 11, color: "#64748b", fontWeight: 600, whiteSpace: "nowrap" }}>
            📅 Print:
          </span>
          <input
            type="date"
            value={printDate}
            onChange={(e) => setPrintDate(e.target.value)}
            style={{
              padding: "6px 8px",
              borderRadius: 6,
              border: "1px solid #cbd5e1",
              fontSize: 12,
              color: "#475569",
              outline: "none",
            }}
            title="Select a date to print/export audits for that day"
          />
        </div>

        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 6,
            padding: "4px 10px",
            borderRadius: 8,
            background: dateFrom || dateTo ? "#ecfeff" : "transparent",
            border: dateFrom || dateTo ? "1px solid #67e8f9" : "1px solid transparent",
          }}
        >
          <span style={{ fontSize: 11, color: "#64748b", fontWeight: 600, whiteSpace: "nowrap" }}>
            📅 From:
          </span>
          <input
            type="date"
            value={dateFrom}
            onChange={(e) => {
              setDateFrom(e.target.value);
              setPage(1);
            }}
            style={{
              padding: "6px 8px",
              borderRadius: 6,
              border: "1px solid #cbd5e1",
              fontSize: 12,
              color: "#475569",
              outline: "none",
            }}
          />
          <span style={{ fontSize: 11, color: "#64748b", fontWeight: 600, whiteSpace: "nowrap" }}>
            To:
          </span>
          <input
            type="date"
            value={dateTo}
            onChange={(e) => {
              setDateTo(e.target.value);
              setPage(1);
            }}
            style={{
              padding: "6px 8px",
              borderRadius: 6,
              border: "1px solid #cbd5e1",
              fontSize: 12,
              color: "#475569",
              outline: "none",
            }}
          />
        </div>

        <select
          value={year}
          onChange={(e) => {
            setYear(e.target.value);
            setPage(1);
          }}
          style={selectStyle(year !== "all")}
        >
          <option value="all">📅 All Years</option>
          {yearOptions.map((y) => (
            <option key={y} value={String(y)}>{y}</option>
          ))}
        </select>

        <select
          value={month}
          onChange={(e) => {
            setMonth(e.target.value);
            setPage(1);
          }}
          disabled={year === "all"}
          style={{ ...selectStyle(month !== "all"), opacity: year === "all" ? 0.5 : 1 }}
        >
          <option value="all">All Months</option>
          {MONTHS.map((m, i) => (
            <option key={m} value={String(i + 1)}>{m}</option>
          ))}
        </select>

        <button onClick={load} title="Refresh" style={iconBtn}>
          <FiRefreshCw size={15} />
        </button>

        {activeFilters > 0 && (
          <button onClick={clearFilters} style={clearBtn} title="Clear filters">
            ✕ Clear ({activeFilters})
          </button>
        )}
      </div>

      {/* ── Count line ── */}
      {meta && (
        <div
          style={{
            padding: "10px 16px",
            background: "#f0fdfa",
            border: "1px solid #99f6e4",
            borderRadius: 8,
            marginBottom: 12,
            fontSize: 13,
            color: "#0f766e",
          }}
        >
          📋 Showing <strong>{rows.length}</strong> of{" "}
          <strong>{meta.total.toLocaleString()}</strong> audits
          {activeFilters > 0 && (
            <span style={{ marginLeft: 8, fontWeight: 600 }}>
              ({activeFilters} filter{activeFilters > 1 ? 's' : ''} active)
            </span>
          )}
        </div>
      )}

      {/* ── Table ── */}
      <div className={styles.tableWrapper} style={{ overflowX: "auto" }}>
        <table
          className={styles.table}
          style={{ tableLayout: "fixed", width: "100%", minWidth: 1380, borderCollapse: "collapse" }}
        >
          <colgroup>
            <col style={{ width: 40 }} />
            <col style={{ width: 130 }} />
            <col style={{ width: 95 }} />
            <col style={{ width: 175 }} />
            <col style={{ width: 175 }} />
            <col style={{ width: 70 }} />
            <col style={{ width: 95 }} />
            <col style={{ width: 70 }} />
            <col style={{ width: 150 }} />
            <col style={{ width: 95 }} />
            <col style={{ width: 70 }} />
            <col style={{ width: 120 }} />
            <col style={{ width: 95 }} />
          </colgroup>
          <thead>
            <tr style={{ background: "#f8fafc" }}>
              <th style={thStyle}>S#</th>
              <th style={thStyle}>Audit Code</th>
              <th style={thStyle}>Type</th>
              <th style={thStyle}>Company</th>
              <th style={thStyle}>Standard</th>
              <th style={thStyle}>Accred.</th>
              <th style={thStyle}>Stage</th>
              <th style={thStyle}>Mode</th>
              <th style={thStyle}>Coordinator / Submitter</th>
              <th style={thStyle}>Date</th>
              <th style={thStyle}>Time</th>
              <th style={thStyle}>Lead Auditor</th>
              <th style={thStyle}>Status</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={13} style={{ textAlign: "center", padding: 48, color: "#94a3b8" }}>
                  Loading…
                </td>
              </tr>
            ) : rows.length === 0 ? (
              <tr>
                <td colSpan={13} style={{ textAlign: "center", padding: 48 }}>
                  <div style={{ fontSize: 32 }}>📋</div>
                  <div style={{ color: "#6b7280", marginTop: 8 }}>No audits found.</div>
                </td>
              </tr>
            ) : (
              rows.map((row: MyAuditRow, i: number) => {
                const group = (row as any).schedule?.client_group ?? "";
                const name = contactName(row);
                return (
                  <tr key={row.id} style={{ borderTop: "1px solid #f1f5f9" }}>
                    <td style={tdStyle}>{(meta ? (meta.page - 1) * meta.limit : 0) + i + 1}</td>
                    <td style={{ ...tdStyle, fontFamily: "monospace", fontWeight: 600, fontSize: 11 }}>
                      {row.audit_code}
                    </td>
                    <td style={tdStyle}>{prettyType(row.audit_type)}</td>
                    <td style={{ ...tdStyle, fontWeight: 500 }}>
                      {(row as any).company?.name ?? "—"}
                    </td>
                    <td style={tdStyle}>
                      {((row as any).standards ?? []).map((s: any) => s.name).join(", ") || "—"}
                    </td>
                    <td style={tdStyle}>{(row as any).accreditation ?? "—"}</td>
                    <td style={tdStyle}>{(row as any).audit_stage ?? "—"}</td>
                    <td style={tdStyle}>{prettyMode((row as any).audit_mode)}</td>
                    <td style={tdStyle}>
                      {name}
                      {group ? (
                        <span style={{ color: "#94a3b8" }}> / {group}</span>
                      ) : null}
                    </td>
                    <td style={tdStyle}>{(row as any).schedule?.schedule_date ?? "—"}</td>
                    <td style={tdStyle}>
                      {(row as any).audit_time_label ?? (row as any).audit_time ?? "—"}
                    </td>
                    <td style={tdStyle}>
                      {(row as any).lead_auditor ? fullName((row as any).lead_auditor) : "—"}
                    </td>
                    <td style={tdStyle}>
                      <StatusPill status={row.status} />
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>

      {/* ── Pagination ── */}
      {meta && meta.totalPages > 1 && (
        <Pagination
          currentPage={meta.page}
          setCurrentPage={setPage}
          totalPages={meta.totalPages}
          startIndex={(meta.page - 1) * meta.limit + 1}
          endIndex={Math.min(meta.page * meta.limit, meta.total)}
          sortedDataLength={meta.total}
          itemsPerPage={meta.limit}
          setItemsPerPage={() => {}}
        />
      )}

      {/* ── Print Modal ── */}
      <PrintScheduleModal
        isOpen={printModalOpen}
        onClose={() => setPrintModalOpen(false)}
        date={printDate}
        rows={rows.filter((r) => (r as any).schedule?.schedule_date === printDate)}
        onExcelClick={doDateSpecificExcel}
        exporting={exporting === "excel"}
      />
    </div>
  );
}

// ── Inline styles ──────────────────────────────────────────────────────
function exportBtn(color: string): React.CSSProperties {
  return {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "9px 16px",
    borderRadius: 8,
    border: `1px solid ${color}`,
    background: "#fff",
    color,
    fontSize: 13,
    fontWeight: 700,
    cursor: "pointer",
  };
}
function selectStyle(active: boolean): React.CSSProperties {
  return {
    minWidth: 130,
    padding: "8px 12px",
    borderRadius: 8,
    border: active ? "1.5px solid #4a0080" : "1px solid #cbd5e1",
    background: active ? "#faf5ff" : "#fff",
    fontSize: 13,
    fontWeight: 600,
    color: active ? "#4a0080" : "#475569",
    cursor: "pointer",
    outline: "none",
  };
}
const iconBtn: React.CSSProperties = {
  padding: "8px 10px",
  borderRadius: 8,
  border: "1px solid #cbd5e1",
  background: "#fff",
  color: "#475569",
  cursor: "pointer",
};
const clearBtn: React.CSSProperties = {
  display: "inline-flex",
  alignItems: "center",
  gap: 5,
  padding: "8px 14px",
  borderRadius: 8,
  border: "1px solid #fca5a5",
  background: "#fef2f2",
  color: "#dc2626",
  cursor: "pointer",
  fontSize: 12,
  fontWeight: 700,
  marginLeft: "auto",
};