'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Search, Eye, Shield, AlertTriangle, User, Loader2, AlertCircle } from 'lucide-react';
import { getAdminSupport, getAdminRestaurants } from '@client/api/admin';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { toast } from 'sonner';

interface Restaurant {
  id: string; name: string; owner: string; plan: string; status: string;
}

interface AuditLogEntry {
  id: string; actor: string; actorType: string; action: string;
  resource: string; timestamp: string; ip: string; severity: string;
}

type Tab = 'impersonate' | 'audit';

const severityConfig: Record<string, string> = {
  info: 'badge-info',
  warning: 'badge-warning',
  critical: 'badge-danger',
};

const actorTypeIcon = (type: string) => {
  if (type === 'admin') return <Shield size={12} style={{ color: 'hsl(var(--primary))' }} />;
  if (type === 'system') return <AlertTriangle size={12} style={{ color: 'hsl(var(--warning))' }} />;
  return <User size={12} style={{ color: 'hsl(var(--info))' }} />;
};

function formatTimestamp(ts: string) {
  const d = new Date(ts);
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) +
    ' ' + d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
}

export default function SupportToolsPage() {
  const { t } = useLanguage();
  usePageHeader(t('admin.support.pageTitle', 'Support Tools'), t('admin.support.pageDescription', 'Impersonate restaurants and view audit logs'));
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<Tab>('impersonate');
  const [search, setSearch] = useState('');
  const [severityFilter, setSeverityFilter] = useState('all');
  const [impersonating, setImpersonating] = useState<string | null>(null);
  const [restaurants, setRestaurants] = useState<Restaurant[]>([]);
  const [auditLogs, setAuditLogs] = useState<AuditLogEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [refetching, setRefetching] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleImpersonate = useCallback(async (restaurantId: string, restaurantName: string) => {
    try {
      const res = await fetch('/api/admin/support/impersonate', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ restaurantId, restaurantName }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error?.message ?? t('admin.support.impersonationFailed', 'Impersonation failed'));
      }
      setImpersonating(restaurantName);
      toast.success(t('admin.support.nowViewingAs', 'Now viewing as {name}').replace('{name}', restaurantName));
      router.push('/restaurant-dashboard');
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('admin.support.failedToImpersonate', 'Failed to impersonate restaurant'));
    }
  }, [router, t]);

  const fetchData = useCallback(async (isRetry = false) => {
    setError(null);
    if (isRetry) setRefetching(true);
    try {
      const [supportResult, restaurantResult] = await Promise.all([
        getAdminSupport({ search, severity: severityFilter }),
        getAdminRestaurants(),
      ]);
      setRestaurants(restaurantResult.restaurants ?? []);
      setAuditLogs(supportResult.auditLogs ?? []);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : t('admin.support.failedToLoadData', 'Failed to load support data');
      setError(msg);
      toast.error(msg);
    } finally {
      setLoading(false);
      setRefetching(false);
    }
  }, [search, severityFilter, t]);

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

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="animate-spin" size={32} style={{ color: 'hsl(var(--muted-foreground))' }} />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-3">
        <AlertCircle size={32} style={{ color: 'hsl(var(--danger))' }} />
        <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.support.failedToLoadTools', 'Failed to load support tools')}</p>
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{error}</p>
        <button onClick={() => fetchData(true)} disabled={refetching} className="btn-secondary text-sm mt-2 flex items-center gap-1.5">
          {refetching && <Loader2 size={13} className="animate-spin" />}
          {refetching ? t('admin.support.retrying', 'Retrying…') : t('admin.support.retry', 'Retry')}
        </button>
      </div>
    );
  }

  return (
    <>
      <div className="flex items-center gap-3 px-4 py-3 rounded-xl mb-6" style={{ backgroundColor: 'hsl(231, 40%, 14%)', color: 'white' }}>
        <div className="w-2 h-2 rounded-full bg-orange-400 animate-pulse" />
        <span className="text-sm font-semibold">{t('admin.support.adminPanel', 'Admin Panel')}</span>
        <span className="text-xs opacity-60">— {t('admin.support.actionsLogged', 'All actions in this panel are logged')}</span>
      </div>

      <div className="flex gap-1 p-1 rounded-xl mb-6 w-fit" style={{ backgroundColor: 'hsl(var(--muted))' }}>
        {[
          { key: 'impersonate', label: t('admin.support.tab.impersonate', 'Impersonate Restaurant') },
          { key: 'audit', label: t('admin.support.tab.audit', 'Audit Logs') }
        ].map(tTab => (
          <button
            key={tTab.key}
            onClick={() => setActiveTab(tTab.key as Tab)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === tTab.key ? 'bg-white shadow-sm' : ''}`}
            style={{ color: activeTab === tTab.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
          >
            {tTab.label}
          </button>
        ))}
      </div>

      {activeTab === 'impersonate' && (
        <div>
          {impersonating && (
            <div className="flex items-center justify-between px-4 py-3 rounded-xl mb-4" style={{ backgroundColor: 'hsl(38, 100%, 96%)', border: '1px solid hsl(38, 92%, 80%)' }}>
              <div className="flex items-center gap-2">
                <Eye size={16} style={{ color: 'hsl(var(--warning))' }} />
                <span className="text-sm font-semibold" style={{ color: 'hsl(var(--warning))' }}>
                  {t('admin.support.impersonatingHeader', 'Impersonating: {name} — You are viewing their dashboard').replace('{name}', impersonating)}
                </span>
              </div>
              <button className="btn-secondary text-sm py-1" onClick={() => setImpersonating(null)}>{t('admin.support.exitSession', 'Exit Session')}</button>
            </div>
          )}
          {restaurants.length > 0 ? (
            <div className="grid gap-3">
              {restaurants.map(r => (
                <div key={r.id} className="card p-4 flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-xl flex items-center justify-center text-white font-bold" style={{ backgroundColor: 'hsl(231, 40%, 14%)' }}>
                      {r.name[0]}
                    </div>
                    <div>
                      <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{r.name}</p>
                      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{r.owner} · {r.plan}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className={`badge ${r.status === 'active' ? 'badge-success' : 'badge-warning'}`}>{t(`admin.support.status.${r.status}`, r.status)}</span>
                    <button
                      className="btn-secondary text-sm py-1.5 flex items-center gap-1.5"
                      onClick={() => handleImpersonate(r.id, r.name)}
                    >
                      <Eye size={14} /> {t('admin.support.impersonate', 'Impersonate')}
                    </button>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-sm py-10 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.support.noRestaurantsFound', 'No restaurants found')}</p>
          )}
        </div>
      )}

      {activeTab === 'audit' && (
        <div>
          <div className="flex flex-col sm:flex-row gap-3 mb-4">
            <div className="relative flex-1 max-w-sm">
              <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <input
                className="input-base pl-9"
                placeholder={t('admin.support.searchAuditPlaceholder', 'Search by actor, action, resource…')}
                value={search}
                onChange={e => setSearch(e.target.value)}
              />
            </div>
            <div className="flex gap-2">
              {['all', 'info', 'warning', 'critical'].map(s => (
                <button
                  key={s}
                  onClick={() => setSeverityFilter(s)}
                  className={`px-3 py-1.5 rounded-lg text-sm font-medium capitalize transition-all ${severityFilter === s ? 'btn-primary' : 'btn-secondary'}`}
                >
                  {t(`admin.support.severity.${s}`, s)}
                </button>
              ))}
            </div>
          </div>

          <div className="card overflow-hidden">
            {auditLogs.length > 0 ? (
              <table className="w-full">
                <thead>
                  <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                    {[
                      { key: 'actor', label: 'Actor' },
                      { key: 'action', label: 'Action' },
                      { key: 'resource', label: 'Resource' },
                      { key: 'timestamp', label: 'Timestamp' },
                      { key: 'ip', label: 'IP' },
                      { key: 'severity', label: 'Severity' }
                    ].map(h => (
                      <th key={h.key} className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {t(`admin.support.table.${h.key}`, h.label)}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {auditLogs.map((log, idx) => (
                    <tr key={log.id} className="table-row-hover" style={{ borderBottom: idx < auditLogs.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          {actorTypeIcon(log.actorType)}
                          <span className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{log.actor}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-sm" style={{ color: 'hsl(var(--foreground-secondary))' }}>{log.action}</td>
                      <td className="px-4 py-3"><span className="badge badge-neutral">{log.resource || '—'}</span></td>
                      <td className="px-4 py-3 text-xs font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>{formatTimestamp(log.timestamp)}</td>
                      <td className="px-4 py-3 text-xs font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>{log.ip}</td>
                      <td className="px-4 py-3"><span className={`badge ${severityConfig[log.severity] ?? 'badge-neutral'}`}>{t(`admin.support.severity.${log.severity}`, log.severity)}</span></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <p className="text-sm py-10 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.support.noAuditLogs', 'No audit logs recorded yet')}</p>
            )}
          </div>
        </div>
      )}
    </>
  );
}
