'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 } from '@/lib/api/http';

import DocumentsHeader from './DocumentsHeader';
import DocumentsFilters from './DocumentsFilters';
import DocumentRowComponent from './DocumentRow';
import UploadDocumentModal from './UploadDocumentModal';
import UnlockModal from './UnlockModal';
import AuditLogModal from './AuditLogModal';

import {
  getDocuments,
  getDocumentsAnalytics,
  deleteDocument,
} from '@/lib/api/documents.api';
import type {
  DocumentRow,
  DocumentStatus,
  DocumentsAnalytics,
} from '@/lib/api/types/documents.types';

// ── Permission system 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[];
}

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3008/api';

// ── Fallback columns ──────────────────────────────────────────────────────
const FALLBACK_COLUMNS: ColumnConfig[] = [
  { key: 'title', type: 'text', label: 'Document', order: 1, sortable: true, default_visible: true },
  { key: 'roles', type: 'custom', label: 'Assigned to', order: 2, sortable: false, default_visible: true },
  { key: 'security', type: 'text', label: 'Security', order: 3, sortable: false, default_visible: true },
  { key: 'opens', type: 'text', label: 'Opens', order: 4, sortable: false, default_visible: true },
  { key: 'status', type: 'text', label: 'Status', order: 5, sortable: true, default_visible: true },
  { key: 'created_at', type: 'date', label: 'Uploaded', order: 6, 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 DocumentsPage() {
  // ── Data state ────────────────────────────────────────────────────
  const [data, setData] = useState<DocumentRow[]>([]);
  const [meta, setMeta] = useState<{
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  } | null>(null);
  const [analytics, setAnalytics] = useState<DocumentsAnalytics | null>(null);
  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 [categoryFilter, setCategoryFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState<DocumentStatus | 'all'>('all');
  const debouncedSearch = useDebounce(searchTerm, 400);

  // ── Modal state ───────────────────────────────────────────────────
  const [uploadOpen, setUploadOpen] = useState(false);
  const [unlockTarget, setUnlockTarget] = useState<DocumentRow | null>(null);
  const [unlockMode, setUnlockMode] = useState<'view' | 'download'>('view');
  const [logTarget, setLogTarget] = useState<DocumentRow | null>(null);

  // Roles list — loaded once for the upload modal
  const [roles, setRoles] = useState<{ id: number; name: string }[]>([]);

  // ── Permission system state ──────────────────────────────────────────
  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(`[DOCUMENTS-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 === 'documents' || m.name === 'Documents',
      );
      if (mod) {
        setModuleConfig(mod);
        addDebug(`✅ documents module (id:${mod.id})`);
        return true;
      }
      addDebug('⚠️ documents 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]);

  // ── Fetch roles once ──────────────────────────────────────────────────
  const fetchRoles = useCallback(async () => {
    try {
      const res = await fetchApi<any>(`${API_BASE_URL}/roles`);
      const list = Array.isArray(res) ? res : res?.data || [];
      setRoles(
        list.map((r: any) => ({ id: r.id, name: r.name })),
      );
    } catch (err: any) {
      addDebug(`⚠️ roles fetch: ${err.message}`);
    }
  }, [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 ─────────────────────────────────────────
  const permittedActions = useMemo((): Set<string> => {
    if (!moduleConfig) return new Set(['view', 'request_otp', 'unlock']);

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

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

  // Admin-view = user can see the extra "Opens" column and the status filter
  const isAdminView =
    permittedActions.has('view_log') || permittedActions.has('view_all');

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

  // ── Row buttons ────────────────────────────────────────────────────────
  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],
  );

  // ── Fetch one page of documents ──────────────────────────────────────
  const fetchPage = useCallback(
    (
      page: number,
      limit: number,
      search: string,
      category: string,
      status: string,
    ) => {
      setLoading(true);
      getDocuments({
        page,
        limit,
        ...(search && { search }),
        ...(category !== 'all' && { category }),
        ...(status !== 'all' && { status: status as DocumentStatus }),
      })
        .then((res) => {
          setData(res.data);
          setMeta(res.meta);
          addDebug(`✅ Page ${page}: ${res.data.length} of ${res.meta.total}`);
        })
        .catch((err) => setError(err.message))
        .finally(() => setLoading(false));
    },
    [addDebug],
  );

  // ── Fetch analytics ────────────────────────────────────────────────────
  const fetchAnalytics = useCallback(() => {
    if (!isAdminView) return;
    getDocumentsAnalytics()
      .then((a) => setAnalytics(a))
      .catch(() => addDebug('⚠️ Analytics fetch failed'));
  }, [isAdminView, addDebug]);

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

  // Refresh analytics once we know whether the user is admin
  useEffect(() => {
    if (permissionSystemReady) fetchAnalytics();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [permissionSystemReady, isAdminView]);

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

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

  const refresh = () => {
    fetchPage(currentPage, itemsPerPage, debouncedSearch, categoryFilter, statusFilter);
    fetchAnalytics();
  };

  const clearAllFilters = () => {
    setSearchTerm('');
    setCategoryFilter('all');
    setStatusFilter('all');
  };

  // ── Row handlers ──────────────────────────────────────────────────────
  const handleOpen = (row: DocumentRow) => {
    if (!permittedActions.has('view')) {
      toast.error("You don't have permission to view this document");
      return;
    }
    setUnlockMode('view');
    setUnlockTarget(row);
  };

  const handleDownload = (row: DocumentRow) => {
    if (!permittedActions.has('download')) {
      toast.error("You don't have permission to download");
      return;
    }
    setUnlockMode('download');
    setUnlockTarget(row);
  };

  const handleEdit = (_row: DocumentRow) => {
    toast('Edit dialog: wire this to your generic edit modal or extend UploadDocumentModal.', {
      icon: '✏️',
    });
  };

  const handleDelete = async (row: DocumentRow) => {
    if (!permittedActions.has('delete')) {
      toast.error("You don't have permission to archive");
      return;
    }
    if (!window.confirm(`Archive "${row.title}"? The audit log will be preserved.`)) {
      return;
    }
    try {
      await deleteDocument(row.id);
      toast.success(`Archived "${row.title}"`);
      refresh();
    } catch (err: any) {
      toast.error(err.message || 'Failed to archive');
    }
  };

  const handleViewLog = (row: DocumentRow) => {
    if (!permittedActions.has('view_log')) {
      toast.error("You don't have permission to view the access log");
      return;
    }
    setLogTarget(row);
  };

  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 */}
      <DocumentsHeader
        totalDocs={meta?.total}
        onRefresh={refresh}
        onUpload={() => setUploadOpen(true)}
      />

      {/* ═══ 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>
              🎯 Documents · {useDynamicMode ? 'DYNAMIC' : '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: 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>
      )}

      {/* KPI tiles (admin only) */}
      {isAdminView && analytics && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          gap: 12,
          marginBottom: 14,
        }}>
          {[
            { label: 'Total documents', value: analytics.total_docs, color: '#4a0080' },
            { label: 'Active', value: analytics.active_docs, color: '#166534' },
            { label: 'Total opens', value: analytics.total_opens, color: '#1e40af' },
            { label: 'Failed attempts', value: analytics.failed_attempts, color: '#dc2626' },
          ].map((k) => (
            <div key={k.label} style={{
              background: '#fff',
              border: '1px solid #eae5f1',
              borderRadius: 12,
              padding: '14px 16px',
            }}>
              <div style={{ fontSize: 24, fontWeight: 800, color: k.color }}>
                {k.value.toLocaleString()}
              </div>
              <div style={{ fontSize: 11, color: '#8b8397', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', marginTop: 2 }}>
                {k.label}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Dynamic toolbar buttons */}
      {useDynamicMode && toolbarButtons.length > 0 && (
        <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
          {toolbarButtons.map((btn) => (
            <button
              key={btn.key}
              onClick={() => {
                if (btn.key === 'create') setUploadOpen(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 */}
      <DocumentsFilters
        searchTerm={searchTerm}
        setSearchTerm={setSearchTerm}
        categoryFilter={categoryFilter}
        setCategoryFilter={setCategoryFilter}
        statusFilter={statusFilter}
        setStatusFilter={setStatusFilter}
        clearFilters={clearAllFilters}
        onRefresh={refresh}
        showStatusFilter={isAdminView}
      />

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

      <div className={styles.tableWrapper}>
        <table className={styles.table} style={{ tableLayout: 'fixed', width: '100%' }}>
          <colgroup>
            <col style={{ width: 320 }} />
            <col style={{ width: 180 }} />
            <col style={{ width: 160 }} />
            {isAdminView && <col style={{ width: 100 }} />}
            <col style={{ width: 130 }} />
            <col style={{ width: 110 }} />
            <col style={{ width: 200 }} />
          </colgroup>
          <thead>
            <tr style={{ background: '#f8fafc' }}>
              <th style={thStyle}>Document</th>
              <th style={thStyle}>Assigned to</th>
              <th style={thStyle}>Security</th>
              {isAdminView && <th style={thStyle}>Opens</th>}
              <th style={thStyle}>Status</th>
              <th style={thStyle}>Uploaded</th>
              {hasActionsColumn && <th style={thStyle}>Actions</th>}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={isAdminView ? 7 : 6} style={{ textAlign: 'center', padding: '60px' }}>
                  <EnterpriseLoader />
                </td>
              </tr>
            ) : data.length === 0 ? (
              <tr>
                <td colSpan={isAdminView ? 7 : 6} style={{ textAlign: 'center', padding: '60px' }}>
                  <div style={{ fontSize: 36 }}>📄</div>
                  <h3 style={{ margin: '12px 0 4px', color: '#111827' }}>
                    No documents found
                  </h3>
                  <p style={{ color: '#6b7280', margin: 0 }}>
                    {searchTerm || categoryFilter !== 'all' || statusFilter !== 'all'
                      ? 'No documents match your filters.'
                      : isAdminView
                        ? 'Upload your first document to get started.'
                        : 'No documents have been shared with you yet.'}
                  </p>
                </td>
              </tr>
            ) : (
              data.map((row) => (
                <DocumentRowComponent
                  key={row.id}
                  row={row}
                  onOpen={handleOpen}
                  onEdit={handleEdit}
                  onDelete={handleDelete}
                  onViewLog={handleViewLog}
                  permittedActions={permittedActions}
                  isAdminView={isAdminView}
                />
              ))
            )}
          </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);
          }}
        />
      )}

      {/* ─── Modals ─── */}
      {uploadOpen && (
        <UploadDocumentModal
          isOpen={uploadOpen}
          onClose={() => setUploadOpen(false)}
          onUploaded={refresh}
          roles={roles}
        />
      )}

      <UnlockModal
        isOpen={!!unlockTarget}
        document={unlockTarget}
        initialMode={unlockMode}
        canDownload={permittedActions.has('download')}
        onClose={() => setUnlockTarget(null)}
      />

      <AuditLogModal
        isOpen={!!logTarget}
        document={logTarget}
        canExport={permittedActions.has('export_log')}
        onClose={() => setLogTarget(null)}
      />
    </div>
  );
}