import { useState, useEffect, useCallback } from 'react';
import {
  FileText,
  ScrollText,
  MessageSquare,
  RefreshCw,
  AlertCircle,
  Loader2,
} from 'lucide-react';
import {
  adminApi,
  type AuditEntry,
  type ConfigLogEntry,
  type ChatLogEntry,
} from '@/api/endpoints/admin';
import { usePolling } from '@/hooks/usePolling';
import { useI18n } from '@/i18n';

/* ── Helpers ── */

function formatDate(iso: string) {
  if (!iso) return '—';
  try {
    const d = new Date(iso.includes('T') ? iso : iso.replace(' ', 'T') + 'Z');
    return d.toLocaleString('pt-BR', {
      day: '2-digit', month: '2-digit', year: '2-digit',
      hour: '2-digit', minute: '2-digit', second: '2-digit',
    });
  } catch {
    return iso;
  }
}

function SeverityBadge({ severity }: { severity: string }) {
  const map: Record<string, { bg: string; fg: string }> = {
    error:   { bg: 'var(--rdl)', fg: 'var(--rd)' },
    success: { bg: 'var(--gnl)', fg: 'var(--gn)' },
    info:    { bg: 'var(--bll)', fg: 'var(--bl)' },
    warning: { bg: 'var(--yll)', fg: 'var(--yl)' },
  };
  const s = map[severity] ?? { bg: 'var(--bg3)', fg: 'var(--t3)' };
  return (
    <span
      className="inline-block px-2 py-0.5 rounded-full text-[0.68rem] font-semibold"
      style={{ background: s.bg, color: s.fg }}
    >
      {severity}
    </span>
  );
}

function ActionTag({ action }: { action: string }) {
  return (
    <span
      className="inline-block px-2 py-0.5 rounded-md text-[0.7rem] font-medium"
      style={{ background: 'var(--acl)', color: 'var(--ac)', border: '1px solid var(--acl2)' }}
    >
      {action}
    </span>
  );
}

function EmptyState({ text }: { text: string }) {
  return (
    <div
      className="flex flex-col items-center justify-center py-12"
      style={{ color: 'var(--t4)' }}
    >
      <FileText size={32} className="mb-3 opacity-40" />
      <p className="text-sm">{text}</p>
    </div>
  );
}

function ErrorBanner({ message }: { message: string }) {
  return (
    <div
      className="flex items-center gap-2 px-4 py-3 rounded-xl text-sm"
      style={{ background: 'var(--rdl)', color: 'var(--rd)', border: '1px solid var(--rd)' }}
    >
      <AlertCircle size={16} />
      {message}
    </div>
  );
}

function LoadingRow({ cols, text }: { cols: number; text: string }) {
  return (
    <tr>
      <td colSpan={cols} className="text-center py-10">
        <Loader2 size={22} className="inline animate-spin" style={{ color: 'var(--ac)' }} />
        <span className="ml-2 text-sm" style={{ color: 'var(--t4)' }}>{text}</span>
      </td>
    </tr>
  );
}

/* ── Shared table wrapper ── */

const tableContainerStyle: React.CSSProperties = {
  background: 'var(--bg1)',
  border: '1px solid var(--bd)',
  borderRadius: 'var(--r)',
  overflow: 'hidden',
};

const thStyle: React.CSSProperties = {
  padding: '0.6rem 0.75rem',
  fontSize: '0.7rem',
  fontWeight: 600,
  textTransform: 'uppercase',
  letterSpacing: '0.04em',
  color: 'var(--t3)',
  background: 'var(--bg2)',
  borderBottom: '1px solid var(--bd)',
  whiteSpace: 'nowrap',
};

const tdStyle: React.CSSProperties = {
  padding: '0.55rem 0.75rem',
  fontSize: '0.76rem',
  borderBottom: '1px solid var(--bg3)',
  color: 'var(--t2)',
};

const tdDateStyle: React.CSSProperties = {
  ...tdStyle,
  fontSize: '0.68rem',
  color: 'var(--t4)',
  whiteSpace: 'nowrap',
  fontFamily: 'var(--fm)',
};

