'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 FLIGHT_COLORS: Record<string, string> = {
  active: 'bg-green-400/10 text-green-400',
  scheduled: 'bg-blue-400/10 text-blue-400',
  paused: 'bg-gray-600/20 text-gray-400',
  expired: 'bg-red-400/10 text-red-400',
  cancelled: 'bg-[#FFFFFF] text-[#555]',
};

export default function AdOpsIOsPage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [ios, setIos] = useState<any[]>([]);
  const [clients, setClients] = useState<any[]>([]);
  const [staff, setStaff] = useState<any[]>([]);
  const [products, setProducts] = useState<any[]>([]);
  const [loadingData, setLoadingData] = useState(true);
  const [filterStatus, setFilterStatus] = useState('');
  const [filterSite, setFilterSite] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({
    existing_io_id: '', client_id: '', product_id: '', staff_id: '', order_id: '',
    is_comp: false, comp_reason: '', is_paid: false, flight_status: 'scheduled',
    start_date: '', end_date: '', auto_deactivate: true, notes: '',
    banner_image_url: '', click_through_url: '', alt_text: '',
    email_html_url: '', email_scheduled_date: '', email_list_segment: '',
    page_url: '', newsletter_issue_date: '',
  });

  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 (filterStatus) params.set('status', filterStatus);
    if (filterSite) params.set('site', filterSite);
    const [iosR, clientsR, staffR] = await Promise.all([
      fetch(`/api/adops/rmp/ios?${params}`),
      fetch('/api/accounting/clients?status=all'),
      fetch('/api/accounting/staff'),
    ]);
    const [id, cd, sd] = await Promise.all([iosR.json(), clientsR.json(), staffR.json()]);
    setIos(id.ios ?? []);
    setClients(cd.clients ?? []);
    setStaff(sd.staff ?? []);
    setLoadingData(false);
  }, [filterStatus, filterSite]);

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

  useEffect(() => {
    if (!form.product_id) return;
    // product already selected — no need to re-fetch
  }, [form.product_id]);

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    await fetch('/api/adops/rmp/ios', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) });
    setSaving(false);
    setShowForm(false);
    load();
  }

  async function updateStatus(id: string, status: string, reason?: string) {
    await fetch(`/api/adops/rmp/ios/${id}/status`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ flight_status: status, reactivation_reason: reason }) });
    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;

  const selectedProduct = products.find((p: any) => p.id === form.product_id);
  const isEmailProduct = selectedProduct?.product_type?.includes('email') || selectedProduct?.product_type?.includes('newsletter');
  const isAdvertorial = selectedProduct?.product_type === 'featured_advertorial';

  return (
    <div className="min-h-screen bg-[#0a0a0a] text-white p-6">
      <div className="max-w-7xl mx-auto space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-bold">Insertion Orders</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">+ New IO Extension</button>
        </div>

        <div className="flex gap-2 flex-wrap">
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)} className="px-2 py-1 bg-[#111] border border-[#DCE6F2] rounded text-xs text-[#888] focus:outline-none">
            <option value="">All Statuses</option>
            {['scheduled','active','paused','expired','cancelled'].map(s => <option key={s} value={s}>{s}</option>)}
          </select>
          <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>
            {['avbeat','broadcastbeat','backlotbeat','broadcastengineering'].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 IO Extension</h3>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
              <div>
                <label className="text-xs text-[#888] block mb-1">Existing IO ID *</label>
                <input required value={form.existing_io_id} onChange={e => setForm(p => ({ ...p, existing_io_id: 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">Client</label>
                <select value={form.client_id} onChange={e => setForm(p => ({ ...p, client_id: 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>
                  {clients.map((c: any) => <option key={c.id} value={c.id}>{c.company_name}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Salesperson</label>
                <select value={form.staff_id} onChange={e => setForm(p => ({ ...p, staff_id: 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="">None</option>
                  {staff.map((s: any) => <option key={s.id} value={s.id}>{s.full_name}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Start Date *</label>
                <input type="date" required value={form.start_date} onChange={e => setForm(p => ({ ...p, start_date: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none" />
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">End Date</label>
                <input type="date" value={form.end_date} onChange={e => setForm(p => ({ ...p, end_date: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none" />
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Flight Status</label>
                <select value={form.flight_status} onChange={e => setForm(p => ({ ...p, flight_status: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none">
                  {['scheduled','active','paused'].map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Banner Image URL</label>
                <input value={form.banner_image_url} onChange={e => setForm(p => ({ ...p, banner_image_url: 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">Click-Through URL</label>
                <input value={form.click_through_url} onChange={e => setForm(p => ({ ...p, click_through_url: 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="flex items-center gap-3 pt-4">
                <label className="flex items-center gap-2 text-xs text-[#888] cursor-pointer">
                  <input type="checkbox" checked={form.is_comp} onChange={e => setForm(p => ({ ...p, is_comp: e.target.checked }))} className="rounded" />
                  Is Comp?
                </label>
                <label className="flex items-center gap-2 text-xs text-[#888] cursor-pointer">
                  <input type="checkbox" checked={form.auto_deactivate} onChange={e => setForm(p => ({ ...p, auto_deactivate: e.target.checked }))} className="rounded" />
                  Auto-deactivate
                </label>
              </div>
              {form.is_comp && (
                <div>
                  <label className="text-xs text-[#888] block mb-1">Comp Reason</label>
                  <input value={form.comp_reason} onChange={e => setForm(p => ({ ...p, comp_reason: 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>
              )}
              {isEmailProduct && (
                <>
                  <div>
                    <label className="text-xs text-[#888] block mb-1">Email HTML URL</label>
                    <input value={form.email_html_url} onChange={e => setForm(p => ({ ...p, email_html_url: 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">Scheduled Send Date</label>
                    <input type="date" value={form.email_scheduled_date} onChange={e => setForm(p => ({ ...p, email_scheduled_date: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none" />
                  </div>
                  <div>
                    <label className="text-xs text-[#888] block mb-1">List Segment</label>
                    <input value={form.email_list_segment} onChange={e => setForm(p => ({ ...p, email_list_segment: 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>
                </>
              )}
              {isAdvertorial && (
                <div>
                  <label className="text-xs text-[#888] block mb-1">Page URL (permanent)</label>
                  <input value={form.page_url} onChange={e => setForm(p => ({ ...p, page_url: 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">Notes</label>
                <textarea value={form.notes} onChange={e => setForm(p => ({ ...p, notes: e.target.value }))} rows={2} 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…' : 'Create IO Extension'}</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]">
                {['IO ID','Client','Product','Start','End','Status','Comp','Paid','Actions'].map(h => (
                  <th key={h} className="px-3 py-2 text-left text-xs text-[#555] font-medium whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {loadingData ? (
                <tr><td colSpan={9} className="px-4 py-8 text-center text-[#555] text-xs">Loading…</td></tr>
              ) : ios.length === 0 ? (
                <tr><td colSpan={9} className="px-4 py-8 text-center text-[#555] text-xs">No IO extensions found</td></tr>
              ) : ios.map((io: any) => (
                <tr key={io.id} className="border-b border-[#FFFFFF] hover:bg-[#FFFFFF]">
                  <td className="px-3 py-2 text-[#1D4ED8] font-mono text-xs">{io.existing_io_id}</td>
                  <td className="px-3 py-2 text-white text-xs">{io.rmp_clients?.company_name ?? '—'}</td>
                  <td className="px-3 py-2 text-[#ccc] text-xs">{io.rmp_products?.name ?? '—'}</td>
                  <td className="px-3 py-2 text-[#888] text-xs">{io.start_date}</td>
                  <td className="px-3 py-2 text-[#888] text-xs">{io.end_date ?? '∞'}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs ${FLIGHT_COLORS[io.flight_status] ?? FLIGHT_COLORS.cancelled}`}>{io.flight_status}</span>
                  </td>
                  <td className="px-3 py-2">
                    {io.is_comp && <span className="px-2 py-0.5 rounded-full text-xs bg-blue-400/10 text-blue-400">Comp</span>}
                  </td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs ${io.is_paid ? 'bg-green-400/10 text-green-400' : 'bg-yellow-400/10 text-yellow-400'}`}>{io.is_paid ? 'Paid' : 'Unpaid'}</span>
                  </td>
                  <td className="px-3 py-2 flex gap-2">
                    <Link href={`/admin/adops/ios/${io.id}`} className="text-xs text-[#1D4ED8] hover:underline">View</Link>
                    {io.flight_status === 'expired' && (
                      <button onClick={() => { const r = prompt('Reactivation reason?'); if (r) updateStatus(io.id, 'active', r); }} className="text-xs text-green-400 hover:underline">Reactivate</button>
                    )}
                    {io.flight_status === 'active' && (
                      <button onClick={() => updateStatus(io.id, 'paused')} className="text-xs text-yellow-400 hover:underline">Pause</button>
                    )}
                    {io.flight_status === 'paused' && (
                      <button onClick={() => updateStatus(io.id, 'active')} className="text-xs text-green-400 hover:underline">Resume</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
