'use client';

import { useCallback, useEffect, useState } from 'react';
import { AlertTriangle, Loader2, Plus, Save, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';

export type M365SenderRow = {
  email: string;
  name: string;
  companyId?: number;
  active: boolean;
  note?: string;
};

function emptyRow(): M365SenderRow {
  return { email: '', name: '', active: true, note: '' };
}

export interface M365SendersPoolTabProps {
  /** Nach erfolgreichem Speichern — z. B. Parent lädt `/api/m365/senders` neu. */
  onSaved?: () => void;
}

export function M365SendersPoolTab({ onSaved }: M365SendersPoolTabProps) {
  const [rows, setRows] = useState<M365SenderRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [flash, setFlash] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/m365/senders?includeInactive=1');
      const data = await res.json();
      if (!res.ok) {
        setError(data.error ?? `HTTP ${res.status}`);
        setRows([emptyRow()]);
        return;
      }
      const list = (data.senders ?? []) as M365SenderRow[];
      setRows(list.length > 0 ? list.map(normalizeRow) : [emptyRow()]);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Netzwerkfehler');
      setRows([emptyRow()]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const updateRow = (index: number, patch: Partial<M365SenderRow>) => {
    setRows((prev) => {
      const next = [...prev];
      next[index] = { ...next[index], ...patch };
      return next;
    });
  };

  const removeRow = (index: number) => {
    setRows((prev) => (prev.length <= 1 ? [emptyRow()] : prev.filter((_, i) => i !== index)));
  };

  const addRow = () => {
    setRows((prev) => [...prev, emptyRow()]);
  };

  const handleSave = async () => {
    setSaving(true);
    setError(null);
    setFlash(null);
    const cleaned: M365SenderRow[] = [];
    for (const r of rows) {
      const email = r.email.trim().toLowerCase();
      const name = r.name.trim();
      if (!email && !name) continue;
      if (!email || !name) {
        setError('Jede Zeile mit Inhalt braucht E-Mail und Anzeige-Name — oder Zeile leeren zum Entfernen.');
        setSaving(false);
        return;
      }
      const rawCid = r.companyId;
      const companyId =
        rawCid === undefined || rawCid === null || Number.isNaN(Number(rawCid))
          ? undefined
          : Math.max(1, Math.floor(Number(rawCid)));
      cleaned.push({
        email,
        name,
        active: r.active,
        ...(companyId !== undefined ? { companyId } : {}),
        ...(r.note?.trim() ? { note: r.note.trim() } : {}),
      });
    }

    try {
      const res = await fetch('/api/m365/senders', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ senders: cleaned }),
      });
      const data = await res.json();
      if (!res.ok) {
        const issues = Array.isArray(data.issues) ? data.issues.join('; ') : '';
        setError([data.error, issues].filter(Boolean).join(' ') || `HTTP ${res.status}`);
        return;
      }
      const saved = (data.senders ?? []) as M365SenderRow[];
      setRows(saved.length > 0 ? saved.map(normalizeRow) : [emptyRow()]);
      setFlash('Sender-Pool gespeichert.');
      onSaved?.();
      setTimeout(() => setFlash(null), 4000);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Netzwerkfehler');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center gap-2 text-sm text-zinc-500">
        <Loader2 className="h-4 w-4 animate-spin" />
        Lade M365-Sender …
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-xs text-blue-900 dark:border-blue-900/50 dark:bg-blue-950/30 dark:text-blue-200">
        <strong>Microsoft Graph</strong> nutzt dieselben Zugangsdaten wie der Versand: App Registration im Tenant,
        Client Secret und ggf. <code className="rounded bg-blue-100/80 px-1 dark:bg-blue-900/60">send_provider_config</code>{' '}
        (Plugin-Seite <code className="rounded bg-blue-100/80 px-1 dark:bg-blue-900/60">/settings</code>) oder die{' '}
        <code className="rounded bg-blue-100/80 px-1 dark:bg-blue-900/60">M365_*</code>-Umgebungsvariablen.
        Hier trägst du nur die <strong>Mailboxen</strong> ein, von denen Graph senden darf (eine Zeile pro Absender).
      </div>

      <div className="rounded-md border border-zinc-200 bg-zinc-50 px-3 py-2 text-xs text-zinc-700 dark:border-zinc-700 dark:bg-zinc-900/50 dark:text-zinc-300">
        <strong>Workspace-Zuordnung:</strong> Unter „Workspaces“ kann pro Workspace eine <em>Pool-Zuordnung (numerisch)</em>{' '}
        gesetzt werden. Sie muss mit der Spalte „Zuordnung“ eines <strong>aktiven</strong> Pool-Senders übereinstimmen,
        wenn beim Versand kein expliziter Absender gewählt wird. Beliebige positive ganze Zahl — nicht auf 1–3 begrenzt.
        <span className="mt-1 block opacity-90">Ist nur <strong>ein</strong> aktiver Pool-Sender konfiguriert, wird der automatisch verwendet (ohne Zuordnung am Workspace).</span>
      </div>

      {flash && (
        <div className="rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-xs text-emerald-900 dark:border-emerald-900/40 dark:bg-emerald-950/30 dark:text-emerald-200">
          {flash}
        </div>
      )}
      {error && (
        <div className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-900 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-200">
          <AlertTriangle className="h-4 w-4 shrink-0" />
          <span>{error}</span>
        </div>
      )}

      <div className="overflow-x-auto rounded-lg border border-zinc-200 dark:border-zinc-800">
        <table className="w-full min-w-[640px] border-collapse text-left text-xs">
          <thead>
            <tr className="border-b border-zinc-200 bg-zinc-100 dark:border-zinc-800 dark:bg-zinc-900">
              <th className="px-2 py-2 font-semibold text-zinc-600 dark:text-zinc-400">Aktiv</th>
              <th className="px-2 py-2 font-semibold text-zinc-600 dark:text-zinc-400">E-Mail (Mailbox)</th>
              <th className="px-2 py-2 font-semibold text-zinc-600 dark:text-zinc-400">Anzeige-Name</th>
              <th className="px-2 py-2 font-semibold text-zinc-600 dark:text-zinc-400">Zuordnung</th>
              <th className="px-2 py-2 font-semibold text-zinc-600 dark:text-zinc-400">Notiz</th>
              <th className="w-10 px-1 py-2" />
            </tr>
          </thead>
          <tbody>
            {rows.map((row, i) => (
              <tr key={i} className="border-b border-zinc-100 dark:border-zinc-800">
                <td className="px-2 py-1.5 align-middle">
                  <input
                    type="checkbox"
                    checked={row.active}
                    onChange={(e) => updateRow(i, { active: e.target.checked })}
                    className="rounded border-zinc-300"
                  />
                </td>
                <td className="px-2 py-1.5 align-middle">
                  <input
                    value={row.email}
                    onChange={(e) => updateRow(i, { email: e.target.value })}
                    placeholder="newsletter@firma.de"
                    className="w-full min-w-[160px] rounded border border-zinc-200 bg-white px-2 py-1 font-mono text-[11px] dark:border-zinc-700 dark:bg-zinc-950"
                  />
                </td>
                <td className="px-2 py-1.5 align-middle">
                  <input
                    value={row.name}
                    onChange={(e) => updateRow(i, { name: e.target.value })}
                    placeholder="Newsletter Team"
                    className="w-full min-w-[120px] rounded border border-zinc-200 bg-white px-2 py-1 dark:border-zinc-700 dark:bg-zinc-950"
                  />
                </td>
                <td className="px-2 py-1.5 align-middle">
                  <input
                    type="number"
                    min={1}
                    value={row.companyId ?? ''}
                    onChange={(e) => {
                      const t = e.target.value;
                      if (t === '') {
                        updateRow(i, { companyId: undefined });
                        return;
                      }
                      const n = parseInt(t, 10);
                      updateRow(i, { companyId: Number.isFinite(n) && n > 0 ? n : undefined });
                    }}
                    placeholder="optional"
                    className="w-20 rounded border border-zinc-200 bg-white px-2 py-1 dark:border-zinc-700 dark:bg-zinc-950"
                  />
                </td>
                <td className="px-2 py-1.5 align-middle">
                  <input
                    value={row.note ?? ''}
                    onChange={(e) => updateRow(i, { note: e.target.value })}
                    placeholder="z. B. Kampagne A"
                    className="w-full min-w-[100px] rounded border border-zinc-200 bg-white px-2 py-1 dark:border-zinc-700 dark:bg-zinc-950"
                  />
                </td>
                <td className="px-1 py-1.5 align-middle text-center">
                  <button
                    type="button"
                    onClick={() => removeRow(i)}
                    className={cn(
                      'rounded p-1 text-zinc-400 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/30',
                    )}
                    title="Zeile entfernen"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="flex flex-wrap items-center gap-2">
        <button
          type="button"
          onClick={addRow}
          className="inline-flex items-center gap-1.5 rounded-md border border-zinc-200 bg-white px-3 py-1.5 text-xs font-medium text-zinc-700 hover:bg-zinc-50 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:bg-zinc-800"
        >
          <Plus className="h-3.5 w-3.5" />
          Zeile
        </button>
        <button
          type="button"
          onClick={() => void handleSave()}
          disabled={saving}
          className="inline-flex items-center gap-1.5 rounded-md bg-zinc-900 px-3 py-1.5 text-xs font-medium text-white hover:bg-zinc-800 disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-zinc-200"
        >
          {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
          Pool speichern
        </button>
      </div>
    </div>
  );
}

function normalizeRow(r: M365SenderRow): M365SenderRow {
  return {
    email: r.email,
    name: r.name,
    active: r.active !== false,
    ...(r.companyId != null ? { companyId: r.companyId } : {}),
    ...(r.note ? { note: r.note } : {}),
  };
}
