'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 PRODUCT_TYPES = [
  'display_banner_300x250','display_banner_728x90','display_banner_300x600',
  'display_banner_970x250','newsletter_banner_600x100','dedicated_email_blast',
  'newsletter_sponsorship','featured_advertorial','featured_newsletter_story',
];

export default function AdOpsProductsPage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [products, setProducts] = useState<any[]>([]);
  const [loadingData, setLoadingData] = useState(true);
  const [filterSite, setFilterSite] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({ site: '', product_type: '', name: '', description: '', dimensions: '', duration_days: '', sort_order: '0' });

  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();
    if (filterSite) params.set('site', filterSite);
    const r = await fetch(`/api/accounting/products?${params}`);
    const d = await r.json();
    setProducts(d.products ?? []);
    setLoadingData(false);
  }, [filterSite]);

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

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    await fetch('/api/accounting/products', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...form, duration_days: form.duration_days ? parseInt(form.duration_days) : null, sort_order: parseInt(form.sort_order) }) });
    setSaving(false);
    setShowForm(false);
    load();
  }

  async function toggleActive(id: string, active: boolean) {
    await fetch(`/api/accounting/products/${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">Product Catalog</h1>
            <Link href="/admin/adops" className="text-xs text-[#555] hover:text-[#888]">← Ad Operations</Link>
          </div>
          <button onClick={() => setShowForm(true)} className="px-3 py-1.5 bg-[#1D4ED8] rounded text-xs font-medium hover:bg-blue-500">+ Add Product</button>
        </div>

        <div className="flex gap-2">
          <select value={filterSite} onChange={e => setFilterSite(e.target.value)} className="px-2 py-1 bg-[#111] border border-[#DCE6F2] rounded text-xs text-[#888] focus:outline-none">
            <option value="">All Sites</option>
            {SITES.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>

        {showForm && (
          <form onSubmit={handleCreate} className="bg-[#111] border border-[#DCE6F2] rounded-lg p-4 space-y-3">
            <h3 className="text-sm font-semibold">New Product</h3>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
              <div>
                <label className="text-xs text-[#888] block mb-1">Site *</label>
                <select required value={form.site} onChange={e => setForm(p => ({ ...p, site: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none">
                  <option value="">Select…</option>
                  {SITES.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Product Type *</label>
                <select required value={form.product_type} onChange={e => setForm(p => ({ ...p, product_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">
                  <option value="">Select…</option>
                  {PRODUCT_TYPES.map(t => <option key={t} value={t}>{t.replace(/_/g, ' ')}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Name *</label>
                <input required value={form.name} onChange={e => setForm(p => ({ ...p, name: 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">Dimensions</label>
                <input value={form.dimensions} onChange={e => setForm(p => ({ ...p, dimensions: e.target.value }))} placeholder="e.g. 300x250" 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">Duration (days)</label>
                <input type="number" value={form.duration_days} onChange={e => setForm(p => ({ ...p, duration_days: 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 className="col-span-2 md:col-span-3">
                <label className="text-xs text-[#888] block mb-1">Description</label>
                <input value={form.description} onChange={e => setForm(p => ({ ...p, description: 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 Product'}</button>
              <button type="button" onClick={() => setShowForm(false)} className="px-3 py-1.5 bg-[#FFFFFF] border border-[#DCE6F2] rounded text-xs text-[#888] hover:text-white">Cancel</button>
            </div>
          </form>
        )}

        <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]">
                {['Site','Type','Name','Dimensions','Duration','Active',''].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>
              ) : products.length === 0 ? (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-[#555] text-xs">No products found</td></tr>
              ) : products.map((p: any) => (
                <tr key={p.id} className={`border-b border-[#FFFFFF] hover:bg-[#FFFFFF] ${!p.active ? 'opacity-50' : ''}`}>
                  <td className="px-3 py-2 text-[#888] text-xs capitalize">{p.site}</td>
                  <td className="px-3 py-2 text-[#555] text-xs">{p.product_type?.replace(/_/g, ' ')}</td>
                  <td className="px-3 py-2 text-white text-xs">{p.name}</td>
                  <td className="px-3 py-2 text-[#888] text-xs">{p.dimensions ?? '—'}</td>
                  <td className="px-3 py-2 text-[#888] text-xs">{p.duration_days ? `${p.duration_days}d` : '—'}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs ${p.active ? 'bg-green-400/10 text-green-400' : 'bg-[#FFFFFF] text-[#555]'}`}>{p.active ? 'Active' : 'Inactive'}</span>
                  </td>
                  <td className="px-3 py-2">
                    <button onClick={() => toggleActive(p.id, p.active)} className="text-xs text-[#1D4ED8] hover:underline">{p.active ? 'Deactivate' : 'Activate'}</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
