"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import { Pagination } from "../companies/Pagination";
import { EnterpriseLoader } from "../../../../components/loader/loader";
import { fetchApi } from "@/lib/api/http";
import { deleteWithConfirm } from "../../../../components/ConfirmDialog/ConfirmDialog";
import { InquiryFilters } from "./InquiryFilters";
import InquiryAnalyticsInline from "./Filters/InquiryAnalyticsInline";
import {
  getInquiriesPaginated,
  deleteInquiry,
  generateDraft,
  confirmDraft,
  requestChanges,
  getPipelineSummary,
} from "@/lib/api/inquiry.api";
import {
  mapInquiriesApiResponse,
  STATUS_CONFIG,
  mapColumnKeyToValue, // ← ADD this
} from "@/lib/api/mappers/inquiry.mappers";
import type { InquiryRow, PaginationMeta } from "@/lib/api/types/inquiry.types";
import { InquiryRow as InquiryRowComponent } from "./InquiryRow";
import InquiryForm from "./Form/InquiryForm";
import InquiryViewModal from "./Form/InquiryViewModal";
import toast from "react-hot-toast";
import dynamic from "next/dynamic";

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

// ── Types ─────────────────────────────────────────────────────────────────────
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 InquiryTableProps {
  refreshFlag?: boolean;
}

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

// ── Fallback columns ───────────────────────────────────
const FALLBACK_COLUMNS: ColumnConfig[] = [
  {
    key: "inquiry_ref",
    type: "text",
    label: "Ref No.",
    order: 1,
    sortable: true,
    default_visible: true,
  },
  {
    key: "inquiry_type",
    type: "text",
    label: "Type",
    order: 2,
    sortable: true,
    default_visible: true,
  },
  {
    key: "company_name",
    type: "text",
    label: "Company",
    order: 3,
    sortable: true,
    default_visible: true,
  },
  {
    key: "auditor_name",
    type: "text",
    label: "Auditor",
    order: 4,
    sortable: true,
    default_visible: true,
  },
  // { key: 'standards',    type: 'custom',  label: 'Standards',    order: 5,  sortable: false, default_visible: true },
  {
    key: "status",
    type: "text",
    label: "Status",
    order: 6,
    sortable: true,
    default_visible: true,
  },
  {
    key: "submitted_by",
    type: "text",
    label: "Submitted By",
    order: 7,
    sortable: false,
    default_visible: true,
  },
  {
    key: "actions",
    type: "actions",
    label: "Actions",
    order: 99,
    sortable: false,
    default_visible: true,
  },
];