const tdMonoStyle: React.CSSProperties = {
  ...tdStyle,
  fontSize: '0.68rem',
  color: 'var(--t4)',
  fontFamily: 'var(--fm)',
};

/* ── Toolbar ── */

interface ToolbarProps {
  limit: number;
  onLimitChange: (n: number) => void;
  severity?: string;
  onSeverityChange?: (s: string) => void;
  onRefresh: () => void;
  loading: boolean;
  showSeverity?: boolean;
}

function Toolbar({
  limit,
  onLimitChange,
  severity,
  onSeverityChange,
  onRefresh,
  loading,
  showSeverity = false,
}: ToolbarProps) {
  const { t } = useI18n();
  const selectStyle: React.CSSProperties = {
    fontSize: '0.72rem',
    padding: '0.3rem 0.5rem',
    borderRadius: '8px',
    border: '1px solid var(--bd)',
    background: 'var(--bg2)',
    color: 'var(--t2)',
    outline: 'none',
  };

  return (
    <div className="flex items-center gap-3 flex-wrap">
      {showSeverity && onSeverityChange && (
        <select
          value={severity ?? ''}
          onChange={(e) => onSeverityChange(e.target.value)}
          style={selectStyle}
        >
          <option value="">{t('audit.all')}</option>
          <option value="error">{t('audit.errors')}</option>
          <option value="success">{t('audit.success')}</option>
          <option value="info">{t('audit.info')}</option>
        </select>
      )}
      <select
        value={limit}
        onChange={(e) => onLimitChange(Number(e.target.value))}
        style={selectStyle}
      >
        <option value={50}>50 {t('audit.records')}</option>
        <option value={100}>100 {t('audit.records')}</option>
        <option value={200}>200 {t('audit.records')}</option>
        <option value={500}>500 {t('audit.records')}</option>
      </select>
      <button
        onClick={onRefresh}
        disabled={loading}
        className="btn btn-secondary btn-sm"
      >
        <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />
        {t('audit.refresh')}
      </button>
    </div>
  );
}

/* ── Tab definitions ── */

type TabId = 'audit' | 'config' | 'chat';

/* ── Audit Log Table ── */

