"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import dynamic from "next/dynamic";
import styles from "../../modules/commonstyle/dattabale.module.css";
import { TemplateFilters } from "./TemplateFilters";
import { Pagination } from "./Pagination";
import { EnterpriseLoader } from "./../../../../components/loader/loader";
import { getTemplates, deleteTemplate, TEMPLATES_API_BASE_URL } from "@/lib/api/template.api";
import { fetchApi } from "@/lib/api/http";
import { deleteWithConfirm } from "./../../../../components/ConfirmDialog/ConfirmDialog";
import TemplateForm from "./Form/TemplateForm";
import TemplateAnalyticsInline from "./Filters/TemplateAnalyticsInline";
import {
  mapTemplatesApiResponse,
  mapColumnKeyToValue,
} from "@/lib/api/mappers/template.mappers";
import type { TemplateRow } from "@/lib/api/types/template.types";

const TemplateRowFallback = dynamic(
  () => import("./TemplateRow").then((m) => m.TemplateRow),
  { ssr: false }
);
const DynamicTemplateRow = dynamic(
  () => import("./DynamicTemplateRow").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 TemplateTableProps { refreshFlag?: boolean; }

// ─── Fallback columns ─────────────────────────────────────────────────────────
const FALLBACK_COLUMNS: ColumnConfig[] = [
  { key: "name",         type: "text",    label: "Name",    order: 1,  sortable: true,  default_visible: true },
  { key: "stageName",    type: "text",    label: "Stage",   order: 2,  sortable: true,  default_visible: true },
  { key: "templateType", type: "custom",  label: "Type",    order: 3,  sortable: false, default_visible: true },
  { key: "version",      type: "text",    label: "Version", order: 4,  sortable: true,  default_visible: true },
  { key: "isActive",     type: "custom",  label: "Status",  order: 5,  sortable: false, default_visible: true },
  { key: "actions",      type: "actions", label: "Actions", order: 99, sortable: false, default_visible: true },
];

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

// ─── Main component ───────────────────────────────────────────────────────────
export default function TemplateTable({ refreshFlag }: TemplateTableProps) {
  const [data, setData]               = useState<TemplateRow[]>([]);
  const [loading, setLoading]         = useState(true);
  const [error, setError]             = useState<string | null>(null);
  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [expandedRows, setExpandedRows] = useState<number[]>([]);
  const [searchTerm, setSearchTerm]     = useState("");
  const [currentPage, setCurrentPage]   = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editingId, setEditingId]             = useState<number | null>(null);
  const [showAnalytics, setShowAnalytics]     = useState(false);
  const [stageFilter, setStageFilter]   = useState("all");
  const [typeFilter, setTypeFilter]     = useState("all");

  // Permission state
  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 [rawModuleResponse, setRawModuleResponse] = useState<any>(null);
  const [rawPermResponse, setRawPermResponse]     = useState<any>(null);
  const [rawUserId, setRawUserId]                 = useState<any>(null);

  const addDebug = useCallback((msg: string) => {
    console.log(`[TEMPLATE-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];
      setRawModuleResponse(response);
      const mod = list.find((m: any) => m.slug === "templates" || m.name === "templates");
      if (mod) { setModuleConfig(mod); addDebug(`✅ templates module found (id:${mod.id})`); return true; }
      addDebug("⚠️ templates module NOT found — FALLBACK"); return false;
    } catch (err: any) { addDebug(`⚠️ module fetch failed: ${err.message}`); return false; }
  }, [addDebug]);

  const fetchUserPermissions = useCallback(async (): Promise<boolean> => {
    try {
      let userId: any = null, source = "";
      if (typeof window !== "undefined") {
        try { const s = localStorage.getItem("user"); if (s) { const p = JSON.parse(s); userId = p?.id || p?.userId || p?.user_id; source = `localStorage("user")`; } } catch {}
        if (!userId) { try { const t = localStorage.getItem("token") || localStorage.getItem("accessToken") || localStorage.getItem("access_token"); if (t) { const p = JSON.parse(atob(t.split(".")[1])); userId = p?.id || p?.userId || p?.user_id || p?.sub; source = "JWT"; } } catch {} }
        if (!userId) { userId = localStorage.getItem("userId") || localStorage.getItem("user_id"); if (userId) source = `localStorage("userId")`; }
      }
      setRawUserId({ userId, source });
      if (!userId) { addDebug("⚠️ No userId — FALLBACK"); setUserPermissions([]); return false; }
      addDebug(`👤 userId=${userId} (${source})`);
      const res = await fetchApi<any>(`${API_BASE_URL}/user-permissions/user/${userId}`);
      setRawPermResponse(res);
      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 fetch failed: ${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", "print", "view_all"]);
    const a = new Set<string>();
    for (const up of userPermissions) {
      if (!up.permission?.action) continue;
      const mid = up.permission.module?.id ?? up.permission.module_id;
      if (mid === moduleConfig.id) a.add(up.permission.action);
    }
    return a;
  }, [moduleConfig, userPermissions]);

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

  const currentUserId = rawUserId?.userId ? Number(rawUserId.userId) : null;
  const canViewAll    = useMemo(() => permittedActions.has("view_all"), [permittedActions]);

  const refreshData = useCallback(() => {
    setLoading(true);
    getTemplates(1, 1000)
      .then((templates) => setData(mapTemplatesApiResponse(templates)))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    const init = async () => {
      setPermissionsLoading(true); setDebugLog([]);
      addDebug("🚀 Templates permission system starting...");
      const [moduleOk, permsOk] = await Promise.all([fetchModuleConfig(), fetchUserPermissions()]);
      const ready = moduleOk && permsOk;
      setPermissionSystemReady(ready); setPermissionsLoading(false);
      addDebug(ready ? "✅ DYNAMIC MODE" : "⚠️ FALLBACK MODE");
    };
    init(); refreshData();
  }, [refreshFlag, fetchModuleConfig, fetchUserPermissions, addDebug, refreshData]);

  useEffect(() => setCurrentPage(1), [searchTerm, stageFilter, typeFilter]);

  const filteredData = useMemo(() => data.filter((row) => {
    const q = searchTerm.toLowerCase();
    if (q && !(
      row.name.toLowerCase().includes(q) ||
      row.filePath.toLowerCase().includes(q) ||
      row.version.toLowerCase().includes(q)
    )) return false;
    if (stageFilter !== "all" && row.stageName !== stageFilter) return false;
    if (typeFilter  !== "all" && row.templateType !== typeFilter) return false;
    return true;
  }), [data, searchTerm, stageFilter, typeFilter]);

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

  const handleDelete = async (row: TemplateRow) => {
    try {
      const { confirmed, error: delErr } = await deleteWithConfirm(
        row.name,
        () => deleteTemplate(row.id),
        { successMessage: "Template deleted.", errorMessage: "Failed to delete." }
      );
      if (confirmed && !delErr) {
        setSelectedRows((p) => p.filter((s) => s !== row.sno));
        setExpandedRows((p) => p.filter((s) => s !== row.sno));
        refreshData();
      }
    } catch (err) { console.error(err); }
  };

  const handleEdit = (row: TemplateRow) => { setEditingId(row.id); setIsEditModalOpen(true); };
  const handleView = (row: TemplateRow) => setExpandedRows((p) => p.includes(row.sno) ? p : [...p, row.sno]);
  const handleAction = useCallback((row: TemplateRow, key: string) => {
    if      (key === "view")   handleView(row);
    else if (key === "edit")   handleEdit(row);
    else if (key === "delete") handleDelete(row);
    else if (key === "print")  window.print();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [expandedRows]);

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

  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={() => window.location.reload()}>Retry</button>
    </div>
  );
  if (loading || 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}>

      {/* ═══ 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 — Templates" : "⚠️ FALLBACK MODE"}</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: userPermissions.length > 0, title: `${userPermissions.length} Perms`,                           detail: Array.from(permittedActions).join(", ") || "none" },
                  { ok: useDynamicMode,             title: useDynamicMode ? "DYNAMIC" : "FALLBACK",                     detail: `${rowButtons.length}r ${toolbarButtons.length}t btns` },
                ].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>
      )}

      {/* Filters */}
      <TemplateFilters
        searchTerm={searchTerm}   setSearchTerm={setSearchTerm}
        stageFilter={stageFilter} setStageFilter={setStageFilter}
        typeFilter={typeFilter}   setTypeFilter={setTypeFilter}
        clearFilters={clearAllFilters}
        onRefresh={refreshData}
        onAnalyticsToggle={() => setShowAnalytics((v) => !v)}
        showAnalytics={showAnalytics}
      />

      {/* 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), setIsEditModalOpen(true))}
              style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "8px 16px", borderRadius: 8, border: `1px solid ${btn.color}33`, backgroundColor: `${btn.color}15`, color: btn.color, cursor: "pointer", fontSize: 13, fontWeight: 600 }}>
              {btn.icon} {btn.label || btn.key}
            </button>
          ))}
        </div>
      )}

      {/* Analytics */}
      {showAnalytics && <TemplateAnalyticsInline templates={data} stageFilter={stageFilter} typeFilter={typeFilter} />}

      {/* Filter summary */}
      {filteredData.length !== data.length && (
        <div style={{ padding: "12px 20px", backgroundColor: "#f0fdfa", border: "1px solid #99f6e4", borderRadius: 10, marginBottom: 16, display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 14, color: "#0f766e" }}>
          <span>📊 Showing <strong>{filteredData.length}</strong> of <strong>{data.length}</strong> templates</span>
          <button onClick={clearAllFilters} style={{ background: "none", border: "none", color: "#0f766e", cursor: "pointer", textDecoration: "underline", fontSize: 14 }}>Clear all 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={filteredData.length > 0 && filteredData.every((r) => selectedRows.includes(r.sno))}
                  onChange={(e) => setSelectedRows(e.target.checked ? filteredData.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}>ID</th>
                  <th className={styles.th}>Name</th>
                  <th className={styles.th}>Stage</th>
                  <th className={styles.th}>Type</th>
                  <th className={styles.th}>Version</th>
                  <th className={styles.th}>Status</th>
                  <th className={styles.actionsCol}>Actions</th>
                </>
              )}
            </tr>
          </thead>
          <tbody>
            {paginatedData.length > 0 ? paginatedData.map((row) =>
              useDynamicMode ? (
                <DynamicTemplateRow
                  key={row.sno} row={row}
                  visibleColumns={headerColumns} rowButtons={rowButtons}
                  hasActionsColumn={hasActionsColumn && rowButtons.length > 0}
                  mapColumnKeyToValue={mapColumnKeyToValue}
                  isExpanded={expandedRows.includes(row.sno)}
                  toggleRowExpand={(id) => setExpandedRows((p) => p.includes(id) ? p.filter((r) => r !== id) : [...p, id])}
                  isSelected={selectedRows.includes(row.sno)}
                  handleRowSelect={(id, checked) => setSelectedRows((p) => checked ? [...p, id] : p.filter((r) => r !== id))}
                  onAction={handleAction}
                />
              ) : (
                <TemplateRowFallback
                  key={row.sno} row={row}
                  isExpanded={expandedRows.includes(row.sno)}
                  toggleRowExpand={(id) => setExpandedRows((p) => p.includes(id) ? p.filter((r) => r !== id) : [...p, id])}
                  isSelected={selectedRows.includes(row.sno)}
                  handleRowSelect={(id, checked) => setSelectedRows((p) => checked ? [...p, id] : p.filter((r) => r !== id))}
                  onEdit={handleEdit} onDelete={handleDelete} onView={handleView}
                />
              )
            ) : (
              <tr><td colSpan={headerColumns.length + 3} style={{ textAlign: "center", padding: "60px" }}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 16 }}>
                  <div style={{ width: 80, height: 80, borderRadius: "50%", backgroundColor: "#f0fdfa", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 36 }}>📄</div>
                  <h3 style={{ fontSize: 18, fontWeight: 600, color: "#111827", margin: 0 }}>No Templates Found</h3>
                  <p style={{ color: "#6b7280", margin: 0 }}>{searchTerm || stageFilter !== "all" || typeFilter !== "all" ? "No templates match your filters." : "Get started by adding a new template."}</p>
                </div>
              </td></tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      <Pagination
        currentPage={currentPage} setCurrentPage={setCurrentPage}
        totalPages={Math.ceil(filteredData.length / itemsPerPage)}
        startIndex={(currentPage - 1) * itemsPerPage + 1}
        endIndex={Math.min(currentPage * itemsPerPage, filteredData.length)}
        sortedDataLength={filteredData.length}
        itemsPerPage={itemsPerPage}
        setItemsPerPage={(v) => { setCurrentPage(1); setItemsPerPage(v); }}
      />

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