"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import dynamic from "next/dynamic";
import styles from "../commonstyle/dattabale.module.css";
import { CompanyAuditFilters } from "./CompanyAuditFilters";
import { Pagination } from "./Pagination";
import { EnterpriseLoader } from "./../../../../components/loader/loader";
import {
  getCompanyAuditsPaginated,
  getAllCompanyAudits,
  deleteCompanyAudit,
  getAuditStageOptions,
  COMPANY_AUDITS_API_BASE_URL,
} from "@/lib/api/companyAudit.api";
import { fetchApi } from "@/lib/api/http";
import { deleteWithConfirm } from "./../../../../components/ConfirmDialog/ConfirmDialog";
import CompanyAuditForm from "./Form/CompanyAuditForm";
import {
  mapCompanyAuditsApiResponse,
  mapColumnKeyToValue,
} from "@/lib/api/mappers/companyAudit.mappers";
import type {
  CompanyAuditRow,
  PaginationMeta,
} from "@/lib/api/types/companyAudit.types";
import toast from "react-hot-toast";

const AuditRowFallback = dynamic(
  () => import("./CompanyAuditRow").then((m) => m.CompanyAuditRow),
  { ssr: false },
);
const DynamicAuditRow = dynamic(
  () => import("./DynamicCompanyAuditRow").then((m) => m.default),
  { ssr: false },
);

interface ButtonConfig {
  key: string;
  icon: string;
  color: string;
  label: string;
  order: number;
  position: "row" | "toolbar";
}
interface ColumnConfig {
  key: string;
  type: string;
  label: string;
  order: number;
  sortable: boolean;
  default_visible: boolean;
}
interface ModuleConfig {
  id: number;
  name: string;
  slug: string;
  button_config: ButtonConfig[];
  column_config: ColumnConfig[];
}
interface CompanyAuditTableProps {
  refreshFlag?: boolean;
}

const FALLBACK_COLUMNS: ColumnConfig[] = [
  {
    key: "companyName",
    type: "text",
    label: "Company",
    order: 1,
    sortable: true,
    default_visible: true,
  },
  {
    key: "auditBy",
    type: "text",
    label: "Audit By",
    order: 2,
    sortable: true,
    default_visible: true,
  },
  {
    key: "auditType",
    type: "text",
    label: "Audit Type",
    order: 3,
    sortable: true,
    default_visible: true,
  },
  {
    key: "auditStage",
    type: "badge",
    label: "Audit Stage",
    order: 4,
    sortable: true,
    default_visible: true,
  },
  {
    key: "auditMode",
    type: "text",
    label: "Audit Mode",
    order: 5,
    sortable: true,
    default_visible: true,
  },
  {
    key: "auditYear",
    type: "text",
    label: "Audit Year",
    order: 6,
    sortable: true,
    default_visible: true,
  },
  {
    key: "status",
    type: "badge",
    label: "Audit Status",
    order: 7,
    sortable: true,
    default_visible: true,
  },
  {
    key: "createdAt",
    type: "date",
    label: "Created At",
    order: 8,
    sortable: true,
    default_visible: true,
  },
  {
    key: "actions",
    type: "actions",
    label: "Actions",
    order: 99,
    sortable: false,
    default_visible: true,
  },
];

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

function useDebounce<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return debounced;
}

