'use client';

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

interface BannedTerm {
  id: string;
  term: string;
  ban_level: 'soft' | 'hard';
  site_scope: 'avbeat' | 'avbeat' | 'both';
  is_active: boolean;
  notes: string | null;
  created_at: string;
  added_by_profile?: { full_name: string } | null;
}

interface FormState {
  term: string;
  ban_level: 'soft' | 'hard';
  site_scope: 'avbeat' | 'avbeat' | 'both';
  notes: string;
}

const EMPTY_FORM: FormState = { term: '', ban_level: 'soft', site_scope: 'both', notes: '' };

export default function BannedTermsPage() {
  const { user, loading } = useAuth();
  const router = useRouter();

  const [terms, setTerms] = useState<BannedTerm[]>([]);
  const [loadingData, setLoadingData] = useState(true);
  const [showAddForm, setShowAddForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<FormState>(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null);

  // Filters
  const [searchTerm, setSearchTerm] = useState('');
  const [filterBanLevel, setFilterBanLevel] = useState('');
  const [filterSiteScope, setFilterSiteScope] = useState('');
  const [filterActive, setFilterActive] = useState('');

  // Retroactive scan
  const [scanning, setScanning] = useState(false);
  const [scanResults, setScanResults] = useState<any[] | null>(null);

  const showToast = (message: string, type: 'success' | 'error' = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 4000);
  };

  const fetchTerms = useCallback(async () => {
    setLoadingData(true);
    try {
      const params = new URLSearchParams();
      if (searchTerm) params.set('search', searchTerm);
      if (filterBanLevel) params.set('ban_level', filterBanLevel);
      if (filterSiteScope) params.set('site_scope', filterSiteScope);
      if (filterActive !== '') params.set('active', filterActive);
      const res = await fetch(`/api/admin/banned-terms?${params}`);
      const data = await res.json();
      setTerms(data.terms || []);
    } catch { showToast('Failed to load banned terms', 'error'); }
    finally { setLoadingData(false); }
  }, [searchTerm, filterBanLevel, filterSiteScope, filterActive]);

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

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

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.term.trim()) { showToast('Term is required', 'error'); return; }
    setSaving(true);
    try {
      if (editingId) {
        const res = await fetch('/api/admin/banned-terms', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id: editingId, ...form }),
        });
        if (!res.ok) throw new Error((await res.json()).error);
        showToast('Term updated');
      } else {
        const res = await fetch('/api/admin/banned-terms', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(form),
        });
        if (!res.ok) throw new Error((await res.json()).error);
        showToast('Term added');
      }
      setForm(EMPTY_FORM); setShowAddForm(false); setEditingId(null);
      fetchTerms();
    } catch (err: any) { showToast(err.message || 'Failed to save', 'error'); }
    finally { setSaving(false); }
  };

  const handleDeactivate = async (id: string, currentActive: boolean) => {
    setActionLoading(id);
    try {
      const res = await fetch('/api/admin/banned-terms', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, is_active: !currentActive }),
      });
      if (!res.ok) throw new Error((await res.json()).error);
      showToast(currentActive ? 'Term deactivated' : 'Term reactivated');
      fetchTerms();
    } catch (err: any) { showToast(err.message || 'Failed', 'error'); }
    finally { setActionLoading(null); }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this banned term permanently?')) return;
    setActionLoading(id);
    try {
      const res = await fetch(`/api/admin/banned-terms?id=${id}`, { method: 'DELETE' });
      if (!res.ok) throw new Error((await res.json()).error);
      showToast('Term deleted');
      fetchTerms();
    } catch (err: any) { showToast(err.message || 'Failed', 'error'); }
    finally { setActionLoading(null); }
  };

  const handleEdit = (term: BannedTerm) => {
    setForm({ term: term.term, ban_level: term.ban_level, site_scope: term.site_scope, notes: term.notes || '' });
    setEditingId(term.id);
    setShowAddForm(true);
  };

  const handleRetroactiveScan = async () => {
    setScanning(true);
    setScanResults(null);
    try {
      const res = await fetch('/api/admin/banned-terms-scan', { method: 'POST' });
      const data = await res.json();
      setScanResults(data.matches || []);
      showToast(`Scan complete: ${data.matches?.length || 0} matches found`);
    } catch { showToast('Scan failed', 'error'); }
    finally { setScanning(false); }
  };

  const exportCSV = () => {
    const headers = ['Term', 'Ban Level', 'Site Scope', 'Active', 'Date Added', 'Notes'];
    const rows = terms.map(t => [t.term, t.ban_level, t.site_scope, t.is_active ? 'Yes' : 'No', new Date(t.created_at).toLocaleDateString(), t.notes || '']);
    const csv = [headers, ...rows].map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = 'banned-terms.csv'; a.click();
    URL.revokeObjectURL(url);
  };

  if (loading || loadingData) {
    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>
    );
  }

  return (
    <div className="min-h-screen bg-[#0a0a0a]">
      {toast && (
        <div className={`fixed top-4 right-4 z-50 px-4 py-3 rounded-lg text-sm font-body shadow-lg flex items-center gap-2 ${
          toast.type === 'success' ? 'bg-green-500/20 border border-green-500/40 text-green-300' : 'bg-red-500/20 border border-red-500/40 text-red-300'
        }`}>
          {toast.message}
        </div>
      )}

      <div className="max-w-7xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <Link href="/admin" className="text-[#555] hover:text-white text-sm font-body transition-colors">Admin</Link>
              <svg className="w-3.5 h-3.5 text-[#333]" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" /></svg>
              <span className="text-[#888] text-sm font-body">Banned Terms</span>
            </div>
            <h1 className="text-2xl font-display font-bold text-white">Banned Terms</h1>
            <p className="text-[#555] text-sm font-body mt-1">Manage restricted company names and keywords — visible to administrators only</p>
          </div>
          <div className="flex items-center gap-2">
            <button onClick={exportCSV} className="flex items-center gap-2 px-3 py-2 bg-[#FFFFFF] border border-[#333] text-[#888] hover:text-white text-sm font-body rounded-lg transition-colors">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /></svg>
              Export CSV
            </button>
            <button onClick={handleRetroactiveScan} disabled={scanning}
              className="flex items-center gap-2 px-3 py-2 bg-[#FFFFFF] border border-[#333] text-[#888] hover:text-white text-sm font-body rounded-lg transition-colors disabled:opacity-50">
              {scanning ? <div className="w-4 h-4 border-2 border-[#888]/30 border-t-[#888] rounded-full animate-spin" /> : <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>}
              Scan Published Posts
            </button>
            <button onClick={() => { setForm(EMPTY_FORM); setEditingId(null); setShowAddForm(true); }}
              className="flex items-center gap-2 px-4 py-2 bg-[#1D4ED8] hover:bg-blue-500 text-white text-sm font-body font-semibold rounded-lg transition-colors">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" /></svg>
              Add Term
            </button>
          </div>
        </div>

        {/* Retroactive scan results */}
        {scanResults !== null && (
          <div className="mb-6 bg-[#111] border border-[#DCE6F2] rounded-lg p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-display font-bold text-white">Retroactive Scan Results — {scanResults.length} match{scanResults.length !== 1 ? 'es' : ''} found</h3>
              <button onClick={() => setScanResults(null)} className="text-[#555] hover:text-white text-xs font-body">Dismiss</button>
            </div>
            {scanResults.length === 0 ? (
              <p className="text-[#555] text-sm font-body">No published posts contain currently active banned terms.</p>
            ) : (
              <div className="space-y-2 max-h-64 overflow-y-auto">
                {scanResults.map((r: any, i: number) => (
                  <div key={i} className="flex items-center gap-3 px-3 py-2 bg-[#0a0a0a] rounded-lg">
                    <span className="text-xs px-2 py-0.5 rounded bg-red-500/10 text-red-400 font-bold">{r.matched_term}</span>
                    <span className="text-sm text-white flex-1 truncate">{r.title}</span>
                    <span className="text-xs text-[#555]">{r.author}</span>
                    <span className="text-xs text-[#555]">{new Date(r.published_at).toLocaleDateString()}</span>
                    <span className="text-xs px-1.5 py-0.5 rounded bg-[#0ea5e9]/10 text-[#0ea5e9]">{r.site_id === 2 ? 'AV' : 'BB'}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Add/Edit Form */}
        {showAddForm && (
          <div className="mb-6 bg-[#111] border border-[#DCE6F2] rounded-lg p-6">
            <h3 className="text-sm font-display font-bold text-white mb-4">{editingId ? 'Edit Term' : 'Add Banned Term'}</h3>
            <form onSubmit={handleSave} className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="md:col-span-2">
                <label className="block text-xs font-body text-[#888] mb-1.5">Term / Company Name *</label>
                <input type="text" value={form.term} onChange={e => setForm(f => ({ ...f, term: e.target.value }))} placeholder="e.g. Sony, Acme Corp"
                  className="w-full bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]" required />
              </div>
              <div>
                <label className="block text-xs font-body text-[#888] mb-1.5">Ban Level</label>
                <select value={form.ban_level} onChange={e => setForm(f => ({ ...f, ban_level: e.target.value as 'soft' | 'hard' }))}
                  className="w-full bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]">
                  <option value="soft">Soft Ban — Flag for review (contributor doesn't know)</option>
                  <option value="hard">Hard Ban — Block submission entirely</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-body text-[#888] mb-1.5">Site Scope</label>
                <select value={form.site_scope} onChange={e => setForm(f => ({ ...f, site_scope: e.target.value as any }))}
                  className="w-full bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8]">
                  <option value="both">Both Sites</option>
                  <option value="avbeat">AV Beat only</option>
                  <option value="avbeat">AV Beat only</option>
                </select>
              </div>
              <div className="md:col-span-2">
                <label className="block text-xs font-body text-[#888] mb-1.5">Internal Notes (not shown to contributors)</label>
                <textarea value={form.notes} onChange={e => setForm(f => ({ ...f, notes: e.target.value }))} rows={2} placeholder="Reason for ban, context..."
                  className="w-full bg-[#0a0a0a] border border-[#333] rounded-lg px-3 py-2.5 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8] resize-none" />
              </div>
              <div className="md:col-span-2 flex gap-3">
                <button type="submit" disabled={saving}
                  className="px-5 py-2 bg-[#1D4ED8] hover:bg-blue-500 text-white text-sm font-body font-semibold rounded-lg transition-colors disabled:opacity-50">
                  {saving ? 'Saving...' : editingId ? 'Update Term' : 'Add Term'}
                </button>
                <button type="button" onClick={() => { setShowAddForm(false); setEditingId(null); setForm(EMPTY_FORM); }}
                  className="px-4 py-2 bg-[#FFFFFF] border border-[#333] text-[#888] hover:text-white text-sm font-body rounded-lg transition-colors">
                  Cancel
                </button>
              </div>
            </form>
          </div>
        )}

        {/* Filters */}
        <div className="mb-4 flex flex-wrap gap-3">
          <input type="text" value={searchTerm} onChange={e => setSearchTerm(e.target.value)} placeholder="Search terms..."
            className="bg-[#111] border border-[#DCE6F2] rounded-lg px-3 py-2 text-white text-sm font-body focus:outline-none focus:border-[#1D4ED8] w-48" />
          <select value={filterBanLevel} onChange={e => setFilterBanLevel(e.target.value)}
            className="bg-[#111] border border-[#DCE6F2] rounded-lg px-3 py-2 text-[#888] text-sm font-body focus:outline-none focus:border-[#1D4ED8]">
            <option value="">All Ban Levels</option>
            <option value="soft">Soft Ban</option>
            <option value="hard">Hard Ban</option>
          </select>
          <select value={filterSiteScope} onChange={e => setFilterSiteScope(e.target.value)}
            className="bg-[#111] border border-[#DCE6F2] rounded-lg px-3 py-2 text-[#888] text-sm font-body focus:outline-none focus:border-[#1D4ED8]">
            <option value="">All Sites</option>
            <option value="avbeat">AV Beat</option>
            <option value="avbeat">AV Beat</option>
            <option value="both">Both</option>
          </select>
          <select value={filterActive} onChange={e => setFilterActive(e.target.value)}
            className="bg-[#111] border border-[#DCE6F2] rounded-lg px-3 py-2 text-[#888] text-sm font-body focus:outline-none focus:border-[#1D4ED8]">
            <option value="">All Status</option>
            <option value="true">Active</option>
            <option value="false">Inactive</option>
          </select>
        </div>

        {/* Terms Table */}
        <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
          <div className="px-5 py-4 border-b border-[#FFFFFF] flex items-center justify-between">
            <h2 className="text-sm font-display font-bold text-white">Banned Terms ({terms.length})</h2>
          </div>
          {terms.length === 0 ? (
            <div className="px-5 py-12 text-center">
              <p className="text-[#555] text-sm font-body">No banned terms found. Add your first term above.</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-[#FFFFFF]">
                    {['Term', 'Ban Level', 'Site Scope', 'Status', 'Date Added', 'Added By', 'Notes', 'Actions'].map(h => (
                      <th key={h} className="px-4 py-3 text-left text-xs font-body font-bold text-[#555] uppercase tracking-wider">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#FFFFFF]">
                  {terms.map(term => (
                    <tr key={term.id} className={`hover:bg-[#F8FAFC] transition-colors ${!term.is_active ? 'opacity-50' : ''}`}>
                      <td className="px-4 py-3">
                        <span className="text-sm font-body font-semibold text-white">{term.term}</span>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-body font-bold ${
                          term.ban_level === 'hard' ? 'bg-red-500/10 text-red-400' : 'bg-yellow-500/10 text-yellow-400'
                        }`}>
                          {term.ban_level === 'hard' ? 'Hard Ban' : 'Soft Ban'}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <span className="text-xs text-[#888] font-body capitalize">{term.site_scope === 'both' ? 'Both Sites' : term.site_scope === 'avbeat' ? 'AV Beat' : 'AV Beat'}</span>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-body ${term.is_active ? 'bg-green-500/10 text-green-400' : 'bg-[#FFFFFF] text-[#555]'}`}>
                          {term.is_active ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-xs text-[#555] font-body">{new Date(term.created_at).toLocaleDateString()}</td>
                      <td className="px-4 py-3 text-xs text-[#555] font-body">{term.added_by_profile?.full_name || '—'}</td>
                      <td className="px-4 py-3 text-xs text-[#555] font-body max-w-xs truncate">{term.notes || '—'}</td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <button onClick={() => handleEdit(term)} className="text-xs text-[#1D4ED8] hover:text-blue-300 font-body transition-colors">Edit</button>
                          <button onClick={() => handleDeactivate(term.id, term.is_active)} disabled={actionLoading === term.id}
                            className="text-xs text-[#888] hover:text-white font-body transition-colors disabled:opacity-50">
                            {term.is_active ? 'Deactivate' : 'Reactivate'}
                          </button>
                          <button onClick={() => handleDelete(term.id)} disabled={actionLoading === term.id}
                            className="text-xs text-red-500 hover:text-red-400 font-body transition-colors disabled:opacity-50">Delete</button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Legend */}
        <div className="mt-6 bg-[#111] border border-[#DCE6F2] rounded-lg p-5">
          <h3 className="text-xs font-body font-bold text-[#555] uppercase tracking-widest mb-3">Ban Level Reference</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <div className="flex items-center gap-2 mb-1">
                <span className="text-xs px-2 py-0.5 rounded-full bg-yellow-500/10 text-yellow-400 font-bold">Soft Ban</span>
              </div>
              <p className="text-xs text-[#555] font-body">Post is allowed through. Tagged internally as "banned-term-flagged". Editor sees a red flag icon and internal note. Contributor sees normal "Pending Review" status — no indication of flagging.</p>
            </div>
            <div>
              <div className="flex items-center gap-2 mb-1">
                <span className="text-xs px-2 py-0.5 rounded-full bg-red-500/10 text-red-400 font-bold">Hard Ban</span>
              </div>
              <p className="text-xs text-[#555] font-body">Submission is blocked. Post saved as draft automatically. Contributor sees only: "This post could not be submitted. Please contact the editorial team at editor@avbeat.com for assistance." Admin receives email notification.</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
