'use client';

import React, { useEffect, useState, useMemo, useCallback } from 'react';
import styles from '../../modules/commonstyle/dattabale.module.css';
import { EnterpriseLoader } from '../../../../components/loader/loader';
import { fetchApi } from '@/lib/api/http';
import { deleteWithConfirm } from '../../../../components/ConfirmDialog/ConfirmDialog';
import {
  getEmailSettings,
  deleteEmailSetting,
  sendTestEmail,
} from '@/lib/api/email-settings.api';
import { mapEmailSettingsApiResponse } from '@/lib/api/mappers/email-settings.mappers';
import type { EmailSettingRow as EmailSettingRowType } from '@/lib/api/types/email-settings.types';
import { EmailSettingRow as EmailSettingRowComponent } from './EmailSettingsRow';
import EmailSettingsForm from './Form/EmailSettingsForm';
import toast from 'react-hot-toast';

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

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

// ── Fallback columns ───────────────────────────────────
const FALLBACK_COLUMNS: ColumnConfig[] = [
  { key: 'from_email',      type: 'text', label: 'From',       order: 1, sortable: true,  default_visible: true },
  { key: 'smtp_host',       type: 'text', label: 'SMTP Host',  order: 2, sortable: true,  default_visible: true },
  { key: 'smtp_username',   type: 'text', label: 'Username',   order: 3, sortable: true,  default_visible: true },
  { key: 'smtp_encryption', type: 'text', label: 'Encryption', order: 4, sortable: true,  default_visible: true },
  { key: 'user_id',         type: 'text', label: 'User',       order: 5, sortable: true,  default_visible: true },
  { key: 'updated_at',      type: 'text', label: 'Updated',    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;
}

// ── Send-test prompt modal ────────────────────────────────────────────────────
function SendTestModal({
  open, onClose, onSubmit, fromEmail,
}: { open: boolean; onClose: () => void; onSubmit: (to: string) => void; fromEmail?: string }) {
  const [to, setTo] = 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: 460, padding: 24, boxShadow: '0 20px 60px rgba(0,0,0,0.2)' }}>
        <h3 style={{ margin: '0 0 6px', fontSize: 16, fontWeight: 700, color: '#111827' }}>✉️ Send Test Email</h3>
        <p style={{ margin: '0 0 16px', fontSize: 13, color: '#6b7280' }}>
          Sends a test message{fromEmail ? <> from <strong>{fromEmail}</strong></> : ''} to verify the SMTP credentials work.
        </p>
        <input
          type="email"
          value={to}
          onChange={e => setTo(e.target.value)}
          placeholder="recipient@example.com"
          style={{ width: '100%', borderRadius: 8, border: '1.5px solid #e5e7eb', padding: '10px 12px', fontSize: 13, marginBottom: 16, boxSizing: 'border-box' }}
        />
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
          <button onClick={() => { onClose(); setTo(''); }}
            style={{ padding: '9px 18px', borderRadius: 8, border: '1px solid #e5e7eb', backgroundColor: '#fff', color: '#6b7280', cursor: 'pointer', fontSize: 14 }}>
            Cancel
          </button>
          <button onClick={() => {
            if (!to.trim()) { toast.error('Enter a recipient email'); return; }
            onSubmit(to.trim()); onClose(); setTo('');
          }}
            style={{ padding: '9px 20px', borderRadius: 8, border: 'none', backgroundColor: '#0F6E56', color: '#fff', cursor: 'pointer', fontSize: 14, fontWeight: 600 }}>
            Send Test
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── EmailSettingsTable ───────────────────────────────────────────────────────
export default function EmailSettingsTable({ refreshFlag }: TableProps) {

  const [data,    setData]    = useState<EmailSettingRowType[]>([]);
  const [loading, setLoading] = useState(true);
  const [error,   setError]   = useState<string | null>(null);

  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [searchTerm,   setSearchTerm]   = useState('');
  const debouncedSearch = useDebounce(searchTerm, 400);

  // ── Modals ────────────────────────────────────────────────────────────────
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingId,  setEditingId]  = useState<number | null>(null);
  const [testRow,    setTestRow]    = useState<EmailSettingRowType | null>(null);
  const [testingId,  setTestingId]  = useState<number | null>(null);

  // ── Permission / module config ──────────────────────────────────────────────
  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(`[EMAIL-SETTINGS-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 === 'email-settings' || m.name === 'email-settings');
      if (mod) { setModuleConfig(mod); addDebug(`✅ email-settings 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']);
    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 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]);

  // ── Data fetch ──────────────────────────────────────────────────────────────
  const fetchData = useCallback(() => {
    setLoading(true);
    setSelectedRows([]);
    getEmailSettings()
      .then(rows => {
        setData(mapEmailSettingsApiResponse(rows));
        addDebug(`✅ Loaded ${rows.length} SMTP configs`);
      })
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, [addDebug]);

  useEffect(() => {
    const init = async () => {
      setPermissionsLoading(true); setDebugLog([]);
      addDebug('🚀 Email Settings starting...');
      const [moduleOk, permsOk] = await Promise.all([fetchModuleConfig(), fetchUserPermissions()]);
      setPermissionSystemReady(moduleOk && permsOk);
      setPermissionsLoading(false);
    };
    init();
    fetchData();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [refreshFlag]);

  const refresh = () => fetchData();

  // ── Filtered rows (client-side search) ────────────────────────────────────────
  const filtered = useMemo(() => {
    const q = debouncedSearch.trim().toLowerCase();
    if (!q) return data;
    return data.filter(r =>
      (r.from_email || '').toLowerCase().includes(q) ||
      (r.smtp_host || '').toLowerCase().includes(q) ||
      (r.smtp_username || '').toLowerCase().includes(q) ||
      (r.from_name || '').toLowerCase().includes(q),
    );
  }, [data, debouncedSearch]);

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

  const handleDelete = async (row: EmailSettingRowType) => {
    const { confirmed, error: e } = await deleteWithConfirm(
      row.from_email,
      () => deleteEmailSetting(row.id),
      { successMessage: 'SMTP config deleted.', errorMessage: 'Failed to delete.' },
    );
    if (confirmed && !e) refresh();
  };

  const handleTest = (row: EmailSettingRowType) => setTestRow(row);

  const submitTest = async (to: string) => {
    if (!testRow) return;
    setTestingId(testRow.id);
    try {
      await sendTestEmail(testRow.id, { to });
      toast.success(`Test email sent to ${to}`);
    } catch (err: any) {
      toast.error(err.message || 'Failed to send test email');
    } finally {
      setTestingId(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 headerColumns    = visibleColumns.filter(c => c.key !== 'actions');

  return (
    <div className={styles.container}>

      {/* ═══ SEND TEST MODAL ══════════════════════════════════════════════ */}
      <SendTestModal
        open={!!testRow}
        onClose={() => setTestRow(null)}
        onSubmit={submitTest}
        fromEmail={testRow?.from_email}
      />

      {/* ═══ 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'} — {data.length} configs</span>
            <span>{showDebug ? '▼' : '▶'}</span>
          </div>
          {showDebug && (
            <div style={{ padding: '16px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,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: data.length > 0, title: `${data.length} Configs`, detail: '' },
                ].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>
      )}

      {/* ═══ Search ══════════════════════════════════════════════════════ */}
      <div style={{ marginBottom: 12 }}>
        <input
          value={searchTerm}
          onChange={e => setSearchTerm(e.target.value)}
          placeholder="Search by email, host, or username…"
          style={{ width: '100%', maxWidth: 360, padding: '9px 12px', fontSize: 13, border: '1px solid #e5e7eb', borderRadius: 8, boxSizing: 'border-box' }}
        />
      </div>

      {/* ═══ Record count ════════════════════════════════════════════════ */}
      <div style={{ padding: '10px 16px', backgroundColor: '#f0fdfa', border: '1px solid #99f6e4', borderRadius: 8, marginBottom: 12, fontSize: 13, color: '#0f766e' }}>
        📋 Showing <strong>{filtered.length}</strong> of <strong>{data.length}</strong> SMTP config{data.length !== 1 ? 's' : ''}
        {debouncedSearch && <span style={{ marginLeft: 8, color: '#9ca3af' }}>(filtered)</span>}
      </div>

      {/* ═══ TABLE ═══════════════════════════════════════════════════════ */}
      <div className={styles.tableWrapper}>
        <table className={styles.table}>
          <thead>
            <tr>
              <th className={styles.checkboxCol}>
                <input type="checkbox" className={styles.checkbox}
                  checked={filtered.length > 0 && filtered.every(r => selectedRows.includes(r.sno))}
                  onChange={e => setSelectedRows(e.target.checked ? filtered.map(r => r.sno) : [])} />
              </th>
              {useDynamicMode ? (
                <>
                  {headerColumns.map(col => <th key={col.key} className={styles.th}>{col.label}</th>)}
                  {hasActionsColumn && <th className={styles.actionsCol}>Actions</th>}
                </>
              ) : (
                <>
                  <th className={styles.th}>From</th>
                  <th className={styles.th}>SMTP Host</th>
                  <th className={styles.th}>Username</th>
                  <th className={styles.th}>Encryption</th>
                  <th className={styles.th}>User</th>
                  <th className={styles.th}>Updated</th>
                  <th className={styles.actionsCol}>Actions</th>
                </>
              )}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={headerColumns.length + 2} 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>
            ) : filtered.length > 0 ? filtered.map(row => (
              <EmailSettingRowComponent
                key={row.sno}
                row={row}
                isSelected={selectedRows.includes(row.sno)}
                handleRowSelect={(sno, checked) => setSelectedRows(p => checked ? [...p, sno] : p.filter(r => r !== sno))}
                onEdit={handleEdit}
                onDelete={handleDelete}
                onTest={handleTest}
                testing={testingId === row.id}
              />
            )) : (
              <tr>
                <td colSpan={headerColumns.length + 2} 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 SMTP Configs Found</h3>
                    <p style={{ color: '#6b7280', margin: 0 }}>
                      {debouncedSearch ? 'No configs match your search.' : 'Get started by adding a new SMTP config.'}
                    </p>
                  </div>
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

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

    </div>
  );
}