function AuditLogTable() {
  const { t } = useI18n();
  const [data, setData] = useState<AuditEntry[]>([]);
  const [limit, setLimit] = useState(100);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const rows = await adminApi.getAuditLog(limit);
      setData(rows);
    } catch (e: any) {
      setError(e.message || 'Erro ao carregar audit log');
    } finally {
      setLoading(false);
    }
  }, [limit]);

  useEffect(() => { load(); }, [load]);

  usePolling(async () => { await load(); }, 30_000, true);

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-xs" style={{ color: 'var(--t4)' }}>
          {data.length > 0 && `${data.length} ${t('audit.records')}`}
        </p>
        <Toolbar limit={limit} onLimitChange={setLimit} onRefresh={load} loading={loading} />
      </div>
      {error && <ErrorBanner message={error} />}
      <div className="overflow-x-auto" style={{ borderRadius: 'var(--r)', border: '1px solid var(--bd)' }}>
        <table className="data-table">
          <thead>
            <tr>
              <th>{t('audit.date')}</th>
              <th>{t('audit.user')}</th>
              <th>{t('audit.action')}</th>
              <th>{t('audit.resource')}</th>
              <th>{t('audit.details')}</th>
              <th>{t('audit.ip')}</th>
            </tr>
          </thead>
          <tbody>
            {loading && data.length === 0 ? (
              <LoadingRow cols={6} text={t('audit.loadingLogs')} />
            ) : data.length === 0 ? (
              <tr>
                <td colSpan={6}><EmptyState text={t('audit.noAudit')} /></td>
              </tr>
            ) : (
              data.map((row) => (
                <tr key={row.id}>
                  <td style={{ whiteSpace: 'nowrap', fontFamily: 'var(--fm)', fontSize: '.72rem', color: 'var(--t4)' }}>{formatDate(row.created_at)}</td>
                  <td>{row.username || '—'}</td>
                  <td><ActionTag action={row.action} /></td>
                  <td style={{ fontFamily: 'var(--fm)', fontSize: '.72rem', color: 'var(--t4)' }} title={row.resource ?? ''}>
                    {row.resource ? (row.resource.length > 20 ? row.resource.slice(0, 20) + '...' : row.resource) : '—'}
                  </td>
                  <td
                    style={{ fontSize: '0.72rem', maxWidth: '300px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                    title={row.details ?? ''}
                  >
                    {row.details?.slice(0, 120) || '—'}
                  </td>
                  <td style={{ fontSize: '0.72rem' }}>{row.ip || '—'}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ── Config Logs Table ── */

function ConfigLogsTable() {
  const { t } = useI18n();
  const [data, setData] = useState<ConfigLogEntry[]>([]);
  const [limit, setLimit] = useState(50);
  const [severity, setSeverity] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const rows = await adminApi.getConfigLogs({
        severity: severity || undefined,
        limit,
      });
      setData(rows);
    } catch (e: any) {
      setError(e.message || 'Erro ao carregar config logs');
    } finally {
      setLoading(false);
    }
  }, [limit, severity]);

  useEffect(() => { load(); }, [load]);

  usePolling(async () => { await load(); }, 30_000, true);

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-xs" style={{ color: 'var(--t4)' }}>
          {data.length > 0 && `${data.length} ${t('audit.records')}`}
        </p>
        <Toolbar
          limit={limit}
          onLimitChange={setLimit}
          severity={severity}
          onSeverityChange={setSeverity}
          onRefresh={load}
          loading={loading}
          showSeverity
        />
      </div>
      {error && <ErrorBanner message={error} />}
      <div className="overflow-x-auto" style={{ borderRadius: 'var(--r)', border: '1px solid var(--bd)' }}>
        <table className="data-table">
          <thead>
            <tr>
              <th>{t('audit.date')}</th>
              <th>{t('audit.config')}</th>
              <th>{t('audit.action')}</th>
              <th>{t('audit.status')}</th>
              <th>{t('audit.message')}</th>
            </tr>
          </thead>
          <tbody>
            {loading && data.length === 0 ? (
              <LoadingRow cols={5} text={t('audit.loadingLogs')} />
            ) : data.length === 0 ? (
              <tr>
                <td colSpan={5}><EmptyState text={t('audit.noConfig')} /></td>
              </tr>
            ) : (
              data.map((row) => (
                <tr key={row.id}>
                  <td style={{ whiteSpace: 'nowrap', fontFamily: 'var(--fm)', fontSize: '.72rem', color: 'var(--t4)' }}>{formatDate(row.created_at)}</td>
                  <td style={{ fontSize: '0.72rem' }}>
                    {row.config_name || row.config_id?.slice(0, 8) || '—'}
                  </td>
                  <td><ActionTag action={row.action} /></td>
                  <td><SeverityBadge severity={row.severity} /></td>
                  <td
                    style={{ fontSize: '0.72rem', maxWidth: '400px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                    title={row.message || ''}
                  >
                    {row.message?.slice(0, 150) || '—'}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ── Chat Logs Table ── */

function ChatLogsTable() {
  const { t } = useI18n();
  const [data, setData] = useState<ChatLogEntry[]>([]);
  const [limit, setLimit] = useState(50);
  const [severity, setSeverity] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const rows = await adminApi.getChatLogs({
        severity: severity || undefined,
        limit,
      });
      setData(rows);
    } catch (e: any) {
      setError(e.message || 'Erro ao carregar chat logs');
    } finally {
      setLoading(false);
    }
  }, [limit, severity]);

  useEffect(() => { load(); }, [load]);

  usePolling(async () => { await load(); }, 30_000, true);

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-xs" style={{ color: 'var(--t4)' }}>
          {data.length > 0 && `${data.length} ${t('audit.records')}`}
        </p>
        <Toolbar
          limit={limit}
          onLimitChange={setLimit}
          severity={severity}
          onSeverityChange={setSeverity}
          onRefresh={load}
          loading={loading}
          showSeverity
        />
      </div>
      {error && <ErrorBanner message={error} />}
      <div className="overflow-x-auto" style={{ borderRadius: 'var(--r)', border: '1px solid var(--bd)' }}>
        <table className="data-table">
          <thead>
            <tr>
              <th>{t('audit.date')}</th>
              <th>{t('audit.session')}</th>
              <th>{t('audit.source')}</th>
              <th>{t('audit.action')}</th>
              <th>{t('audit.status')}</th>
              <th>{t('audit.message')}</th>
            </tr>
          </thead>
          <tbody>
            {loading && data.length === 0 ? (
              <LoadingRow cols={6} text={t('audit.loadingLogs')} />
            ) : data.length === 0 ? (
              <tr>
                <td colSpan={6}><EmptyState text={t('audit.noChat')} /></td>
              </tr>
            ) : (
              data.map((row) => (
                <tr key={row.id}>
                  <td style={{ whiteSpace: 'nowrap', fontFamily: 'var(--fm)', fontSize: '.72rem', color: 'var(--t4)' }}>{formatDate(row.created_at)}</td>
                  <td style={{ fontFamily: 'var(--fm)', fontSize: '.72rem', color: 'var(--t4)' }} title={row.session_id ?? ''}>
                    {row.session_id ? row.session_id.slice(0, 8) + '...' : '—'}
                  </td>
                  <td style={{ fontSize: '0.72rem' }}>{row.source || '—'}</td>
                  <td><ActionTag action={row.action} /></td>
                  <td><SeverityBadge severity={row.severity} /></td>
                  <td
                    style={{ fontSize: '0.72rem', maxWidth: '400px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                    title={row.message || ''}
                  >
                    {row.message?.slice(0, 150) || '—'}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ── Main Page ── */

export default function AuditPage() {
  const { t } = useI18n();
  const [activeTab, setActiveTab] = useState<TabId>('audit');

  const tabs: { id: TabId; label: string; icon: React.ReactNode }[] = [
    { id: 'audit', label: t('audit.tabAudit'), icon: <FileText size={15} /> },
    { id: 'config', label: t('audit.tabConfig'), icon: <ScrollText size={15} /> },
    { id: 'chat', label: t('audit.tabChat'), icon: <MessageSquare size={15} /> },
  ];

  return (
    <div className="page" style={{ overflow: 'auto', height: '100%' }}>
      {/* Header */}
      <div className="page-header">
        <div className="card-header icon" style={{ background: 'var(--acl)' }}>
          <FileText size={20} style={{ color: 'var(--ac)' }} />
        </div>
        <div>
          <h1>{t('audit.title')}</h1>
          <div className="subtitle">
            {t('audit.subtitle')}
          </div>
        </div>
      </div>

      {/* Card with tabs + content */}
      <div className="card">
        {/* Tab bar */}
        <div
          className="flex gap-1 p-1 rounded-xl mb-4"
          style={{ background: 'var(--bg2)', border: '1px solid var(--bd)' }}
        >
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className="btn btn-sm"
              style={{
                background: activeTab === tab.id ? 'var(--bg1)' : 'transparent',
                color: activeTab === tab.id ? 'var(--t1)' : 'var(--t3)',
                border: activeTab === tab.id ? '1px solid var(--bd)' : '1px solid transparent',
                boxShadow: activeTab === tab.id ? 'var(--sh1)' : 'none',
              }}
            >
              {tab.icon}
              {tab.label}
            </button>
          ))}
        </div>

        {/* Tab content */}
        <div style={{ animation: 'fadeIn .3s ease-out' }}>
          {activeTab === 'audit' && <AuditLogTable />}
          {activeTab === 'config' && <ConfigLogsTable />}
          {activeTab === 'chat' && <ChatLogsTable />}
        </div>
      </div>
    </div>
  );
}
