"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import styles from "../commonstyle/dattabale.module.css";
import { EnterpriseLoader } from "../../../../components/loader/loader";
import { Pagination } from "../companies/Pagination";
import { fetchApi } from "@/lib/api/http";
import MyAuditsHeader from "./MyAuditsHeader";
import MyAuditsFilters from "./MyAuditsFilters";
import MyAuditsAnalyticsInline from "./MyAuditsAnalyticsInline";
import MyAuditRowComponent from "./MyAuditRow";
import { getMyAudits, markAuditComplete } from "@/lib/api/my-audits.api";
import type {
  MyAuditRow,
  RowStatus,
  AuditType,
  MyAuditsDatePreset,
} from "@/lib/api/types/my-audits.types";

// ── Permission system types (mirrors InquiryTable) ────────────────
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[];
}

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

// ── Fallback columns (used when module config not loaded) ─────────
const FALLBACK_COLUMNS: ColumnConfig[] = [
  { key: "audit_code", type: "text", label: "Audit Code", order: 1, sortable: true, default_visible: true },
  { key: "company_name", type: "text", label: "Company", order: 2, sortable: true, default_visible: true },
  { key: "schedule_date", type: "date", label: "Date / Time", order: 3, sortable: true, default_visible: true },
  { key: "standards", type: "custom", label: "Standards", order: 4, sortable: false, default_visible: true },
  { key: "coordinator", type: "text", label: "Coordinator", order: 5, sortable: false, default_visible: true },
  { key: "lead_auditor", type: "text", label: "Lead Auditor", order: 6, sortable: false, default_visible: true },
  { key: "co_auditors", type: "custom", label: "Co-Auditor(s)", order: 6.5, sortable: false, default_visible: true },
  { key: "status", type: "text", label: "Status", order: 7, sortable: true, 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;
}

export default function MyAuditsPage() {
  const router = useRouter();

  // ── Data state ────────────────────────────────────────────────
  const [data, setData] = useState<MyAuditRow[]>([]);
  const [meta, setMeta] = useState<{
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  } | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [allData, setAllData] = useState<MyAuditRow[]>([]);
  const [analyticsLoaded, setAnalyticsLoaded] = useState(false);
  const [allDataLoading, setAllDataLoading] = useState(false);
  const [showAnalytics, setShowAnalytics] = useState(false);

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

  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<RowStatus | "all">("all");
  const [datePresetFilter, setDatePresetFilter] = useState<MyAuditsDatePreset>("all");
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");
  const [auditTypeFilter, setAuditTypeFilter] = useState<AuditType | "all">("all");
  const debouncedSearch = useDebounce(searchTerm, 400);

  const [completingId, setCompletingId] = useState<number | null>(null);

  // ── Permission system state (mirrors InquiryTable) ────────────
  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(`[MY-AUDITS-DEBUG] ${msg}`);
    setDebugLog((p) => [...p, `${new Date().toLocaleTimeString()} — ${msg}`]);
  }, []);

  // ── Fetch module config ───────────────────────────────────────
  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 === "my-audits" || m.name === "My Audits",
      );
      if (mod) {
        setModuleConfig(mod);
        addDebug(`✅ my-audits module (id:${mod.id})`);
        return true;
      }
      addDebug("⚠️ my-audits module NOT found — FALLBACK");
      return false;
    } catch (err: any) {
      addDebug(`⚠️ module fetch: ${err.message}`);
      return false;
    }
  }, [addDebug]);

  // ── Fetch user permissions ────────────────────────────────────
  const fetchUserPermissions = useCallback(async (): Promise<boolean> => {
    try {
      let userId: any = null;
      let 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]);

  // ── Compute visible columns ───────────────────────────────────
  const visibleColumns = useMemo((): ColumnConfig[] => {
    if (!moduleConfig?.column_config?.length) return FALLBACK_COLUMNS;
    return [...moduleConfig.column_config].sort(
      (a, b) => (a.order ?? 99) - (b.order ?? 99),
    );
  }, [moduleConfig]);

  // ── Compute permitted actions for THIS user on this module ────
  const permittedActions = useMemo((): Set<string> => {
    // No module config yet → default action set so UI isn't blank
    if (!moduleConfig) return new Set(["view", "complete"]);

    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);
      }
    }

    console.log("🎯 MY-AUDITS ACTIONS:", Array.from(a).join(", ") || "(empty)");
    console.log("🎯 MY-AUDITS PERMS COUNT:", userPermissions.length);
    console.log("🎯 MY-AUDITS MODULE ID:", moduleConfig.id);

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

  // ── Row buttons (only the ones user has permission for) ───────
  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],
  );

  // ── Toolbar buttons (filtered by perms) ───────────────────────
  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],
  );

  // ── Fetch one page of audits ──────────────────────────────────
  const fetchPage = useCallback(
    (
      page: number,
      limit: number,
      search: string,
      status: string,
      preset: string,
      from: string,
      to: string,
    ) => {
      setLoading(true);
      getMyAudits({
        page,
        limit,
        ...(search && { search }),
        ...(status !== "all" && { status }),
        ...(preset !== "all" && { date_preset: preset }),
        ...(from && { date_from: from }),
        ...(to && { date_to: to }),
      })
        .then((res) => {
          setData(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 fetchAllForAnalytics = useCallback(() => {
    if (analyticsLoaded) return;
    setAllDataLoading(true);
    getMyAudits({ page: 1, limit: 100 })
      .then((res) => {
        setAllData(res.data);
        setAnalyticsLoaded(true);
        addDebug(`📊 Analytics: ${res.data.length} total audits loaded`);
      })
      .catch(() => addDebug("⚠️ Analytics fetch failed"))
      .finally(() => setAllDataLoading(false));
  }, [analyticsLoaded, addDebug]);

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

  // ── Initial load: module + permissions + data ─────────────────
  useEffect(() => {
    const init = async () => {
      setPermissionsLoading(true);
      setDebugLog([]);
      addDebug("🚀 My Audits starting...");
      const [moduleOk, permsOk] = await Promise.all([
        fetchModuleConfig(),
        fetchUserPermissions(),
      ]);
      setPermissionSystemReady(moduleOk && permsOk);
      setPermissionsLoading(false);
    };
    init();
    fetchPage(1, itemsPerPage, "", "all", "all", "", "");
    setCurrentPage(1);
    setAnalyticsLoaded(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ── Re-fetch when page/limit changes ──────────────────────────
  useEffect(() => {
    fetchPage(currentPage, itemsPerPage, debouncedSearch, statusFilter, datePresetFilter, dateFrom, dateTo);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, itemsPerPage]);

  // ── Re-fetch when filters change ──────────────────────────────
  useEffect(() => {
    setCurrentPage(1);
    fetchPage(1, itemsPerPage, debouncedSearch, statusFilter, datePresetFilter, dateFrom, dateTo);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debouncedSearch, statusFilter, datePresetFilter, dateFrom, dateTo]);

  const visibleData =
    auditTypeFilter === "all"
      ? data
      : data.filter((r) => r.audit_type === auditTypeFilter);

  const refresh = () => {
    fetchPage(currentPage, itemsPerPage, debouncedSearch, statusFilter, datePresetFilter, dateFrom, dateTo);
    setAnalyticsLoaded(false);
    if (showAnalytics) {
      setAllData([]);
      fetchAllForAnalytics();
    }
  };

  const clearAllFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setDatePresetFilter("all");
    setDateFrom("");
    setDateTo("");
    setAuditTypeFilter("all");
  };

  const handleOpen = (row: MyAuditRow) => {
    if (!permittedActions.has("view") && !permittedActions.has("view-all")) {
      toast.error("You don't have permission to view audit details");
      return;
    }
    router.push(`/modules/audits/${row.id}`);
  };

  const handleMarkComplete = async (row: MyAuditRow) => {
    if (!permittedActions.has("complete")) {
      toast.error("You don't have permission to mark audits complete");
      return;
    }
    setCompletingId(row.id);
    try {
      await markAuditComplete(row.id);
      toast.success(`✅ Audit ${row.audit_code} marked complete`);
      refresh();
    } catch (err: any) {
      toast.error(err.message || "Failed to mark complete");
    } finally {
      setCompletingId(null);
    }
  };

  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 thStyle: React.CSSProperties = {
    padding: "10px",
    textAlign: "left",
    fontSize: 10,
    fontWeight: 700,
    color: "#6b7280",
    textTransform: "uppercase",
    letterSpacing: "0.05em",
  };

  return (
    <div className={styles.container}>
      {/* Purple gradient header */}
      <MyAuditsHeader totalAudits={meta?.total} onRefresh={refresh} />

      {/* ═══ DEBUG PANEL (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 ?? 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: permittedActions.size > 0,
                    title: `${permittedActions.size} action(s)`,
                    detail: Array.from(permittedActions).join(", ") || "(none)",
                  },
                  {
                    ok: !!meta,
                    title: meta ? `${meta.total} Records` : "—",
                    detail: meta ? `Page ${meta.page}/${meta.totalPages}` : "",
                  },
                ].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}
              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 */}
      <MyAuditsFilters
        searchTerm={searchTerm}
        setSearchTerm={setSearchTerm}
        statusFilter={statusFilter}
        setStatusFilter={setStatusFilter}
        datePresetFilter={datePresetFilter}
        setDatePresetFilter={setDatePresetFilter}
        dateFrom={dateFrom}
        setDateFrom={setDateFrom}
        dateTo={dateTo}
        setDateTo={setDateTo}
        auditTypeFilter={auditTypeFilter}
        setAuditTypeFilter={setAuditTypeFilter}
        clearFilters={clearAllFilters}
        onRefresh={refresh}
        onAnalyticsToggle={handleAnalyticsToggle}
        showAnalytics={showAnalytics}
      />

      {showAnalytics && (
        <MyAuditsAnalyticsInline
          audits={allData}
          statusFilter={statusFilter}
          auditTypeFilter={auditTypeFilter}
        />
      )}

      {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> audits
          </span>
        </div>
      )}

      <div className={styles.tableWrapper}>
        <table className={styles.table} style={{ tableLayout: "fixed", width: "100%" }}>
          <colgroup>
            <col style={{ width: 170 }} />
            <col style={{ width: 220 }} />
            <col style={{ width: 150 }} />
            <col style={{ width: 170 }} />
            <col style={{ width: 120 }} />
            <col style={{ width: 120 }} />
            <col style={{ width: 100 }} />
            <col style={{ width: 120 }} />
          </colgroup>
          <thead>
            <tr style={{ background: "#f8fafc" }}>
              <th style={thStyle}>Audit Code</th>
              <th style={thStyle}>Client</th>
              <th style={thStyle}>Date / Time</th>
              <th style={thStyle}>Standards</th>
              <th style={thStyle}>Coordinator</th>
              <th style={thStyle}>Lead Auditor</th>
              <th style={thStyle}>Co-Auditor(s)</th>
              <th style={thStyle}>Status</th>
              {hasActionsColumn && <th style={thStyle}>Actions</th>}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={9} style={{ textAlign: "center", padding: "60px" }}>
                  <EnterpriseLoader />
                </td>
              </tr>
            ) : visibleData.length === 0 ? (
              <tr>
                <td colSpan={9} style={{ textAlign: "center", padding: "60px" }}>
                  <div style={{ fontSize: 36 }}>📋</div>
                  <h3 style={{ margin: "12px 0 4px", color: "#111827" }}>
                    No audits found
                  </h3>
                  <p style={{ color: "#6b7280", margin: 0 }}>
                    {searchTerm || statusFilter !== "all" || datePresetFilter !== "all" || dateFrom || dateTo || auditTypeFilter !== "all"
                      ? "No audits match your filters."
                      : "No audits are assigned to you yet."}
                  </p>
                </td>
              </tr>
            ) : (
              visibleData.map((row) => (
                <MyAuditRowComponent
                  key={row.id}
                  row={row}
                  onOpen={handleOpen}
                  onMarkComplete={handleMarkComplete}
                  isCompleting={completingId === row.id}
                  permittedActions={permittedActions}
                />
              ))
            )}
          </tbody>
        </table>
      </div>

      {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);
          }}
        />
      )}
    </div>
  );
}