"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
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, API_BASE_URL as HTTP_API_BASE_URL } from "@/lib/api/http";
import ChecklistTemplatesHeader from "./ChecklistTemplatesHeader";
import ChecklistTemplatesFilters, {
  TemplateTypeFilter,
  StandardFilter,
} from "./ChecklistTemplatesFilters";
import ChecklistTemplateRow from "./ChecklistTemplateRow";
import ChecklistTemplateEditor from "./ChecklistTemplateEditor";
import {
  listChecklistTemplates,
  deleteChecklistTemplate,
} from "@/lib/api/checklist.api";
import type {
  ChecklistTemplate,
  Standard,
} from "@/lib/api/types/checklist.types";

// ── Permission system types (mirrors MyAuditsPage / 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: "template", type: "text", label: "Template", order: 1, sortable: true, default_visible: true },
  { key: "checklist_items", type: "custom", label: "Checklist Items", order: 2, 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;
}

export default function ChecklistTemplatesPage() {
  // ── Data state ────────────────────────────────────────────────
  const [templates, setTemplates] = useState<ChecklistTemplate[]>([]);
  const [standards, setStandards] = useState<Standard[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const [searchTerm, setSearchTerm] = useState("");
  const [typeFilter, setTypeFilter] = useState<TemplateTypeFilter>("all");
  const [standardFilter, setStandardFilter] = useState<StandardFilter>("all");
  const debouncedSearch = useDebounce(searchTerm, 400);

  const [view, setView] = useState<"list" | "edit">("list");
  const [editing, setEditing] = useState<ChecklistTemplate | null>(null);
  const [deletingId, setDeletingId] = useState<number | null>(null);

  // ── Permission system state (mirrors MyAuditsPage) ────────────
  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(`[CHECKLIST-TEMPLATES-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 === "checklist-templates" || m.name === "Checklist Templates",
      );
      if (mod) {
        setModuleConfig(mod);
        addDebug(`✅ checklist-templates module (id:${mod.id})`);
        return true;
      }
      addDebug("⚠️ checklist-templates 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", "create", "edit", "delete"]);

    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("🎯 CHECKLIST-TEMPLATES ACTIONS:", Array.from(a).join(", ") || "(empty)");
    console.log("🎯 CHECKLIST-TEMPLATES PERMS COUNT:", userPermissions.length);
    console.log("🎯 CHECKLIST-TEMPLATES MODULE ID:", moduleConfig.id);

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

  // ── 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 templates + standards ───────────────────────────────
  const fetchAll = useCallback(async () => {
    setLoading(true);
    try {
      const [templatesData, standardsRes] = await Promise.all([
        listChecklistTemplates(),
        fetchApi<Standard[] | { data: Standard[] }>(
          `${HTTP_API_BASE_URL}/standards`,
          { method: "GET" },
        ),
      ]);
      setTemplates(templatesData);
      setStandards(
        Array.isArray(standardsRes) ? standardsRes : standardsRes.data || [],
      );
      setError(null);
      addDebug(`✅ Loaded ${templatesData.length} templates`);
    } catch (err: any) {
      setError(err?.message || "Failed to load checklist templates");
      addDebug(`⚠️ templates fetch: ${err?.message}`);
    } finally {
      setLoading(false);
    }
  }, [addDebug]);

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

  // ── Client-side filtering (endpoint returns the full list) ────
  const filtered = useMemo(() => {
    const q = debouncedSearch.trim().toLowerCase();
    return templates.filter((t) => {
      const matchesSearch =
        !q ||
        t.name.toLowerCase().includes(q) ||
        (t.standard?.name ?? "").toLowerCase().includes(q) ||
        t.items.some((i) => i.item_text.toLowerCase().includes(q));
      const matchesType =
        typeFilter === "all" ||
        (typeFilter === "generic" && t.is_generic) ||
        (typeFilter === "specific" && !t.is_generic);
      const matchesStandard =
        standardFilter === "all" ||
        (!t.is_generic && t.standard_id === standardFilter);
      return matchesSearch && matchesType && matchesStandard;
    });
  }, [templates, debouncedSearch, typeFilter, standardFilter]);

  // ── Meta (same shape My Audits gets from its API) ─────────────
  const meta = useMemo(() => {
    const total = filtered.length;
    const totalPages = Math.max(1, Math.ceil(total / itemsPerPage));
    return { total, page: currentPage, limit: itemsPerPage, totalPages };
  }, [filtered.length, currentPage, itemsPerPage]);

  // ── Reset / clamp page when filters shrink the result set ─────
  useEffect(() => {
    setCurrentPage(1);
  }, [debouncedSearch, typeFilter, standardFilter]);

  useEffect(() => {
    if (currentPage > meta.totalPages) setCurrentPage(meta.totalPages);
  }, [currentPage, meta.totalPages]);

  const visibleData = useMemo(
    () =>
      filtered.slice(
        (currentPage - 1) * itemsPerPage,
        currentPage * itemsPerPage,
      ),
    [filtered, currentPage, itemsPerPage],
  );

  const refresh = () => {
    fetchAll();
  };

  const clearAllFilters = () => {
    setSearchTerm("");
    setTypeFilter("all");
    setStandardFilter("all");
  };

  // ── Actions (permission-gated like handleOpen/handleMarkComplete) ─
  const handleNew = () => {
    if (!permittedActions.has("create")) {
      toast.error("You don't have permission to create templates");
      return;
    }
    setEditing(null);
    setView("edit");
  };

  const handleEdit = (row: ChecklistTemplate) => {
    if (!permittedActions.has("edit") && !permittedActions.has("view-all")) {
      toast.error("You don't have permission to edit templates");
      return;
    }
    setEditing(row);
    setView("edit");
  };

  const handleDelete = async (row: ChecklistTemplate) => {
    if (!permittedActions.has("delete")) {
      toast.error("You don't have permission to delete templates");
      return;
    }
    if (!confirm(`Delete "${row.name}"? This can't be undone.`)) return;
    setDeletingId(row.id);
    try {
      await deleteChecklistTemplate(row.id);
      toast.success(`✅ Template "${row.name}" deleted`);
      refresh();
    } catch (err: any) {
      toast.error(err.message || "Failed to delete template");
    } finally {
      setDeletingId(null);
    }
  };

  const handleSaved = () => {
    setView("list");
    setEditing(null);
    fetchAll();
  };

  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 />;

  // ── Editor view ───────────────────────────────────────────────
  if (view === "edit") {
    return (
      <ChecklistTemplateEditor
        editing={editing}
        standards={standards}
        onBack={() => {
          setView("list");
          setEditing(null);
        }}
        onSaved={handleSaved}
      />
    );
  }

  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 */}
      <ChecklistTemplatesHeader
        totalTemplates={meta.total}
        onRefresh={refresh}
        onNewTemplate={handleNew}
      />

      {/* ═══ 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} 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.total > 0,
                    title: `${meta.total} Records`,
                    detail: `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 */}
      <ChecklistTemplatesFilters
        searchTerm={searchTerm}
        setSearchTerm={setSearchTerm}
        typeFilter={typeFilter}
        setTypeFilter={setTypeFilter}
        standardFilter={standardFilter}
        setStandardFilter={setStandardFilter}
        standards={standards}
        clearFilters={clearAllFilters}
        onRefresh={refresh}
      />

      {meta.total > 0 && (
        <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> templates
          </span>
        </div>
      )}

      <div className={styles.tableWrapper}>
        <table className={styles.table} style={{ tableLayout: "fixed", width: "100%" }}>
          <colgroup>
            <col style={{ width: 300 }} />
            <col />
            {hasActionsColumn && <col style={{ width: 150 }} />}
          </colgroup>
          <thead>
            <tr style={{ background: "#f8fafc" }}>
              <th style={thStyle}>Template</th>
              <th style={thStyle}>Checklist Items</th>
              {hasActionsColumn && <th style={thStyle}>Actions</th>}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={hasActionsColumn ? 3 : 2} style={{ textAlign: "center", padding: "60px" }}>
                  <EnterpriseLoader />
                </td>
              </tr>
            ) : visibleData.length === 0 ? (
              <tr>
                <td colSpan={hasActionsColumn ? 3 : 2} style={{ textAlign: "center", padding: "60px" }}>
                  <div style={{ fontSize: 36 }}>📋</div>
                  <h3 style={{ margin: "12px 0 4px", color: "#111827" }}>
                    No templates found
                  </h3>
                  <p style={{ color: "#6b7280", margin: 0 }}>
                    {searchTerm || typeFilter !== "all" || standardFilter !== "all"
                      ? "No templates match your filters."
                      : "No checklist templates yet — create your first one."}
                  </p>
                </td>
              </tr>
            ) : (
              visibleData.map((row) => (
                <ChecklistTemplateRow
                  key={row.id}
                  row={row}
                  onEdit={handleEdit}
                  onDelete={handleDelete}
                  isDeleting={deletingId === row.id}
                  permittedActions={permittedActions}
                />
              ))
            )}
          </tbody>
        </table>
      </div>

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