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

function fmt(cents: number) { return '$' + (cents / 100).toLocaleString('en-US', { minimumFractionDigits: 2 }); }

const SITES = ['avbeat','avbeat','backlotbeat','broadcastengineering'];

export default function ReportsPage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [report, setReport] = useState<any>(null);
  const [loadingData, setLoadingData] = useState(false);
  const [startDate, setStartDate] = useState(`${new Date().getFullYear()}-01-01`);
  const [endDate, setEndDate] = useState(new Date().toISOString().split('T')[0]);

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

  async function loadReport() {
    setLoadingData(true);
    const r = await fetch(`/api/accounting/reports?start=${startDate}&end=${endDate}`);
    const d = await r.json();
    setReport(d);
    setLoadingData(false);
  }

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

  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">P&L Reports</h1>
            <Link href="/admin/accounting" className="text-xs text-[#555] hover:text-[#888]">← Accounting</Link>
          </div>
          <div className="flex gap-2 items-center">
            <input type="date" value={startDate} onChange={e => setStartDate(e.target.value)} className="px-2 py-1 bg-[#111] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none" />
            <span className="text-[#555] text-xs">to</span>
            <input type="date" value={endDate} onChange={e => setEndDate(e.target.value)} className="px-2 py-1 bg-[#111] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none" />
            <button onClick={loadReport} disabled={loadingData} className="px-3 py-1.5 bg-[#1D4ED8] rounded text-xs font-medium hover:bg-blue-500 disabled:opacity-50">Run Report</button>
          </div>
        </div>

        {loadingData ? (
          <div className="flex items-center justify-center py-20"><div className="w-8 h-8 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" /></div>
        ) : report ? (
          <div className="space-y-4">
            {/* P&L Summary */}
            <div className="grid grid-cols-3 gap-3">
              <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-4">
                <p className="text-xs text-[#555]">Total Revenue</p>
                <p className="text-2xl font-bold text-green-400 mt-1">{fmt(report.total_revenue_cents ?? 0)}</p>
              </div>
              <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-4">
                <p className="text-xs text-[#555]">Total Expenses</p>
                <p className="text-2xl font-bold text-red-400 mt-1">{fmt(report.total_expenses_cents ?? 0)}</p>
              </div>
              <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-4">
                <p className="text-xs text-[#555]">Net Profit</p>
                <p className={`text-2xl font-bold mt-1 ${(report.net_profit_cents ?? 0) >= 0 ? 'text-blue-400' : 'text-red-400'}`}>{fmt(report.net_profit_cents ?? 0)}</p>
              </div>
            </div>

            {/* Revenue by Site */}
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
              <div className="px-4 py-3 border-b border-[#DCE6F2]"><h2 className="text-sm font-semibold">Revenue by Site</h2></div>
              <table className="w-full text-sm">
                <thead><tr className="border-b border-[#FFFFFF]">{['Site','Revenue'].map(h => <th key={h} className="px-4 py-2 text-left text-xs text-[#555]">{h}</th>)}</tr></thead>
                <tbody>
                  {(report.by_site ?? []).map((r: any) => (
                    <tr key={r.site} className="border-b border-[#FFFFFF]">
                      <td className="px-4 py-2 text-white text-xs capitalize">{r.site}</td>
                      <td className="px-4 py-2 text-green-400 text-xs">{fmt(r.revenue_cents ?? 0)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Top Clients */}
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
              <div className="px-4 py-3 border-b border-[#DCE6F2]"><h2 className="text-sm font-semibold">Top 10 Clients</h2></div>
              <table className="w-full text-sm">
                <thead><tr className="border-b border-[#FFFFFF]">{['Client','Revenue'].map(h => <th key={h} className="px-4 py-2 text-left text-xs text-[#555]">{h}</th>)}</tr></thead>
                <tbody>
                  {(report.top_clients ?? []).map((c: any) => (
                    <tr key={c.id} className="border-b border-[#FFFFFF]">
                      <td className="px-4 py-2 text-white text-xs">{c.company_name}</td>
                      <td className="px-4 py-2 text-green-400 text-xs">{fmt(c.revenue_cents ?? 0)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Expenses by Category */}
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
              <div className="px-4 py-3 border-b border-[#DCE6F2]"><h2 className="text-sm font-semibold">Expenses by Category</h2></div>
              <table className="w-full text-sm">
                <thead><tr className="border-b border-[#FFFFFF]">{['Category','Amount'].map(h => <th key={h} className="px-4 py-2 text-left text-xs text-[#555]">{h}</th>)}</tr></thead>
                <tbody>
                  {(report.by_category ?? []).map((c: any) => (
                    <tr key={c.category} className="border-b border-[#FFFFFF]">
                      <td className="px-4 py-2 text-white text-xs">{c.category?.replace(/_/g, ' ')}</td>
                      <td className="px-4 py-2 text-red-400 text-xs">{fmt(c.amount_cents ?? 0)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        ) : null}
      </div>
    </div>
  );
}