// ── Debounce hook ─────────────────────────────────
function useDebounce<T>(value: T, delay: number): T {
  const [d, setD] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setD(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return d;
}

// ── Pipeline config ────────────────────────────
const PIPELINE_STEPS = [
  {
    key: "PENDING",
    label: "Pending",
    color: "#d97706",
    bg: "#fffbeb",
    border: "#fde68a",
    icon: "⏳",
    step: 1,
    desc: "Marketing submitted — waiting for Scheme to review",
  },
  {
    key: "IN_REVIEW",
    label: "In Review",
    color: "#2563eb",
    bg: "#eff6ff",
    border: "#bfdbfe",
    icon: "🔍",
    step: 2,
    desc: "Scheme is filling certificate details & generating draft",
  },
  {
    key: "DRAFT_READY",
    label: "Draft Ready",
    color: "#7c3aed",
    bg: "#f5f3ff",
    border: "#ddd6fe",
    icon: "📄",
    step: 3,
    desc: "Draft generated — Marketing reviews & approves or requests changes",
  },
  {
    key: "CHANGES_REQUESTED",
    label: "Changes",
    color: "#dc2626",
    bg: "#fef2f2",
    border: "#fecaca",
    icon: "↩",
    step: 4,
    desc: "Marketing requested corrections — Scheme must fix & regenerate",
  },
  {
    key: "CLIENT_CONFIRMED",
    label: "Confirmed",
    color: "#059669",
    bg: "#f0fdf4",
    border: "#a7f3d0",
    icon: "✅",
    step: 5,
    desc: "Client approved the draft — Scheme issues final certificate",
  },
  {
    key: "FINAL_ISSUED",
    label: "Issued",
    color: "#0f766e",
    bg: "#f0fdfa",
    border: "#99f6e4",
    icon: "🏆",
    step: 6,
    desc: "Final certificate issued — process complete",
  },
];

// ── Pipeline Modal ─────────────────────────────────────────────────────────────
function PipelineModal({
  open,
  onClose,
  counts,
  total,
}: {
  open: boolean;
  onClose: () => void;
  counts: Record<string, number>;
  total: number;
}) {
  if (!open) return null;
  const safeTotal = total || 1;
  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 1200,
        backgroundColor: "rgba(0,0,0,0.55)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 16,
      }}
      onClick={onClose}
    >
      <div
        style={{
          backgroundColor: "#fff",
          borderRadius: 16,
          width: "100%",
          maxWidth: 680,
          boxShadow: "0 25px 80px rgba(0,0,0,0.25)",
          overflow: "hidden",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <div
          style={{
            padding: "18px 24px",
            borderBottom: "1px solid #e5e7eb",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            background: "linear-gradient(135deg, #0f766e 0%, #14b8a6 100%)",
          }}
        >
          <div>
            <h2
              style={{
                margin: 0,
                fontSize: 16,
                fontWeight: 700,
                color: "#fff",
              }}
            >
              📊 Inquiry Pipeline
            </h2>
            <p
              style={{
                margin: "2px 0 0",
                fontSize: 12,
                color: "rgba(255,255,255,0.75)",
              }}
            >
              {total.toLocaleString()} total inquiries across all stages
            </p>
          </div>
          <button
            onClick={onClose}
            style={{
              background: "rgba(255,255,255,0.2)",
              border: "none",
              borderRadius: 8,
              width: 32,
              height: 32,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              cursor: "pointer",
              color: "#fff",
              fontSize: 18,
              fontWeight: 700,
            }}
          >
            ✕
          </button>
        </div>
        <div style={{ padding: "16px 24px 0" }}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 0,
              marginBottom: 4,
            }}
          >
            {PIPELINE_STEPS.map((p, i) => (
              <React.Fragment key={p.key}>
                <div
                  style={{
                    flex: 1,
                    height: 6,
                    borderRadius:
                      i === 0
                        ? "99px 0 0 99px"
                        : i === PIPELINE_STEPS.length - 1
                          ? "0 99px 99px 0"
                          : 0,
                    backgroundColor:
                      (counts[p.key] ?? 0) > 0 ? p.color : "#e5e7eb",
                    transition: "background 0.2s",
                  }}
                />
                {i < PIPELINE_STEPS.length - 1 && (
                  <div
                    style={{
                      width: 0,
                      height: 0,
                      borderTop: "3px solid transparent",
                      borderBottom: "3px solid transparent",
                      borderLeft: `5px solid ${(counts[p.key] ?? 0) > 0 ? p.color : "#e5e7eb"}`,
                      flexShrink: 0,
                    }}
                  />
                )}
              </React.Fragment>
            ))}
          </div>
          <div style={{ display: "flex" }}>
            {PIPELINE_STEPS.map((p) => (
              <div key={p.key} style={{ flex: 1, textAlign: "center" }}>
                <div
                  style={{
                    fontSize: 9,
                    fontWeight: 700,
                    color: (counts[p.key] ?? 0) > 0 ? p.color : "#9ca3af",
                  }}
                >
                  {p.step}
                </div>
              </div>
            ))}
          </div>
        </div>
        <div
          style={{
            padding: "12px 24px 24px",
            display: "flex",
            flexDirection: "column",
            gap: 8,
          }}
        >
          {PIPELINE_STEPS.map((p) => {
            const count = counts[p.key] ?? 0;
            const pct = Math.round((count / safeTotal) * 100);
            const active = count > 0;
            return (
              <div
                key={p.key}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 14,
                  padding: "12px 16px",
                  borderRadius: 10,
                  backgroundColor: active ? p.bg : "#fafafa",
                  border: `1px solid ${active ? p.border : "#f3f4f6"}`,
                }}
              >
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: "50%",
                    flexShrink: 0,
                    backgroundColor: active ? p.color : "#e5e7eb",
                    color: "#fff",
                    fontSize: 12,
                    fontWeight: 800,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  {p.step}
                </div>
                <div style={{ width: 120, flexShrink: 0 }}>
                  <div
                    style={{
                      fontSize: 13,
                      fontWeight: 700,
                      color: active ? p.color : "#9ca3af",
                    }}
                  >
                    {p.icon} {p.label}
                  </div>
                  <div
                    style={{
                      fontSize: 10,
                      color: "#9ca3af",
                      marginTop: 2,
                      lineHeight: 1.3,
                    }}
                  >
                    {p.desc}
                  </div>
                </div>
                <div style={{ flex: 1 }}>
                  <div
                    style={{
                      height: 6,
                      borderRadius: 99,
                      backgroundColor: "#e5e7eb",
                      overflow: "hidden",
                    }}
                  >
                    <div
                      style={{
                        height: "100%",
                        borderRadius: 99,
                        backgroundColor: active ? p.color : "transparent",
                        width: `${pct}%`,
                        transition: "width 0.5s ease",
                      }}
                    />
                  </div>
                </div>
                <div
                  style={{ textAlign: "right", flexShrink: 0, minWidth: 52 }}
                >
                  <div
                    style={{
                      fontSize: 22,
                      fontWeight: 900,
                      lineHeight: 1,
                      color: active ? p.color : "#d1d5db",
                    }}
                  >
                    {count}
                  </div>
                  {active && (
                    <div
                      style={{ fontSize: 10, color: p.color, fontWeight: 600 }}
                    >
                      {pct}%
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── Request Changes Modal ─────────────────────────────────────────────────────
function RequestChangesModal({
  open,
  onClose,
  onSubmit,
}: {
  open: boolean;
  onClose: () => void;
  onSubmit: (notes: string) => void;
}) {
  const [notes, setNotes] = useState("");
  if (!open) return null;
  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 1100,
        backgroundColor: "rgba(0,0,0,0.5)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 16,
      }}
    >
      <div
        style={{
          backgroundColor: "#fff",
          borderRadius: 12,
          width: "100%",
          maxWidth: 480,
          padding: 24,
          boxShadow: "0 20px 60px rgba(0,0,0,0.2)",
        }}
      >
        <h3
          style={{
            margin: "0 0 6px",
            fontSize: 16,
            fontWeight: 700,
            color: "#111827",
          }}
        >
          ↩ Request Changes
        </h3>
        <p style={{ margin: "0 0 16px", fontSize: 13, color: "#6b7280" }}>
          Describe what needs to be changed so Scheme can fix it.
        </p>
        <textarea
          value={notes}
          rows={4}
          onChange={(e) => setNotes(e.target.value)}
          placeholder="e.g. Fix the address, add ISO 45001 standard, update expiry date..."
          style={{
            width: "100%",
            borderRadius: 8,
            border: "1.5px solid #e5e7eb",
            padding: "10px 12px",
            fontSize: 13,
            resize: "vertical",
            marginBottom: 16,
            boxSizing: "border-box",
          }}
        />
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
          <button
            onClick={() => {
              onClose();
              setNotes("");
            }}
            style={{
              padding: "9px 18px",
              borderRadius: 8,
              border: "1px solid #e5e7eb",
              backgroundColor: "#fff",
              color: "#6b7280",
              cursor: "pointer",
              fontSize: 14,
            }}
          >
            Cancel
          </button>
          <button
            onClick={() => {
              if (!notes.trim()) {
                toast.error("Please describe the changes needed");
                return;
              }
              onSubmit(notes);
              onClose();
              setNotes("");
            }}
            style={{
              padding: "9px 20px",
              borderRadius: 8,
              border: "none",
              backgroundColor: "#ef4444",
              color: "#fff",
              cursor: "pointer",
              fontSize: 14,
              fontWeight: 600,
            }}
          >
            Send to Scheme
          </button>
        </div>
      </div>
    </div>
  );
}

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

  const [pipelineCounts, setPipelineCounts] = useState<Record<string, number>>(
    {},
  );
  const [allData, setAllData] = useState<InquiryRow[]>([]);
  const [allDataLoading, setAllDataLoading] = useState(false);
  const [showAnalytics, setShowAnalytics] = useState(false);
  const [analyticsLoaded, setAnalyticsLoaded] = useState(false);

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

  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(20);

  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [monthFilter, setMonthFilter] = useState("all");
  const debouncedSearch = useDebounce(searchTerm, 400);

  // ✅ NEW — User filter state (super admin / scheme can filter by submitter)
  type SubmitterOpt = {
    id: number;
    firstName?: string;
    lastName?: string;
    email?: string;
  };
  const [userFilter, setUserFilter] = useState("all");
  const [submitters, setSubmitters] = useState<SubmitterOpt[]>([]);

  // ── Modals ────────────────────────────────────────────────────────────────
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [changeRow, setChangeRow] = useState<InquiryRow | null>(null);
  const [generating, setGenerating] = useState<number | null>(null);
  const [showPipeline, setShowPipeline] = useState(false);
  const [viewRow, setViewRow] = useState<InquiryRow | null>(null); // ✅ FIXED — was missing

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

  const addDebug = useCallback((msg: string) => {
    console.log(`[INQUIRY-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 === "inquiries" || m.name === "inquiries",
      );
      if (mod) {
        setModuleConfig(mod);
        addDebug(`✅ inquiries 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("access_token");
            if (t) {
              const p = JSON.parse(atob(t.split(".")[1]));
              userId = p?.id || p?.userId || p?.sub;
              source = "JWT";
            }
          } catch {}
        }
      }
      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;
    }
    return cond
      ? all.filter((c) =>
          cond!
            .split(",")
            .map((k) => k.trim())
            .includes(c.key),
        )
      : all;
  }, [moduleConfig, userPermissions]);

  const permittedActions = useMemo((): Set<string> => {
    if (!moduleConfig)
      return new Set(["view", "edit", "delete", "create", "export"]);

    const a = new Set<string>();
    for (const up of userPermissions) {
      const action = up.permission?.action ?? up.action;
      const moduleId =
        up.permission?.module?.id ??
        up.permission?.module_id ??
        up.module?.id ??
        up.module_id;

      if (!action) continue;
      if (moduleId === moduleConfig.id) {
        a.add(action);
      }
    }

    // 🎯 BETTER DEBUG — prints values directly without needing to expand
    console.log("🎯 ACTIONS:", Array.from(a).join(", ") || "(empty)");
    console.log("🎯 PERMS COUNT:", userPermissions.length);
    console.log("🎯 MODULE ID:", moduleConfig.id);
    console.log("🎯 SAMPLE PERM:", JSON.stringify(userPermissions[0], null, 2));

    return a;
  }, [moduleConfig, userPermissions]);

  // ✅ NEW — Detect if current user is super admin (1, 8) OR has scheme role
  const canFilterByUser = useMemo(() => {
    const uid = Number(rawUserId?.userId);
    if (uid === 1 || uid === 8) return true;

    // Check if user has scheme role via permissions
    for (const up of userPermissions) {
      const roleName = (
        up.role?.name ??
        up.permission?.role?.name ??
        ""
      ).toLowerCase();
      if (roleName === "scheme") return true;
    }
    return false;
  }, [rawUserId, 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],
  );

  // ✅ UPDATED — fetchPage now accepts submittedBy filter
  const fetchPage = useCallback(
    (
      page: number,
      limit: number,
      search: string,
      status: string,
      submittedBy?: string,
    ) => {
      setLoading(true);
      setSelectedRows([]);
      setExpandedRows([]);
      getInquiriesPaginated({
        page,
        limit,
        ...(search && { search }),
        ...(status !== "all" && { status }),
        ...(submittedBy &&
          submittedBy !== "all" && { submitted_by_id: submittedBy }), // ✅ NEW
      })
        .then((res) => {
          setData(mapInquiriesApiResponse(res.data));
          setMeta(res.meta);
          addDebug(
            `✅ Page ${page}: ${res.data.length} of ${res.meta.total} total`,
          );
        })
        .catch((err) => setError(err.message))
        .finally(() => setLoading(false));
    },
    [addDebug],
  );

  const fetchPipelineCounts = useCallback(() => {
    getPipelineSummary()
      .then((counts) => {
        setPipelineCounts(counts);
        addDebug(`📊 Pipeline counts loaded`);
      })
      .catch(() => addDebug("⚠️ Pipeline summary failed"));
  }, [addDebug]);

  const fetchAllForAnalytics = useCallback(() => {
    if (analyticsLoaded) return;
    setAllDataLoading(true);
    getInquiriesPaginated({ page: 1, limit: 9999 })
      .then((res) => {
        setAllData(mapInquiriesApiResponse(res.data));
        setAnalyticsLoaded(true);
        addDebug(`📊 Analytics: ${res.data.length} total inquiries loaded`);
      })
      .catch(() => addDebug("⚠️ Analytics data fetch failed"))
      .finally(() => setAllDataLoading(false));
  }, [addDebug, analyticsLoaded]);

  const handleAnalyticsToggle = useCallback(() => {
    setShowAnalytics((v) => {
      if (!v) fetchAllForAnalytics();
      return !v;
    });
  }, [fetchAllForAnalytics]);

  useEffect(() => {
    const init = async () => {
      setPermissionsLoading(true);
      setDebugLog([]);
      addDebug("🚀 Inquiries starting...");
      const [moduleOk, permsOk] = await Promise.all([
        fetchModuleConfig(),
        fetchUserPermissions(),
      ]);
      setPermissionSystemReady(moduleOk && permsOk);
      setPermissionsLoading(false);
    };
    init();
    fetchPage(1, itemsPerPage, "", "all");
    fetchPipelineCounts();
    setCurrentPage(1);
    setAnalyticsLoaded(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [refreshFlag]);

  // ✅ UPDATED — pass userFilter to fetchPage
  useEffect(() => {
    fetchPage(
      currentPage,
      itemsPerPage,
      debouncedSearch,
      statusFilter,
      userFilter,
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, itemsPerPage]);

  // ✅ NEW — Fetch users list directly from /users endpoint (super admin / scheme only)
  useEffect(() => {
    if (!canFilterByUser) return;

    fetchApi<any>(`${API_BASE_URL}/users`)
      .then((res) => {
        // Handle different response shapes: array, { data: [...] }, or { data: { data: [...] } }
        const raw = Array.isArray(res)
          ? res
          : Array.isArray(res?.data)
            ? res.data
            : Array.isArray(res?.data?.data)
              ? res.data.data
              : [];

        // Map to the shape our dropdown expects
        const list = raw.map((u: any) => ({
          id: u.id,
          firstName: u.firstName ?? u.first_name ?? "",
          lastName: u.lastName ?? u.last_name ?? "",
          email: u.email ?? "",
        }));

        // Sort by firstName for nice display
        list.sort((a: any, b: any) =>
          (a.firstName || a.email).localeCompare(b.firstName || b.email),
        );

        setSubmitters(list);
        addDebug(`👥 Loaded ${list.length} users from /users`);
        console.log("👥 Users loaded:", list);
      })
      .catch((err) => {
        addDebug(`⚠️ Users fetch failed: ${err.message}`);
        console.error("Users fetch error:", err);
        setSubmitters([]);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [canFilterByUser, addDebug]);
  // ✅ UPDATED — refetch when userFilter changes
  useEffect(() => {
    setCurrentPage(1);
    fetchPage(1, itemsPerPage, debouncedSearch, statusFilter, userFilter);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debouncedSearch, statusFilter, userFilter]);

  // ✅ UPDATED — refresh now passes userFilter too
  const refresh = () => {
    fetchPage(
      currentPage,
      itemsPerPage,
      debouncedSearch,
      statusFilter,
      userFilter,
    );
    fetchPipelineCounts();
    setAnalyticsLoaded(false);
    if (showAnalytics) {
      setAllData([]);
      fetchAllForAnalytics();
    }
  };

  // ✅ UPDATED — clear also resets userFilter
  const clearAllFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setMonthFilter("all");
    setUserFilter("all");
  };

  // ── Actions ───────────────────────────────────────────────────────────────
  const handleEdit = (row: InquiryRow) => {
    setEditingId(row.id);
    setIsFormOpen(true);
  };

  const handleView = (row: InquiryRow) => {
    setViewRow(row); // ✅ opens view modal
    setExpandedRows((p) => (p.includes(row.sno) ? p : [...p, row.sno])); // keeps toggle too
  };

  const handleDelete = async (row: InquiryRow) => {
    const { confirmed, error: e } = await deleteWithConfirm(
      row.inquiry_ref,
      () => deleteInquiry(row.id),
      { successMessage: "Inquiry deleted.", errorMessage: "Failed to delete." },
    );
    if (confirmed && !e) refresh();
  };

  const handleGenerate = async (row: InquiryRow) => {
    if (!row.certificate_number) {
      toast.error(
        "⚠️ Fill Certificate Number first — Edit → set fields → status IN_REVIEW → Save",
      );
      return;
    }
    setGenerating(row.id);
    try {
      await generateDraft(row.id);
      toast.success("✅ Draft generated! PDF and Word files are ready.");
      refresh();
    } catch (err: any) {
      toast.error(err.message || "Failed to generate draft");
    } finally {
      setGenerating(null);
    }
  };

  const handleConfirm = async (row: InquiryRow) => {
    try {
      await confirmDraft(row.id);
      toast.success(
        "✅ Client confirmed! Scheme will issue the final certificate.",
      );
      refresh();
    } catch (err: any) {
      toast.error(err.message || "Failed to confirm");
    }
  };

  const handleRequestChanges = (row: InquiryRow) => setChangeRow(row);

  const submitChanges = async (notes: string) => {
    if (!changeRow) return;
    try {
      await requestChanges(changeRow.id, notes);
      toast.success("Change request sent to Scheme department.");
      refresh();
    } catch (err: any) {
      toast.error(err.message || "Failed to send request");
    }
  };

  const handleAction = useCallback((row: InquiryRow, key: string) => {
    switch (key) {
      case "view":
        handleView(row);
        break;
      case "edit":
        handleEdit(row);
        break;
      case "delete":
        handleDelete(row);
        break;
      case "generate-draft":
        handleGenerate(row);
        break;
      case "confirm":
        handleConfirm(row);
        break;
      case "request-changes":
        handleRequestChanges(row);
        break;
      default:
        console.warn("[InquiryTable] Unknown action:", key);
    }
    // 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");

  return (
    <div className={styles.container}>
      {/* ═══ VIEW MODAL ══════════════════════════════════════════════════ */}
      <InquiryViewModal row={viewRow} onClose={() => setViewRow(null)} />

      {/* ═══ PIPELINE MODAL ══════════════════════════════════════════════ */}
      <PipelineModal
        open={showPipeline}
        onClose={() => setShowPipeline(false)}
        counts={pipelineCounts}
        total={meta?.total ?? 0}
      />

      {/* ═══ 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: "13px",
          }}
        >
          <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
            </span>
            <span>{showDebug ? "▼" : "▶"}</span>
          </div>
          {showDebug && (
            <div style={{ padding: "16px" }}>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(4,1fr)",
                  gap: "10px",
                  marginBottom: "12px",
                }}
              >
                {[
                  {
                    ok: !!moduleConfig,
                    title: moduleConfig
                      ? `Module #${moduleConfig.id}`
                      : "No Module",
                    detail: `${moduleConfig?.button_config?.length || 0}b ${moduleConfig?.column_config?.length || 0}c`,
                  },
                  {
                    ok: !!rawUserId?.userId,
                    title: rawUserId?.userId
                      ? `User #${rawUserId.userId}`
                      : "No User",
                    detail: rawUserId?.source || "",
                  },
                  {
                    ok: !!meta,
                    title: meta
                      ? `${meta.total.toLocaleString()} DB Records`
                      : "—",
                    detail: meta ? `Page ${meta.page}/${meta.totalPages}` : "",
                  },
                  {
                    ok: Object.keys(pipelineCounts).length > 0,
                    title: "Pipeline Counts",
                    detail: `${Object.values(pipelineCounts).reduce((a, b) => a + b, 0)} total`,
                  },
                ].map((c, i) => (
                  <div
                    key={i}
                    style={{
                      padding: 10,
                      background: c.ok ? "#dcfce7" : "#fef2f2",
                      borderRadius: 8,
                      textAlign: "center",
                    }}
                  >
                    <div
                      style={{
                        fontWeight: 700,
                        color: c.ok ? "#166534" : "#991b1b",
                        fontSize: 13,
                      }}
                    >
                      {c.ok ? "✅" : "❌"} {c.title}
                    </div>
                    <div
                      style={{ fontSize: 11, color: "#64748b", marginTop: 2 }}
                    >
                      {c.detail}
                    </div>
                  </div>
                ))}
              </div>
              <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>
      )}

      {/* ═══ Toolbar buttons (dynamic mode) ══════════════════════════════ */}
      {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), setIsFormOpen(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>
      )}

      {/* ═══ Filters ═════════════════════════════════════════════════════ */}
      <InquiryFilters
        searchTerm={searchTerm}
        setSearchTerm={setSearchTerm}
        statusFilter={statusFilter}
        setStatusFilter={setStatusFilter}
        monthFilter={monthFilter}
        setMonthFilter={setMonthFilter}
        clearFilters={clearAllFilters}
        onRefresh={refresh}
        onAnalyticsToggle={handleAnalyticsToggle}
        showAnalytics={showAnalytics}
        onPipelineView={() => setShowPipeline(true)}
        // ✅ NEW — User filter props (super admin / scheme only)
        showUserFilter={canFilterByUser}
        userFilter={userFilter}
        setUserFilter={setUserFilter}
        submitters={submitters}
      />

      {/* ═══ Analytics ═══════════════════════════════════════════════════ */}
      {showAnalytics && (
        <InquiryAnalyticsInline
          inquiries={allData}
          statusFilter={statusFilter}
          monthFilter={monthFilter}
        />
      )}

      {/* ═══ Record count ════════════════════════════════════════════════ */}
      {meta && (
        <div
          style={{
            padding: "10px 16px",
            backgroundColor: "#f0fdfa",
            border: "1px solid #99f6e4",
            borderRadius: 8,
            marginBottom: 12,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            fontSize: 13,
            color: "#0f766e",
          }}
        >
          <span>
            📋 Showing{" "}
            <strong>
              {(currentPage - 1) * itemsPerPage + 1}–
              {Math.min(currentPage * itemsPerPage, meta.total)}
            </strong>{" "}
            of <strong>{meta.total.toLocaleString()}</strong> inquiries
            {(searchTerm ||
              statusFilter !== "all" ||
              monthFilter !== "all" ||
              userFilter !== "all") && (
              <span style={{ marginLeft: 8, color: "#9ca3af" }}>
                (filtered)
              </span>
            )}
          </span>
          {(searchTerm ||
            statusFilter !== "all" ||
            monthFilter !== "all" ||
            userFilter !== "all") && (
            <button
              onClick={clearAllFilters}
              style={{
                background: "none",
                border: "none",
                color: "#0f766e",
                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}>Ref No.</th>
                  <th className={styles.th}>Type</th>
                  <th className={styles.th}>Company</th>
                  <th className={styles.th}>Auditor / Date</th>
                  {/* <th className={styles.th}>Standards</th> */}
                  <th className={styles.th}>Status</th>
                  <th className={styles.th}>Submitted By</th>
                  <th className={styles.actionsCol}>Actions</th>
                </>
              )}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td
                  colSpan={headerColumns.length + 3}
                  style={{
                    textAlign: "center",
                    padding: "60px",
                    color: "#9ca3af",
                  }}
                >
                  <div
                    style={{
                      display: "inline-block",
                      width: 28,
                      height: 28,
                      border: "3px solid #e5e7eb",
                      borderTopColor: "#14b8a6",
                      borderRadius: "50%",
                      animation: "spin 0.7s linear infinite",
                      marginBottom: 10,
                    }}
                  />
                  <p style={{ margin: 0 }}>Loading...</p>
                </td>
              </tr>
            ) : data.length > 0 ? (
              data.map((row) =>
                useDynamicMode ? (
                  <DynamicInquiryRow
                    key={row.sno}
                    row={row}
                    visibleColumns={headerColumns}
                    rowButtons={rowButtons}
                    hasActionsColumn={hasActionsColumn && rowButtons.length > 0}
                    mapColumnKeyToValue={mapColumnKeyToValue}
                    isExpanded={expandedRows.includes(row.sno)}
                    isSelected={selectedRows.includes(row.sno)}
                    generating={generating === row.id}
                    toggleRowExpand={(sno) =>
                      setExpandedRows((p) =>
                        p.includes(sno)
                          ? p.filter((r) => r !== sno)
                          : [...p, sno],
                      )
                    }
                    handleRowSelect={(sno, checked) =>
                      setSelectedRows((p) =>
                        checked ? [...p, sno] : p.filter((r) => r !== sno),
                      )
                    }
                    onAction={handleAction}
                  />
                ) : (
                  <InquiryRowComponent
                    key={row.sno}
                    row={row}
                    isExpanded={expandedRows.includes(row.sno)}
                    isSelected={selectedRows.includes(row.sno)}
                    toggleRowExpand={(sno) =>
                      setExpandedRows((p) =>
                        p.includes(sno)
                          ? p.filter((r) => r !== sno)
                          : [...p, sno],
                      )
                    }
                    handleRowSelect={(sno, checked) =>
                      setSelectedRows((p) =>
                        checked ? [...p, sno] : p.filter((r) => r !== sno),
                      )
                    }
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                    onView={handleView}
                    onGenerate={handleGenerate}
                    onConfirm={handleConfirm}
                    onRequestChanges={handleRequestChanges}
                    generating={generating === row.id}
                  />
                ),
              )
            ) : (
              <tr>
                <td
                  colSpan={headerColumns.length + 3}
                  style={{ textAlign: "center", padding: "60px" }}
                >
                  <div
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "center",
                      gap: 12,
                    }}
                  >
                    <div style={{ fontSize: 36 }}>📋</div>
                    <h3 style={{ margin: 0, color: "#111827" }}>
                      No Inquiries Found
                    </h3>
                    <p style={{ color: "#6b7280", margin: 0 }}>
                      {searchTerm ||
                      statusFilter !== "all" ||
                      monthFilter !== "all" ||
                      userFilter !== "all"
                        ? "No inquiries match your filters."
                        : "Get started by creating a new inquiry."}
                    </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);
          }}
        />
      )}

      {/* ═══ Inquiry Form Modal ══════════════════════════════════════════ */}
      <InquiryForm
        isOpen={isFormOpen}
        onClose={() => {
          setIsFormOpen(false);
          setEditingId(null);
        }}
        refreshData={refresh}
        editId={editingId}
      />

      {/* ═══ Request Changes Modal ═══════════════════════════════════════ */}
      <RequestChangesModal
        open={!!changeRow}
        onClose={() => setChangeRow(null)}
        onSubmit={submitChanges}
      />
    </div>
  );
}
