'use client';

/**
 * Verwaltungs-Panel für freigeschaltete Trigger-Templates (Settings-Drawer-Tab).
 *
 * Funktionen:
 *  - Liste aller Templates mit Status, Trigger-Count, letztem Trigger.
 *  - Activate/Deactivate-Toggle.
 *  - API-Key rotieren (alter sofort ungültig, neuer wird einmalig angezeigt).
 *  - Logs der letzten 100 Trigger-Calls (auch abgewiesene).
 */

import { useEffect, useState } from 'react';
import { Loader2, Webhook, RefreshCw, Eye, ShieldOff, ShieldCheck, Copy, X } from 'lucide-react';
import { cn } from '@/lib/utils';

interface TriggerTemplateView {
  id: string;
  key: string;
  name: string;
  description: string | null;
  workspaceId: string;
  subject: string;
  preheader: string;
  senderEmail: string | null;
  apiKeyPrefix: string;
  isActive: boolean;
  rateLimitPerHour: number | null;
  triggerCount: number;
  lastTriggeredAt: string | null;
  variableSchema: Array<{ key: string; required: boolean }>;
  createdAt: string;
  updatedAt: string;
}

interface TriggerLog {
  id: string;
  recipientEmail: string;
  status: string;
  errorMessage: string | null;
  idempotencyKey: string | null;
  emailQueueJobId: string | null;
  createdAt: string;
}

