'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 border-green-400/20',
  scheduled: 'bg-blue-400/10 text-blue-400 border-blue-400/20',
  paused: 'bg-gray-600/20 text-gray-400 border-gray-600/20',
  expired: 'bg-red-400/10 text-red-400 border-red-400/20',
  cancelled: 'bg-[#1a1a1a] text-[#555] border-[#252525]',
};

export default function AdOpsDashboardPage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [stats, setStats] = useState<any>(null);
  const [flights, setFlights] = useState<any[]>([]);
  const [emailSchedule, setEmailSchedule] = useState<any[]>([]);
  const [loadingData, setLoadingData] = useState(true);
  const [filterSite, setFilterSite] = useState('');
  const [filterStatus, setFilterStatus] = useState('');

  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);
    if (filterStatus) params.set('status', filterStatus);
    const [statsR, flightsR, emailR] = await Promise.all([
      fetch('/api/adops/rmp/stats'),
      fetch(`/api/adops/rmp/flights?${params}`),
      fetch('/api/adops/rmp/email-schedule'),
    ]);
    const [sd, fd, ed] = await Promise.all([statsR.json(), flightsR.json(), emailR.json()]);
    setStats(sd);
    setFlights(fd.flights ?? []);
    setEmailSchedule(ed.schedule ?? []);
    setLoadingData(false);
  }, [filterSite, filterStatus]);

  useEffect(() => { if (user) load(); }, [user, 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-[#ffb800] 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-7xl mx-auto space-y-6">
        <div>
          <h1 className="text-2xl font-bold">Ad Operations</h1>
          <p className="text-[#888] text-sm mt-1">Relevant Media Properties, LLC</p>
        </div>

        {/* Stat Cards */}
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
          {[
            { label: 'Active Flights', key: 'active', color: 'text-green-400' },
            { label: 'Expiring 30d', key: 'expiring_30d', color: 'text-yellow-400' },
            { label: 'Expired This Month', key: 'expired_month', color: 'text-red-400' },
            { label: 'Comped Running', key: 'comped', color: 'text-blue-400' },
            { label: 'Unpaid Active', key: 'unpaid_active', color: 'text-orange-400' },
            { label: 'Email Blasts Scheduled', key: 'email_scheduled', color: 'text-purple-400' },
          ].map(c => (
            <div key={c.key} className="bg-[#111] border border-[#252525] rounded-lg p-4">
              <p className={`text-2xl font-bold ${c.color}`}>{stats?.[c.key] ?? 0}</p>
              <p className="text-xs text-[#888] mt-1">{c.label}</p>
            </div>
          ))}
        </div>

        {/* Filters */}
        <div className="flex gap-2 flex-wrap">
          <select value={filterSite} onChange={e => setFilterSite(e.target.value)} className="px-2 py-1 bg-[#111] border border-[#252525] rounded text-xs text-[#888] focus:outline-none">
            <option value="">All Sites</option>
            {['avbeat','avbeat','backlotbeat','broadcastengineering'].map(s => <option key={s} value={s}>{s}</option>)}
          </select>
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)} className="px-2 py-1 bg-[#111] border border-[#252525] rounded text-xs text-[#888] focus:outline-none">
            <option value="">All Statuses</option>
            {['active','scheduled','paused','expired','cancelled'].map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>

        {/* Active Flights Table */}
        <div className="bg-[#111] border border-[#252525] rounded-lg overflow-x-auto">
          <div className="px-4 py-3 border-b border-[#252525] flex items-center justify-between">
            <h2 className="text-sm font-semibold">Active Flights</h2>
            <Link href="/admin/adops/ios" className="text-xs text-[#ffb800] hover:underline">View All IOs →</Link>
          </div>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-[#1a1a1a]">
                {['Client','Product','Site','Start','End','Status','Salesperson','Paid',''].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>
              ) : flights.length === 0 ? (
                <tr><td colSpan={9} className="px-4 py-8 text-center text-[#555] text-xs">No flights found</td></tr>
              ) : flights.map((f: any) => (
                <tr key={f.id} className="border-b border-[#1a1a1a] hover:bg-[#161616]">
                  <td className="px-3 py-2 text-white text-xs">{f.rmp_clients?.company_name ?? '—'}</td>
                  <td className="px-3 py-2 text-[#ccc] text-xs">{f.rmp_products?.name ?? '—'}</td>
                  <td className="px-3 py-2 text-[#888] text-xs capitalize">{f.rmp_orders?.site ?? '—'}</td>
                  <td className="px-3 py-2 text-[#888] text-xs">{f.start_date}</td>
                  <td className="px-3 py-2 text-[#888] text-xs">{f.end_date ?? '∞'}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs border ${FLIGHT_COLORS[f.flight_status] ?? FLIGHT_COLORS.cancelled}`}>{f.flight_status}</span>
                  </td>
                  <td className="px-3 py-2 text-[#ccc] text-xs">{f.rmp_sales_staff?.full_name ?? '—'}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs ${f.is_paid ? 'bg-green-400/10 text-green-400' : f.is_comp ? 'bg-blue-400/10 text-blue-400' : 'bg-yellow-400/10 text-yellow-400'}`}>{f.is_comp ? 'Comp' : f.is_paid ? 'Paid' : 'Unpaid'}</span>
                  </td>
                  <td className="px-3 py-2">
                    <Link href={`/admin/adops/ios/${f.id}`} className="text-xs text-[#ffb800] hover:underline">View</Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Email Schedule */}
        <div className="bg-[#111] border border-[#252525] rounded-lg overflow-hidden">
          <div className="px-4 py-3 border-b border-[#252525]">
            <h2 className="text-sm font-semibold">Email Distribution Schedule</h2>
          </div>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-[#1a1a1a]">
                {['Client','Type','Site','Scheduled Date','Status',''].map(h => (
                  <th key={h} className="px-3 py-2 text-left text-xs text-[#555] font-medium">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {emailSchedule.length === 0 ? (
                <tr><td colSpan={6} className="px-4 py-6 text-center text-[#555] text-xs">No email blasts scheduled</td></tr>
              ) : emailSchedule.map((e: any) => (
                <tr key={e.id} className="border-b border-[#1a1a1a] hover:bg-[#161616]">
                  <td className="px-3 py-2 text-white text-xs">{e.rmp_clients?.company_name ?? '—'}</td>
                  <td className="px-3 py-2 text-[#888] text-xs">{e.rmp_products?.product_type?.replace(/_/g, ' ')}</td>
                  <td className="px-3 py-2 text-[#888] text-xs capitalize">{e.rmp_orders?.site ?? '—'}</td>
                  <td className="px-3 py-2 text-[#ccc] text-xs">{e.email_scheduled_date ?? '—'}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs ${e.email_sent_at ? 'bg-green-400/10 text-green-400' : 'bg-blue-400/10 text-blue-400'}`}>{e.email_sent_at ? 'Sent' : 'Pending'}</span>
                  </td>
                  <td className="px-3 py-2">
                    {e.email_html_url && <a href={e.email_html_url} target="_blank" rel="noopener noreferrer" className="text-xs text-[#ffb800] hover:underline">Preview</a>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
