'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import OverviewTab from './components/OverviewTab';
import InvoicesTab from './components/InvoicesTab';
import ClientsTab from './components/ClientsTab';
import PaymentsTab from './components/PaymentsTab';
import ReportsTab from './components/ReportsTab';
import BillingSettingsTab from './components/BillingSettingsTab';

type Tab = 'overview' | 'invoices' | 'clients' | 'payments' | 'reports' | 'settings';
type Company = { id: string; name: string; llc_entity: string; invoice_prefix: string };

export default function BillingDashboard() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<Tab>('overview');
  const [selectedCompany, setSelectedCompany] = useState<'rmp' | 'jtr'>('rmp');
  const [companies, setCompanies] = useState<Company[]>([]);
  const [billingMode, setBillingMode] = useState<'mooninvoice' | 'native'>('mooninvoice');
  const [isAdmin, setIsAdmin] = useState(false);
  const [authChecked, setAuthChecked] = useState(false);

  useEffect(() => {
    if (loading) return;
    if (!user) { router.replace('/'); return; }

    // Check admin role
    fetch('/api/billing/settings')
      .then(r => {
        if (r.status === 404) { router.replace('/'); return null; }
        return r.json();
      })
      .then(data => {
        if (!data) return;
        setIsAdmin(true);
        setCompanies(data.companies || []);
        setBillingMode(data.settings?.billing_mode || 'mooninvoice');
        setAuthChecked(true);
      })
      .catch(() => { router.replace('/'); });
  }, [user, loading, router]);

  const getCompanyId = useCallback(() => {
    return companies.find(c => c.llc_entity === selectedCompany.toUpperCase())?.id;
  }, [companies, selectedCompany]);

  if (loading || !authChecked) {
    return (
      <div className="min-h-screen bg-gray-950 flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  if (!isAdmin) return null;

  const tabs: { id: Tab; label: string }[] = [
    { id: 'overview', label: 'Overview' },
    { id: 'invoices', label: 'Invoices' },
    { id: 'clients', label: 'Clients' },
    { id: 'payments', label: 'Payments' },
    { id: 'reports', label: 'Reports' },
    { id: 'settings', label: 'Settings' },
  ];

  const rmpCompany = companies.find(c => c.llc_entity === 'RMP');
  const jtrCompany = companies.find(c => c.llc_entity === 'JTR');

  return (
    <div className="min-h-screen bg-gray-950 text-gray-100">
      {/* Header */}
      <div className="border-b border-gray-800 bg-gray-900">
        <div className="max-w-screen-xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between flex-wrap gap-4">
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
                <svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 11h.01M12 11h.01M15 11h.01M4 19h16a2 2 0 002-2V7a2 2 0 00-2-2H4a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
              </div>
              <div>
                <h1 className="text-lg font-bold text-white">Unified Billing</h1>
                <p className="text-xs text-gray-400">Ryan Salazar — Admin Only</p>
              </div>
            </div>

            {/* Company Switcher */}
            <div className="flex items-center gap-2 bg-gray-800 rounded-lg p-1">
              <button
                onClick={() => setSelectedCompany('rmp')}
                className={`px-4 py-2 rounded-md text-sm font-medium transition-all ${
                  selectedCompany === 'rmp' ?'bg-blue-600 text-white shadow' :'text-gray-400 hover:text-white'
                }`}
              >
                Relevant Media Properties
              </button>
            </div>

            {/* Data Source Indicator */}
            <div className="flex items-center gap-2">
              <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${
                billingMode === 'mooninvoice' ?'bg-blue-900/50 text-blue-300 border border-blue-700' :'bg-green-900/50 text-green-300 border border-green-700'
              }`}>
                <span className={`w-1.5 h-1.5 rounded-full ${billingMode === 'mooninvoice' ? 'bg-blue-400' : 'bg-green-400'}`} />
                {billingMode === 'mooninvoice' ? 'Data: MoonInvoice (live)' : 'Data: Native (self-hosted)'}
              </span>
            </div>
          </div>

          {/* Tabs */}
          <div className="flex gap-1 mt-4 border-b border-gray-800 -mb-px">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-400' :'border-transparent text-gray-400 hover:text-gray-200'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Tab Content */}
      <div className="max-w-screen-xl mx-auto px-6 py-6">
        {activeTab === 'overview' && (
          <OverviewTab companyId={getCompanyId()} selectedCompany={selectedCompany} />
        )}
        {activeTab === 'invoices' && (
          <InvoicesTab companyId={getCompanyId()} selectedCompany={selectedCompany} companies={companies} />
        )}
        {activeTab === 'clients' && (
          <ClientsTab companyId={getCompanyId()} selectedCompany={selectedCompany} companies={companies} />
        )}
        {activeTab === 'payments' && (
          <PaymentsTab companyId={getCompanyId()} selectedCompany={selectedCompany} />
        )}
        {activeTab === 'reports' && (
          <ReportsTab companyId={getCompanyId()} selectedCompany={selectedCompany} companies={companies} />
        )}
        {activeTab === 'settings' && (
          <BillingSettingsTab
            companies={companies}
            billingMode={billingMode}
            onModeChange={setBillingMode}
          />
        )}
      </div>
    </div>
  );
}