export default function CompanyAuditTable({
  refreshFlag,
}: CompanyAuditTableProps) {
  // ── Data ────────────────────────────────────────────────────────────────────
  const [data, setData] = useState<CompanyAuditRow[]>([]);
  const [meta, setMeta] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // ── UI state ────────────────────────────────────────────────────────────────
  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [expandedRows, setExpandedRows] = useState<number[]>([]);

  // ── Pagination ──────────────────────────────────────────────────────────────
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  // ── Filters ──────────────────────────────────────────────────────────────────
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [stageFilter, setStageFilter] = useState("all");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const debouncedSearch = useDebounce(searchTerm, 400);

  // Month & Year filters
  const [monthFilter, setMonthFilter] = useState("all");
  const [yearFilter, setYearFilter] = useState("all");

  // Stage options (kept in state for backward compat; no longer used by the dropdown)
  const [stageOptions, setStageOptions] = useState<
    { value: number | string; label: string }[]
  >([]);

  // ── Modal ───────────────────────────────────────────────────────────────────
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);

  // ── Permission system ────────────────────────────────────────────────────────
  const [moduleConfig, setModuleConfig] = useState<ModuleConfig | null>(null);
  const [userPermissions, setUserPermissions] = useState<any[]>([]);
  const [permissionsLoading, setPermissionsLoading] = useState(true);
  const [permissionSystemReady, setPermissionSystemReady] = useState(false);
  const [rawUserId, setRawUserId] = useState<any>(null);
  const [debugLog, setDebugLog] = useState<string[]>([]);
  const [showDebug, setShowDebug] = useState(true);

  const addDebug = useCallback((msg: string) => {
    console.log(`[AUDIT-DEBUG] ${msg}`);
    setDebugLog((p) => [...p, `${new Date().toLocaleTimeString()} — ${msg}`]);
  }, []);

  const fetchModuleConfig = useCallback(async (): Promise<boolean> => {
    try {
      const response = await fetchApi<any>(`${API_BASE_URL}/modules`);
      const list = Array.isArray(response)
        ? response
        : response?.data
          ? Array.isArray(response.data)
            ? response.data
            : [response.data]
          : [response];
      const mod = list.find(
        (m: any) => m.slug === "company-audits" || m.name === "company-audits",
      );
      if (mod) {
        setModuleConfig(mod);
        addDebug(`✅ company-audits module (id:${mod.id})`);
        return true;
      }
      addDebug("⚠️ module NOT found — FALLBACK");
      return false;
    } catch (err: any) {
      addDebug(`⚠️ module fetch: ${err.message}`);
      return false;
    }
  }, [addDebug]);

  const fetchUserPermissions = useCallback(async (): Promise<boolean> => {
    try {
      let userId: any = null,
        source = "";
      if (typeof window !== "undefined") {
        try {
          const s = localStorage.getItem("user");
          if (s) {
            const p = JSON.parse(s);
            userId = p?.id || p?.userId || p?.user_id;
            source = `localStorage("user")`;
          }
        } catch {}
        if (!userId) {
          try {
            const t =
              localStorage.getItem("token") ||
              localStorage.getItem("accessToken") ||
              localStorage.getItem("access_token");
            if (t) {
              const p = JSON.parse(atob(t.split(".")[1]));
              userId = p?.id || p?.userId || p?.user_id || p?.sub;
              source = "JWT";
            }
          } catch {}
        }
        if (!userId) {
          userId =
            localStorage.getItem("userId") || localStorage.getItem("user_id");
          if (userId) source = `localStorage("userId")`;
        }
      }
      setRawUserId({ userId, source });
      if (!userId) {
        addDebug("⚠️ No userId — FALLBACK");
        setUserPermissions([]);
        return false;
      }
      const res = await fetchApi<any>(
        `${API_BASE_URL}/user-permissions/user/${userId}`,
      );
      const list = Array.isArray(res)
        ? res
        : res?.data
          ? Array.isArray(res.data)
            ? res.data
            : [res.data]
          : (res?.permissions ?? []);
      setUserPermissions(list);
      addDebug(`📦 ${list.length} permissions`);
      return true;
    } catch (err: any) {
      addDebug(`⚠️ perms: ${err.message}`);
      setUserPermissions([]);
      return false;
    }
  }, [addDebug]);

  const visibleColumns = useMemo((): ColumnConfig[] => {
    if (!moduleConfig?.column_config?.length) return FALLBACK_COLUMNS;
    const all = [...moduleConfig.column_config].sort(
      (a, b) => (a.order ?? 99) - (b.order ?? 99),
    );
    let cond: string | null = null;
    for (const up of userPermissions) {
      const mid = up.permission?.module?.id ?? up.permission?.module_id;
      if (mid && mid !== moduleConfig.id) continue;
      for (const c of up.conditions ?? []) {
        if (
          (c.condition_field || c.field) === "visible_columns" &&
          (c.condition_value || c.value)
        ) {
          cond = c.condition_value || c.value;
          break;
        }
      }
      if (cond) break;
    }
    let filtered = cond
      ? all.filter((c) =>
          cond!
            .split(",")
            .map((k) => k.trim())
            .includes(c.key),
        )
      : all;

    // Ensure auditStage column exists
    if (!filtered.some((c) => c.key === "auditStage")) {
      const auditByIdx = filtered.findIndex((c) => c.key === "auditBy");
      const stageCol: ColumnConfig = {
        key: "auditStage",
        type: "badge",
        label: "Audit Stage",
        order: (filtered[auditByIdx]?.order ?? 2) + 1,
        sortable: true,
        default_visible: true,
      };
      if (auditByIdx >= 0) {
        filtered = [
          ...filtered.slice(0, auditByIdx + 1),
          stageCol,
          ...filtered.slice(auditByIdx + 1),
        ];
      } else {
        filtered = [...filtered, stageCol];
      }
    }
    return filtered;
  }, [moduleConfig, userPermissions]);

  const permittedActions = useMemo((): Set<string> => {
    if (!moduleConfig)
      return new Set([
        "view",
        "edit",
        "delete",
        "create",
        "export",
        "print",
        "view_all",
      ]);
    const a = new Set<string>();
    for (const up of userPermissions) {
      if (!up.permission?.action) continue;
      const mid = up.permission.module?.id ?? up.permission.module_id;
      if (mid === moduleConfig.id) a.add(up.permission.action);
    }
    return a;
  }, [moduleConfig, userPermissions]);

  const rowButtons = useMemo(
    () =>
      !moduleConfig?.button_config
        ? []
        : moduleConfig.button_config
            .filter((b) => b.position === "row" && permittedActions.has(b.key))
            .sort((a, b) => (a.order ?? 99) - (b.order ?? 99)),
    [moduleConfig, permittedActions],
  );
  const toolbarButtons = useMemo(
    () =>
      !moduleConfig?.button_config
        ? []
        : moduleConfig.button_config
            .filter(
              (b) => b.position === "toolbar" && permittedActions.has(b.key),
            )
            .sort((a, b) => (a.order ?? 99) - (b.order ?? 99)),
    [moduleConfig, permittedActions],
  );

  // ── Server-side page fetch + client-side filters ──────────────────────────
  const fetchPage = useCallback(
    (
      page: number,
      limit: number,
      search: string,
      status: string,
      stage: string,
      start: string,
      end: string,
      month: string = "all",
      year: string = "all",
    ) => {
      setLoading(true);
      setSelectedRows([]);
      setExpandedRows([]);

      console.log("[AUDIT-FILTER] fetchPage called with:", {
        page,
        limit,
        search,
        status,
        stage,
        start,
        end,
        month,
        year,
      });

      getCompanyAuditsPaginated({
        page,
        limit,
        ...(search && { search }),
        ...(status !== "all" && { status }),
        // Only send auditStageId to server if `stage` is numeric.
        // For text values (Stage 1, Surveillance, etc.) we filter client-side below.
        ...(stage !== "all" &&
          !isNaN(Number(stage)) && { auditStageId: Number(stage) }),
        ...(start && { startDate: start }),
        ...(end && { endDate: end }),
      })
        .then((res) => {
          let rows = mapCompanyAuditsApiResponse(res.data);
          const beforeCount = rows.length;
          if (search && search.trim()) {
            const needle = search.toLowerCase().trim();
            rows = rows.filter((r) => {
              const anyR = r as any;
              const haystack = [
                anyR.companyName,
                anyR.auditBy,
                anyR.leadAuditor,
                anyR.auditStage,
                anyR.auditType,
                anyR.auditMode,
                anyR.auditCode,
                anyR.raw?.auditCode,
                anyR.raw?.company?.name,
                anyR.raw?.company?.company_code,
                anyR.raw?.auditType?.name,
                anyR.raw?.standard?.name,
                anyR.raw?.currentStage,
                anyR.findings,
                anyR.notes,
              ]
                .filter(Boolean)
                .map((s) => String(s).toLowerCase());
              return haystack.some((h) => h.includes(needle));
            });
            console.log(
              `[AUDIT-FILTER] Search="${search}" → ${rows.length}/${beforeCount} rows`,
            );
          }
          // ── Client-side stage filter (text match against auditStage / currentStage) ──
          if (stage !== "all" && isNaN(Number(stage))) {
            const needle = stage.toLowerCase().trim();
            rows = rows.filter((r) => {
              const anyR = r as any;
              const candidates = [
                anyR.auditStage,
                anyR.raw?.currentStage,
                anyR.raw?.stages?.[0]?.stageName,
              ]
                .filter(Boolean)
                .map((s) => String(s).toLowerCase());
              return candidates.some((c) => c.includes(needle));
            });
            console.log(
              `[AUDIT-FILTER] Stage="${stage}" → ${rows.length}/${beforeCount} rows`,
            );
          }

          // ── Client-side Month / Year filter ───────────────────────────────
          if (month !== "all" || year !== "all") {
            const before = rows.length;
            rows = rows.filter((r) => {
              const anyR = r as any;

              // Try every date source we can find
              const dateCandidates = [
                anyR.raw?.stages?.[0]?.auditDate,
                anyR.raw?.createdAt,
                anyR.raw?.created_at,
                anyR.auditDate,
                anyR.createdAt,
                anyR.created_at,
              ].filter(Boolean);

              let yr: string | null = null;
              let mo: string | null = null;

              for (const candidate of dateCandidates) {
                const d = new Date(candidate);
                if (!isNaN(d.getTime())) {
                  yr = String(d.getFullYear());
                  mo = String(d.getMonth() + 1).padStart(2, "0");
                  break;
                }
              }

              // Fallback to raw validityPeriod e.g. "2025-2026"
              if (
                year !== "all" &&
                !yr &&
                typeof anyR.raw?.validityPeriod === "string"
              ) {
                const years: string[] =
                  anyR.raw.validityPeriod.match(/\d{4}/g) || []; // ✅ same fix
                if (years.includes(year)) yr = year;
              }

              // Fallback to row.auditYear (which is now "2025-2026" string)
              if (!yr && anyR.auditYear && anyR.auditYear !== "—") {
                const ayStr = String(anyR.auditYear);
                const years: string[] = ayStr.match(/\d{4}/g) || []; // ✅ explicit type
                if (year !== "all" && years.includes(year)) yr = year;
                else if (year === "all") yr = years[0] || null;
              }

              if (year !== "all" && yr !== year) return false;
              if (month !== "all" && mo !== month) return false;
              return true;
            });
            console.log(
              `[AUDIT-FILTER] Month=${month} Year=${year} → ${rows.length}/${before} rows`,
            );
          }

          setData(rows);
          setMeta(res.meta);
          addDebug(
            `✅ Page ${page}: showing ${rows.length} of ${res.meta.total} total`,
          );
        })
        .catch((err) => setError(err.message))
        .finally(() => setLoading(false));
    },
    [addDebug],
  );

  // ── Initial load ────────────────────────────────────────────────────────────
  useEffect(() => {
    const init = async () => {
      setPermissionsLoading(true);
      setDebugLog([]);
      addDebug("🚀 Company Audits starting...");
      const [moduleOk, permsOk] = await Promise.all([
        fetchModuleConfig(),
        fetchUserPermissions(),
      ]);
      setPermissionSystemReady(moduleOk && permsOk);
      setPermissionsLoading(false);
    };
    init();
    fetchPage(1, itemsPerPage, "", "all", "all", "", "", "all", "all");
    setCurrentPage(1);

    getAuditStageOptions()
      .then(setStageOptions)
      .catch(() => addDebug("⚠️ Audit stage options fetch failed"));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [refreshFlag]);

  // ── Page / limit change ─────────────────────────────────────────────────────
  useEffect(() => {
    fetchPage(
      currentPage,
      itemsPerPage,
      debouncedSearch,
      statusFilter,
      stageFilter,
      startDate,
      endDate,
      monthFilter,
      yearFilter,
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, itemsPerPage]);

  // ── Filter / search change → reset to page 1 ───────────────────────────────
  useEffect(() => {
    setCurrentPage(1);
    fetchPage(
      1,
      itemsPerPage,
      debouncedSearch,
      statusFilter,
      stageFilter,
      startDate,
      endDate,
      monthFilter,
      yearFilter,
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    debouncedSearch,
    statusFilter,
    stageFilter,
    startDate,
    endDate,
    monthFilter,
    yearFilter,
  ]);

  const refresh = () =>
    fetchPage(
      currentPage,
      itemsPerPage,
      debouncedSearch,
      statusFilter,
      stageFilter,
      startDate,
      endDate,
      monthFilter,
      yearFilter,
    );

  const clearAllFilters = () => {
    setSearchTerm("");
    setStartDate("");
    setEndDate("");
    setStatusFilter("all");
    setStageFilter("all");
    setMonthFilter("all");
    setYearFilter("all");
  };

  const handleDelete = async (row: CompanyAuditRow) => {
    const { confirmed, error: delErr } = await deleteWithConfirm(
      `audit for ${row.companyName}`,
      () => deleteCompanyAudit(row.id),
      { successMessage: "Audit deleted.", errorMessage: "Failed to delete." },
    );
    if (confirmed && !delErr) refresh();
  };
  const handleEdit = (row: CompanyAuditRow) => {
    setEditingId(row.id);
    setIsEditModalOpen(true);
  };
  const handleView = (row: CompanyAuditRow) =>
    setExpandedRows((p) => (p.includes(row.sno) ? p : [...p, row.sno]));
  const handleAction = useCallback((row: CompanyAuditRow, key: string) => {
    if (key === "view") handleView(row);
    else if (key === "edit") handleEdit(row);
    else if (key === "delete") handleDelete(row);
    else if (key === "print") window.print();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (error)
    return (
      <div className={styles.errorContainer}>
        <div className={styles.errorIcon}>⚠️</div>
        <h3 className={styles.errorTitle}>Error</h3>
        <p className={styles.errorMessage}>{error}</p>
        <button className={styles.errorButton} onClick={refresh}>
          Retry
        </button>
      </div>
    );
  if (permissionsLoading) return <EnterpriseLoader />;

  const useDynamicMode = permissionSystemReady && moduleConfig !== null;
  const hasActionsColumn = visibleColumns.some((c) => c.key === "actions");
  const headerColumns = visibleColumns.filter((c) => c.key !== "actions");

  const anyFilterActive =
    !!searchTerm ||
    statusFilter !== "all" ||
    stageFilter !== "all" ||
    !!startDate ||
    !!endDate ||
    monthFilter !== "all" ||
    yearFilter !== "all";

  return (
    <div className={styles.container}>
      {/* ═══ DEBUG (userId=1 only) ═══ */}
      {Number(rawUserId?.userId) === 1 && (
        <div
          style={{
            margin: "0 0 16px",
            border: `2px solid ${useDynamicMode ? "#14b8a6" : "#f59e0b"}`,
            overflow: "hidden",
            background: useDynamicMode ? "#f0fdfa" : "#fffbeb",
            fontSize: 13,
          }}
        >
          <div
            onClick={() => setShowDebug(!showDebug)}
            style={{
              padding: "10px 16px",
              background: useDynamicMode ? "#0f766e" : "#f59e0b",
              color: "#fff",
              fontWeight: 700,
              cursor: "pointer",
              display: "flex",
              justifyContent: "space-between",
            }}
          >
            <span>
              {useDynamicMode ? "✅ DYNAMIC" : "⚠️ FALLBACK"} —{" "}
              {meta?.total?.toLocaleString() ?? 0} total audits
            </span>
            <span>{showDebug ? "▼" : "▶"}</span>
          </div>
          {showDebug && (
            <div style={{ padding: 16 }}>
              <details>
                <summary
                  style={{
                    cursor: "pointer",
                    fontWeight: 600,
                    color: "#0f766e",
                  }}
                >
                  📋 Debug Log
                </summary>
                <div
                  style={{
                    background: "#0f172a",
                    borderRadius: 6,
                    padding: 10,
                    maxHeight: 150,
                    overflow: "auto",
                    marginTop: 4,
                  }}
                >
                  {debugLog.map((l, i) => (
                    <div
                      key={i}
                      style={{
                        fontSize: 11,
                        color: l.includes("✅")
                          ? "#4ade80"
                          : l.includes("⚠️")
                            ? "#fbbf24"
                            : "#94a3b8",
                        fontFamily: "monospace",
                        marginBottom: 2,
                      }}
                    >
                      {l}
                    </div>
                  ))}
                </div>
              </details>
            </div>
          )}
        </div>
      )}

      {/* ═══ Filters ═══ */}
      <CompanyAuditFilters
        searchTerm={searchTerm}
        setSearchTerm={setSearchTerm}
        statusFilter={statusFilter}
        setStatusFilter={setStatusFilter}
        stageFilter={stageFilter}
        setStageFilter={setStageFilter}
        startDate={startDate}
        setStartDate={setStartDate}
        endDate={endDate}
        setEndDate={setEndDate}
        stageOptions={stageOptions}
        clearFilters={clearAllFilters}
        onRefresh={refresh}
        // Month / Year
        monthFilter={monthFilter}
        setMonthFilter={setMonthFilter}
        yearFilter={yearFilter}
        setYearFilter={setYearFilter}
        // Export & Analytics
        onExportPdf={() => {
          toast.success("PDF export — coming soon");
        }}
        onExportExcel={() => {
          toast.success("Excel export — coming soon");
        }}
        onAnalyticsToggle={() => {
          toast.success("Analytics — coming soon");
        }}
      />

      {/* ═══ Toolbar buttons (dynamic) ═══ */}
      {useDynamicMode && toolbarButtons.length > 0 && (
        <div
          style={{
            display: "flex",
            gap: 8,
            marginBottom: 12,
            flexWrap: "wrap",
          }}
        >
          {toolbarButtons.map((btn) => (
            <button
              key={btn.key}
              onClick={() =>
                btn.key === "create" &&
                (setEditingId(null), setIsEditModalOpen(true))
              }
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
                padding: "8px 16px",
                borderRadius: 8,
                border: `1px solid ${btn.color}33`,
                backgroundColor: `${btn.color}15`,
                color: btn.color,
                cursor: "pointer",
                fontSize: 13,
                fontWeight: 600,
              }}
            >
              {btn.icon} {btn.label || btn.key}
            </button>
          ))}
        </div>
      )}

      {/* ═══ Record count ═══ */}
      {meta && (
        <div
          style={{
            padding: "10px 16px",
            backgroundColor: "#f5f3ff",
            border: "1px solid #ddd6fe",
            borderRadius: 8,
            marginBottom: 12,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            fontSize: 13,
            color: "#6d28d9",
          }}
        >
          <span>
            🗂 Showing{" "}
            <strong>
              {data.length > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0}–
              {Math.min(
                (currentPage - 1) * itemsPerPage + data.length,
                meta.total,
              )}
            </strong>{" "}
            of <strong>{meta.total.toLocaleString()}</strong> audits
            {anyFilterActive && (
              <span style={{ marginLeft: 8, color: "#9ca3af" }}>
                (filtered)
              </span>
            )}
          </span>
          {anyFilterActive && (
            <button
              onClick={clearAllFilters}
              style={{
                background: "none",
                border: "none",
                color: "#7c3aed",
                cursor: "pointer",
                textDecoration: "underline",
                fontSize: 13,
              }}
            >
              Clear filters
            </button>
          )}
        </div>
      )}

      {/* ═══ TABLE ═══ */}
      <div className={styles.tableWrapper}>
        <table className={styles.table}>
          <thead>
            <tr>
              <th className={styles.expandCol}></th>
              <th className={styles.checkboxCol}>
                <input
                  type="checkbox"
                  className={styles.checkbox}
                  checked={
                    data.length > 0 &&
                    data.every((r) => selectedRows.includes(r.sno))
                  }
                  onChange={(e) =>
                    setSelectedRows(
                      e.target.checked ? data.map((r) => r.sno) : [],
                    )
                  }
                />
              </th>
              {useDynamicMode ? (
                <>
                  {headerColumns.map((col) => (
                    <th key={col.key} className={styles.th}>
                      {col.label}
                    </th>
                  ))}
                  {hasActionsColumn && rowButtons.length > 0 && (
                    <th className={styles.actionsCol}>Actions</th>
                  )}
                </>
              ) : (
                <>
                  <th className={styles.th}>Company</th>
                  <th className={styles.th}>Audit By</th>
                  <th className={styles.th}>Audit Type</th>
                  <th className={styles.th}>Audit Stage</th>
                  <th className={styles.th}>Audit Mode</th>
                  <th className={styles.th}>Audit Year</th>
                  <th className={styles.th}>Audit Status</th>
                  <th className={styles.th}>Created At</th>
                  <th className={styles.actionsCol}>Actions</th>
                </>
              )}
            </tr>
          </thead>

          <tbody>
            {loading ? (
              <tr>
                <td
                  colSpan={headerColumns.length + 3}
                  style={{ textAlign: "center", padding: 60, color: "#9ca3af" }}
                >
                  <div
                    style={{
                      display: "inline-block",
                      width: 28,
                      height: 28,
                      border: "3px solid #e5e7eb",
                      borderTopColor: "#7c3aed",
                      borderRadius: "50%",
                      animation: "spin 0.7s linear infinite",
                      marginBottom: 10,
                    }}
                  />
                  <p style={{ margin: 0 }}>Loading audits...</p>
                </td>
              </tr>
            ) : data.length > 0 ? (
              data.map((row) =>
                useDynamicMode ? (
                  <DynamicAuditRow
                    key={row.sno}
                    row={row}
                    visibleColumns={headerColumns}
                    rowButtons={rowButtons}
                    hasActionsColumn={hasActionsColumn && rowButtons.length > 0}
                    mapColumnKeyToValue={mapColumnKeyToValue}
                    isExpanded={expandedRows.includes(row.sno)}
                    toggleRowExpand={(id) =>
                      setExpandedRows((p) =>
                        p.includes(id) ? p.filter((r) => r !== id) : [...p, id],
                      )
                    }
                    isSelected={selectedRows.includes(row.sno)}
                    handleRowSelect={(id, checked) =>
                      setSelectedRows((p) =>
                        checked ? [...p, id] : p.filter((r) => r !== id),
                      )
                    }
                    onAction={handleAction}
                  />
                ) : (
                  <AuditRowFallback
                    key={row.sno}
                    row={row}
                    isExpanded={expandedRows.includes(row.sno)}
                    toggleRowExpand={(id) =>
                      setExpandedRows((p) =>
                        p.includes(id) ? p.filter((r) => r !== id) : [...p, id],
                      )
                    }
                    isSelected={selectedRows.includes(row.sno)}
                    handleRowSelect={(id, checked) =>
                      setSelectedRows((p) =>
                        checked ? [...p, id] : p.filter((r) => r !== id),
                      )
                    }
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                    onView={handleView}
                  />
                ),
              )
            ) : (
              <tr>
                <td
                  colSpan={headerColumns.length + 3}
                  style={{ textAlign: "center", padding: 60 }}
                >
                  <div
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "center",
                      gap: 12,
                    }}
                  >
                    <div style={{ fontSize: 36 }}>🗂</div>
                    <h3 style={{ margin: 0, color: "#111827" }}>
                      No Audits Found
                    </h3>
                    <p style={{ color: "#6b7280", margin: 0 }}>
                      {anyFilterActive
                        ? "No audits match your filters."
                        : "Get started by scheduling a new audit."}
                    </p>
                  </div>
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

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

      {/* ═══ Edit / Create Modal ═══ */}
      <CompanyAuditForm
        isOpen={isEditModalOpen}
        onClose={() => {
          setIsEditModalOpen(false);
          setEditingId(null);
        }}
        refreshData={refresh}
        editId={editingId}
      />
    </div>
  );
}
