'use client';
import React, { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';

const SITES = ['avbeat','avbeat','backlotbeat','broadcastengineering'];
const SUPP_TYPES = ['unsubscribe','bounce_hard','bounce_soft','spam_complaint','hostile_reply','manual'];

export default function SuppressionsPage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [site, setSite] = useState('avbeat');
  const [suppressions, setSuppressions] = useState<any[]>([]);
  const [keywords, setKeywords] = useState<any[]>([]);
  const [stats, setStats] = useState<any>(null);
  const [loadingData, setLoadingData] = useState(true);
  const [filterType, setFilterType] = useState('');
  const [search, setSearch] = useState('');
  const [showAddForm, setShowAddForm] = useState(false);
  const [showKeywordForm, setShowKeywordForm] = useState(false);
  const [addForm, setAddForm] = useState({ email: '', suppression_type: 'manual', notes: '' });
  const [keywordForm, setKeywordForm] = useState({ keyword: '', keyword_type: 'unsubscribe' });
  const [saving, setSaving] = useState(false);

  useEffect(() => { if (!loading && !user) router.push('/login?next=' + encodeURIComponent(window.location.pathname)); }, [user, loading, router]);

  const load = useCallback(async () => {
    setLoadingData(true);
    const params = new URLSearchParams({ site });
    if (filterType) params.set('type', filterType);
    if (search) params.set('search', search);
    const [suppR, kwR, statsR] = await Promise.all([
      fetch(`/api/email/rmp/suppressions?${params}`),
      fetch('/api/email/rmp/keywords'),
      fetch(`/api/email/rmp/suppressions/stats?site=${site}`),
    ]);
    const [sd, kd, stD] = await Promise.all([suppR.json(), kwR.json(), statsR.json()]);
    setSuppressions(sd.suppressions ?? []);
    setKeywords(kd.keywords ?? []);
    setStats(stD);
    setLoadingData(false);
  }, [site, filterType, search]);

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

  async function handleAddSuppression(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    await fetch('/api/email/rmp/suppressions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...addForm, site }) });
    setSaving(false);
    setShowAddForm(false);
    load();
  }

  async function handleAddKeyword(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    await fetch('/api/email/rmp/keywords', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(keywordForm) });
    setSaving(false);
    setShowKeywordForm(false);
    load();
  }

  async function removeSuppression(id: string) {
    await fetch(`/api/email/rmp/suppressions/${id}`, { method: 'DELETE' });
    load();
  }

  async function toggleKeyword(id: string, active: boolean) {
    await fetch(`/api/email/rmp/keywords/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ active: !active }) });
    load();
  }

  if (loading) return <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center"><div className="w-8 h-8 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" /></div>;
  if (!user) return null;

  return (
    <div className="min-h-screen bg-[#0a0a0a] text-white p-6">
      <div className="max-w-6xl mx-auto space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-bold">Email Suppressions</h1>
            <Link href="/admin/email" className="text-xs text-[#555] hover:text-[#888]">← Email</Link>
          </div>
          <div className="flex gap-2">
            <button onClick={() => setShowAddForm(true)} className="px-3 py-1.5 bg-[#1D4ED8] rounded text-xs font-medium hover:bg-blue-500">+ Add Suppression</button>
          </div>
        </div>

        {/* Site selector */}
        <div className="flex gap-1 flex-wrap">
          {SITES.map(s => (
            <button key={s} onClick={() => setSite(s)} className={`px-3 py-1 rounded text-xs capitalize ${site === s ? 'bg-[#1D4ED8] text-white' : 'bg-[#111] border border-[#DCE6F2] text-[#888]'}`}>{s}</button>
          ))}
        </div>

        {/* Stats */}
        {stats && (
          <div className="grid grid-cols-3 gap-3">
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-3">
              <p className="text-xl font-bold text-red-400">{stats.total ?? 0}</p>
              <p className="text-xs text-[#888] mt-0.5">Total Suppressed</p>
            </div>
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-3">
              <p className="text-xl font-bold text-yellow-400">{stats.added_this_month ?? 0}</p>
              <p className="text-xs text-[#888] mt-0.5">Added This Month</p>
            </div>
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-3">
              <p className="text-xl font-bold text-orange-400">{stats.hostile_replies ?? 0}</p>
              <p className="text-xs text-[#888] mt-0.5">Hostile Replies</p>
            </div>
          </div>
        )}

        {/* Filters */}
        <div className="flex gap-2 flex-wrap">
          <select value={filterType} onChange={e => setFilterType(e.target.value)} className="px-2 py-1 bg-[#111] border border-[#DCE6F2] rounded text-xs text-[#888] focus:outline-none">
            <option value="">All Types</option>
            {SUPP_TYPES.map(t => <option key={t} value={t}>{t.replace(/_/g, ' ')}</option>)}
          </select>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search email…" className="px-2 py-1 bg-[#111] border border-[#DCE6F2] rounded text-xs text-white placeholder-[#555] focus:outline-none focus:border-[#1D4ED8]" />
        </div>

        {showAddForm && (
          <form onSubmit={handleAddSuppression} className="bg-[#111] border border-[#DCE6F2] rounded-lg p-4 space-y-3">
            <h3 className="text-sm font-semibold">Add Manual Suppression</h3>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="text-xs text-[#888] block mb-1">Email *</label>
                <input required type="email" value={addForm.email} onChange={e => setAddForm(p => ({ ...p, email: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none focus:border-[#1D4ED8]" />
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Type</label>
                <select value={addForm.suppression_type} onChange={e => setAddForm(p => ({ ...p, suppression_type: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none">
                  {SUPP_TYPES.map(t => <option key={t} value={t}>{t.replace(/_/g, ' ')}</option>)}
                </select>
              </div>
              <div className="col-span-2">
                <label className="text-xs text-[#888] block mb-1">Notes</label>
                <input value={addForm.notes} onChange={e => setAddForm(p => ({ ...p, notes: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none focus:border-[#1D4ED8]" />
              </div>
            </div>
            <div className="flex gap-2">
              <button type="submit" disabled={saving} className="px-3 py-1.5 bg-[#1D4ED8] rounded text-xs font-medium hover:bg-blue-500 disabled:opacity-50">{saving ? 'Saving…' : 'Add'}</button>
              <button type="button" onClick={() => setShowAddForm(false)} className="px-3 py-1.5 bg-[#FFFFFF] border border-[#DCE6F2] rounded text-xs text-[#888] hover:text-white">Cancel</button>
            </div>
          </form>
        )}

        {/* Suppressions table */}
        <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-[#FFFFFF]">
                {['Email','Type','Source','Reply Text','Domain','Date',''].map(h => (
                  <th key={h} className="px-3 py-2 text-left text-xs text-[#555] font-medium">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {loadingData ? (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-[#555] text-xs">Loading…</td></tr>
              ) : suppressions.length === 0 ? (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-[#555] text-xs">No suppressions found</td></tr>
              ) : suppressions.map((s: any) => (
                <tr key={s.id} className="border-b border-[#FFFFFF] hover:bg-[#FFFFFF]">
                  <td className="px-3 py-2 text-white text-xs">{s.email}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs ${s.suppression_type === 'hostile_reply' ? 'bg-red-400/10 text-red-400' : s.suppression_type === 'unsubscribe' ? 'bg-yellow-400/10 text-yellow-400' : 'bg-[#FFFFFF] text-[#555]'}`}>{s.suppression_type?.replace(/_/g, ' ')}</span>
                  </td>
                  <td className="px-3 py-2 text-[#555] text-xs">{s.source}</td>
                  <td className="px-3 py-2 text-[#555] text-xs max-w-xs truncate">{s.reply_text ?? '—'}</td>
                  <td className="px-3 py-2 text-[#555] text-xs">{s.sending_domain ?? '—'}</td>
                  <td className="px-3 py-2 text-[#555] text-xs">{s.suppressed_at ? new Date(s.suppressed_at).toLocaleDateString() : '—'}</td>
                  <td className="px-3 py-2">
                    <button onClick={() => removeSuppression(s.id)} className="text-xs text-red-400 hover:underline">Remove</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Keyword Management */}
        <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
          <div className="px-4 py-3 border-b border-[#DCE6F2] flex items-center justify-between">
            <h2 className="text-sm font-semibold">Suppression Keywords</h2>
            <button onClick={() => setShowKeywordForm(true)} className="text-xs text-[#1D4ED8] hover:underline">+ Add Keyword</button>
          </div>
          {showKeywordForm && (
            <form onSubmit={handleAddKeyword} className="px-4 py-3 border-b border-[#FFFFFF] flex gap-2 items-end">
              <div>
                <label className="text-xs text-[#888] block mb-1">Keyword *</label>
                <input required value={keywordForm.keyword} onChange={e => setKeywordForm(p => ({ ...p, keyword: e.target.value }))} className="px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none focus:border-[#1D4ED8]" />
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Type</label>
                <select value={keywordForm.keyword_type} onChange={e => setKeywordForm(p => ({ ...p, keyword_type: e.target.value }))} className="px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none">
                  <option value="unsubscribe">unsubscribe</option>
                  <option value="hostile">hostile</option>
                </select>
              </div>
              <button type="submit" disabled={saving} className="px-3 py-1.5 bg-[#1D4ED8] rounded text-xs font-medium hover:bg-blue-500 disabled:opacity-50">Add</button>
              <button type="button" onClick={() => setShowKeywordForm(false)} className="px-3 py-1.5 bg-[#FFFFFF] border border-[#DCE6F2] rounded text-xs text-[#888]">Cancel</button>
            </form>
          )}
          <table className="w-full text-sm">
            <thead><tr className="border-b border-[#FFFFFF]">{['Keyword','Type','Active',''].map(h => <th key={h} className="px-4 py-2 text-left text-xs text-[#555]">{h}</th>)}</tr></thead>
            <tbody>
              {keywords.map((k: any) => (
                <tr key={k.id} className="border-b border-[#FFFFFF] hover:bg-[#FFFFFF]">
                  <td className="px-4 py-2 text-white text-xs">{k.keyword}</td>
                  <td className="px-4 py-2 text-[#888] text-xs">{k.keyword_type}</td>
                  <td className="px-4 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs ${k.active ? 'bg-green-400/10 text-green-400' : 'bg-[#FFFFFF] text-[#555]'}`}>{k.active ? 'Active' : 'Inactive'}</span>
                  </td>
                  <td className="px-4 py-2">
                    <button onClick={() => toggleKeyword(k.id, k.active)} className="text-xs text-[#1D4ED8] hover:underline">{k.active ? 'Deactivate' : 'Activate'}</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