export function TriggerTemplatesPanel() {
  const [templates, setTemplates] = useState<TriggerTemplateView[] | null>(null);
  const [loading, setLoading] = useState(true);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [logs, setLogs] = useState<Record<string, TriggerLog[]>>({});
  const [logsLoading, setLogsLoading] = useState<string | null>(null);
  const [rotatedKey, setRotatedKey] = useState<{ id: string; apiKey: string } | null>(null);

  const reload = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/trigger-templates');
      const json = await res.json();
      setTemplates(json.templates ?? []);
    } finally {
      setLoading(false);
    }
  };

  // Initial-Load der Liste beim Mount. setState im Effect ist hier der Standard-
  // Datenfetch-Pattern und im Codebase etabliert.
  // eslint-disable-next-line react-hooks/set-state-in-effect
  useEffect(() => { reload(); }, []);

  const toggleActive = async (t: TriggerTemplateView) => {
    const next = !t.isActive;
    await fetch(`/api/trigger-templates/${t.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ isActive: next }),
    });
    reload();
  };

  const rotateKey = async (id: string) => {
    if (!confirm('API-Key wirklich rotieren? Der alte Key wird sofort ungültig — externe Systeme müssen den neuen Key sofort eintragen.')) return;
    const res = await fetch(`/api/trigger-templates/${id}/rotate-key`, { method: 'POST' });
    const json = await res.json();
    if (res.ok && json.apiKey) {
      setRotatedKey({ id, apiKey: json.apiKey });
      reload();
    } else {
      alert(json.error ?? 'Rotation fehlgeschlagen');
    }
  };

  const loadLogs = async (id: string) => {
    setLogsLoading(id);
    try {
      const res = await fetch(`/api/trigger-templates/${id}/logs`);
      const json = await res.json();
      setLogs(prev => ({ ...prev, [id]: json.logs ?? [] }));
    } finally {
      setLogsLoading(null);
    }
  };

  const expand = async (id: string) => {
    if (expandedId === id) {
      setExpandedId(null);
      return;
    }
    setExpandedId(id);
    if (!logs[id]) await loadLogs(id);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-16 text-zinc-500">
        <Loader2 className="h-5 w-5 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-sm font-semibold">Freigeschaltete Trigger-Templates</h3>
          <p className="text-xs text-zinc-500">
            Templates, die externe Systeme (Online-Shop, CRM) per HTTP-API auslösen können.
          </p>
        </div>
        <button onClick={reload} className="rounded-md p-1.5 text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800">
          <RefreshCw className="h-3.5 w-3.5" />
        </button>
      </div>

      {(!templates || templates.length === 0) && (
        <div className="rounded-md border border-dashed border-zinc-300 p-6 text-center text-xs text-zinc-500 dark:border-zinc-700">
          Noch keine Trigger-Templates. Öffne einen fertigen Draft im Email-Tab und klicke &bdquo;Als Trigger freischalten&ldquo;.
        </div>
      )}

      {templates?.map(t => (
        <div
          key={t.id}
          className={cn(
            'rounded-md border bg-white dark:bg-zinc-900',
            t.isActive ? 'border-zinc-200 dark:border-zinc-800' : 'border-zinc-200 opacity-60 dark:border-zinc-800',
          )}
        >
          <div className="flex items-start gap-3 p-3">
            <Webhook className={cn('mt-0.5 h-4 w-4', t.isActive ? 'text-emerald-500' : 'text-zinc-400')} />
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2">
                <code className="rounded bg-zinc-100 px-1.5 py-0.5 font-mono text-[11px] dark:bg-zinc-800">
                  /api/trigger/{t.key}
                </code>
                <span className={cn(
                  'rounded-full px-1.5 py-0.5 text-[10px] font-medium',
                  t.isActive
                    ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
                    : 'bg-zinc-100 text-zinc-500 dark:bg-zinc-800',
                )}>
                  {t.isActive ? 'aktiv' : 'inaktiv'}
                </span>
              </div>
              <div className="mt-1 text-sm font-medium">{t.name}</div>
              {t.description && <div className="text-xs text-zinc-500">{t.description}</div>}
              <div className="mt-1.5 flex flex-wrap gap-3 text-[11px] text-zinc-500">
                <span>API-Key: <code className="font-mono">{t.apiKeyPrefix}…</code></span>
                <span>{t.triggerCount} Trigger</span>
                {t.lastTriggeredAt && (
                  <span>zuletzt: {new Date(t.lastTriggeredAt).toLocaleString('de-DE')}</span>
                )}
                {t.rateLimitPerHour && <span>Limit: {t.rateLimitPerHour}/h</span>}
                <span>{t.variableSchema.length} Variablen</span>
              </div>
            </div>
            <div className="flex items-center gap-1">
              <IconBtn title={t.isActive ? 'Deaktivieren' : 'Aktivieren'} onClick={() => toggleActive(t)}>
                {t.isActive ? <ShieldOff className="h-3.5 w-3.5" /> : <ShieldCheck className="h-3.5 w-3.5" />}
              </IconBtn>
              <IconBtn title="Key rotieren" onClick={() => rotateKey(t.id)}>
                <RefreshCw className="h-3.5 w-3.5" />
              </IconBtn>
              <IconBtn title="Logs anzeigen" onClick={() => expand(t.id)}>
                <Eye className="h-3.5 w-3.5" />
              </IconBtn>
            </div>
          </div>

          {expandedId === t.id && (
            <div className="border-t border-zinc-100 bg-zinc-50/60 p-3 dark:border-zinc-800 dark:bg-zinc-900/40">
              <div className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-zinc-500">
                Letzte 100 Trigger-Calls
              </div>
              {logsLoading === t.id ? (
                <div className="flex items-center gap-2 py-3 text-xs text-zinc-500">
                  <Loader2 className="h-3 w-3 animate-spin" /> Lädt…
                </div>
              ) : (logs[t.id]?.length ?? 0) === 0 ? (
                <div className="py-3 text-xs text-zinc-500">Noch keine Trigger.</div>
              ) : (
                <div className="max-h-64 overflow-y-auto">
                  <table className="w-full text-[11px]">
                    <thead className="sticky top-0 bg-zinc-50 text-left text-zinc-500 dark:bg-zinc-900">
                      <tr>
                        <th className="py-1 pr-2 font-medium">Zeit</th>
                        <th className="py-1 pr-2 font-medium">Status</th>
                        <th className="py-1 pr-2 font-medium">Empfänger</th>
                        <th className="py-1 pr-2 font-medium">Idempotency</th>
                        <th className="py-1 font-medium">Fehler</th>
                      </tr>
                    </thead>
                    <tbody>
                      {logs[t.id]?.map(l => (
                        <tr key={l.id} className="border-t border-zinc-100 dark:border-zinc-800">
                          <td className="py-1 pr-2 font-mono text-zinc-500">{new Date(l.createdAt).toLocaleTimeString('de-DE')}</td>
                          <td className="py-1 pr-2">
                            <span className={cn(
                              'rounded px-1 py-0.5 text-[10px] font-medium',
                              l.status === 'queued' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
                                : l.status === 'duplicate' ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300'
                                : 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
                            )}>
                              {l.status}
                            </span>
                          </td>
                          <td className="py-1 pr-2 truncate max-w-[160px]">{l.recipientEmail}</td>
                          <td className="py-1 pr-2 truncate max-w-[120px] font-mono text-zinc-500">{l.idempotencyKey ?? '—'}</td>
                          <td className="py-1 truncate text-red-600 dark:text-red-400">{l.errorMessage ?? ''}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}
        </div>
      ))}

      {rotatedKey && <RotatedKeyModal apiKey={rotatedKey.apiKey} onClose={() => setRotatedKey(null)} />}
    </div>
  );
}

function IconBtn({ title, onClick, children }: { title: string; onClick: () => void; children: React.ReactNode }) {
  return (
    <button title={title} onClick={onClick} className="rounded-md p-1.5 text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800">
      {children}
    </button>
  );
}

function RotatedKeyModal({ apiKey, onClose }: { apiKey: string; onClose: () => void }) {
  const [copied, setCopied] = useState(false);
  return (
    <>
      <div className="fixed inset-0 z-[60] bg-black/50" onClick={onClose} />
      <div className="fixed inset-0 z-[70] flex items-center justify-center p-4">
        <div className="w-full max-w-[500px] rounded-xl border border-amber-300 bg-amber-50 p-4 shadow-2xl dark:border-amber-900 dark:bg-amber-950/40">
          <div className="mb-3 flex items-start justify-between">
            <div>
              <h4 className="text-sm font-semibold text-amber-900 dark:text-amber-100">Neuer API-Key</h4>
              <p className="text-[11px] text-amber-800 dark:text-amber-300">Wird nicht erneut angezeigt — bitte sofort kopieren.</p>
            </div>
            <button onClick={onClose} className="text-amber-700 hover:text-amber-900">
              <X className="h-4 w-4" />
            </button>
          </div>
          <div className="flex items-center gap-2">
            <code className="flex-1 select-all rounded bg-white px-3 py-2 font-mono text-xs ring-1 ring-amber-300 dark:bg-zinc-950 dark:ring-amber-900">
              {apiKey}
            </code>
            <button
              onClick={() => { navigator.clipboard.writeText(apiKey); setCopied(true); setTimeout(() => setCopied(false), 2000); }}
              className="inline-flex items-center gap-1.5 rounded-md bg-amber-600 px-3 py-2 text-xs font-medium text-white hover:bg-amber-700"
            >
              <Copy className="h-3 w-3" />
              {copied ? 'Kopiert' : 'Kopieren'}
            </button>
          </div>
        </div>
      </div>
    </>
  );
}
