/**
 * Account Billing Page
 * Consolidated billing dashboard with invoices, payments, and credit balance
 */

import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import {
  CreditCard,
  Download,
  AlertCircle,
  Loader2,
  FileText,
  CheckCircle,
  XCircle,
  Clock,
  DollarSign,
  TrendingUp,
} from 'lucide-react';
import {
  getInvoices,
  getPayments,
  getCreditBalance,
  downloadInvoicePDF,
  type Invoice,
  type Payment,
  type CreditBalance,
} from '../../services/billing.api';
import { Card } from '../../components/ui/card';
import BillingRecentTransactions from '../../components/billing/BillingRecentTransactions';

type TabType = 'overview' | 'invoices' | 'payments';

export default function AccountBillingPage() {
  const [activeTab, setActiveTab] = useState<TabType>('overview');
  const [creditBalance, setCreditBalance] = useState<CreditBalance | null>(null);
  const [invoices, setInvoices] = useState<Invoice[]>([]);
  const [payments, setPayments] = useState<Payment[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      setLoading(true);
      const [balanceRes, invoicesRes, paymentsRes] = await Promise.all([
        getCreditBalance(),
        getInvoices(),
        getPayments(),
      ]);

      setCreditBalance(balanceRes);
      setInvoices(invoicesRes.results);
      setPayments(paymentsRes.results);
    } catch (err: any) {
      setError(err.message || 'Failed to load billing data');
      console.error('Billing data load error:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleDownloadInvoice = async (invoiceId: number, invoiceNumber: string) => {
    try {
      const blob = await downloadInvoicePDF(invoiceId);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `invoice-${invoiceNumber}.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (err) {
      alert('Failed to download invoice');
    }
  };

  const getStatusBadge = (status: string) => {
    const styles: Record<string, { bg: string; text: string; icon: any }> = {
      paid: { bg: 'bg-green-100', text: 'text-green-800', icon: CheckCircle },
      pending: { bg: 'bg-yellow-100', text: 'text-yellow-800', icon: Clock },
      failed: { bg: 'bg-red-100', text: 'text-red-800', icon: XCircle },
      void: { bg: 'bg-gray-100', text: 'text-gray-800', icon: XCircle },
      completed: { bg: 'bg-green-100', text: 'text-green-800', icon: CheckCircle },
      pending_approval: { bg: 'bg-blue-100', text: 'text-blue-800', icon: Clock },
    };

    const style = styles[status] || styles.pending;
    const Icon = style.icon;

    return (
      <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${style.bg} ${style.text}`}>
        <Icon className="w-3 h-3" />
        {status.replace('_', ' ').toUpperCase()}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-6xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-3xl font-bold">Plans & Billing</h1>
            {/* Recent Transactions (moved from Credits & Billing overview) */}
            <div>
              <BillingRecentTransactions />
            </div>

            <p className="text-gray-600">Manage your subscription, credits, and billing</p>
          </div>
          <Link
            to="/account/credits/purchase"
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
          >
            <CreditCard className="w-4 h-4" />
            Purchase Credits
          </Link>
        </div>

        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6 flex items-start gap-2">
            <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
            <p className="text-red-800">{error}</p>
          </div>
        )}

        {/* Tabs */}
        <div className="border-b border-gray-200 mb-6">
          <nav className="flex gap-8">
            {[
              { id: 'overview', label: 'Overview' },
              { id: 'invoices', label: 'Invoices' },
              { id: 'payments', label: 'Payments' },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as TabType)}
                className={`py-3 border-b-2 font-medium transition-colors ${
                  activeTab === tab.id
                    ? 'border-blue-600 text-blue-600'
                    : 'border-transparent text-gray-600 hover:text-gray-900'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </nav>
        </div>

        {/* Overview Tab */}
        {activeTab === 'overview' && creditBalance && (
          <div className="space-y-6">
            {/* Stats Cards */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <Card className="p-6">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="text-sm font-medium text-gray-600 dark:text-gray-400">Current Balance</h3>
                  <CreditCard className="w-5 h-5 text-blue-600" />
                </div>
                <div className="text-3xl font-bold text-gray-900 dark:text-white">
                  {creditBalance?.credits?.toLocaleString() || '0'}
                </div>
                <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">Available credits</p>
              </Card>

              <Card className="p-6">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="text-sm font-medium text-gray-600 dark:text-gray-400">Monthly Allocation</h3>
                  <TrendingUp className="w-5 h-5 text-green-600" />
                </div>
                <div className="text-3xl font-bold text-gray-900 dark:text-white">
                  {creditBalance?.plan_credits_per_month?.toLocaleString() || '0'}
                </div>
                <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">Credits per month</p>
              </Card>

              <Card className="p-6">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="text-sm font-medium text-gray-600 dark:text-gray-400">Used This Month</h3>
                  <DollarSign className="w-5 h-5 text-red-600" />
                </div>
                <div className="text-3xl font-bold text-red-600 dark:text-red-400">
                  {creditBalance?.credits_used_this_month?.toLocaleString() || '0'}
                </div>
                <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">Credits consumed</p>
              </Card>
            </div>

            {/* Quick Actions */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <Card className="p-6">
                <h3 className="text-lg font-semibold mb-4">Quick Actions</h3>
                <div className="space-y-2">
                  <Link
                    to="/account/purchase-credits"
                    className="block w-full bg-blue-600 text-white text-center py-2 px-4 rounded hover:bg-blue-700 transition-colors"
                  >
                    Purchase Credits
                  </Link>
                  <Link
                    to="/account/usage"
                    className="block w-full bg-gray-100 text-gray-700 text-center py-2 px-4 rounded hover:bg-gray-200 transition-colors"
                  >
                    View Usage Analytics
                  </Link>
                </div>
              </Card>

              <Card className="p-6">
                <h3 className="text-lg font-semibold mb-4">Account Summary</h3>
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-gray-600">Remaining Credits:</span>
                    <span className="font-semibold">{creditBalance?.credits_remaining?.toLocaleString() || '0'}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">Total Invoices:</span>
                    <span className="font-semibold">{invoices.length}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">Paid Invoices:</span>
                    <span className="font-semibold text-green-600">
                      {invoices.filter(inv => inv.status === 'paid').length}
                    </span>
                  </div>
                </div>
              </Card>
            </div>
          </div>
        )}

        {/* Invoices Tab */}
        {activeTab === 'invoices' && (
          <div className="bg-white rounded-lg shadow overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50 border-b">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Invoice
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Date
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Amount
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Status
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {invoices.length === 0 ? (
                    <tr>
                      <td colSpan={5} className="px-6 py-8 text-center text-gray-500">
                        <FileText className="w-12 h-12 mx-auto mb-2 text-gray-400" />
                        No invoices yet
                      </td>
                    </tr>
                  ) : (
                    invoices.map((invoice) => (
                      <tr key={invoice.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4">
                          <div className="font-medium">{invoice.invoice_number}</div>
                          {invoice.line_items[0] && (
                            <div className="text-sm text-gray-500">
                              {invoice.line_items[0].description}
                            </div>
                          )}
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-600">
                          {new Date(invoice.created_at).toLocaleDateString()}
                        </td>
                        <td className="px-6 py-4 font-semibold">
                          ${invoice.total_amount}
                        </td>
                        <td className="px-6 py-4">{getStatusBadge(invoice.status)}</td>
                        <td className="px-6 py-4 text-right">
                          <button
                            onClick={() =>
                              handleDownloadInvoice(invoice.id, invoice.invoice_number)
                            }
                            className="text-blue-600 hover:text-blue-700 flex items-center gap-1 ml-auto"
                          >
                            <Download className="w-4 h-4" />
                            Download
                          </button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Payments Tab */}
        {activeTab === 'payments' && (
          <div className="bg-white rounded-lg shadow overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50 border-b">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Date
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Method
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Reference
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Amount
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Status
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {payments.length === 0 ? (
                    <tr>
                      <td colSpan={5} className="px-6 py-8 text-center text-gray-500">
                        <CreditCard className="w-12 h-12 mx-auto mb-2 text-gray-400" />
                        No payments yet
                      </td>
                    </tr>
                  ) : (
                    payments.map((payment) => (
                      <tr key={payment.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 text-sm text-gray-600">
                          {new Date(payment.created_at).toLocaleDateString()}
                        </td>
                        <td className="px-6 py-4">
                          <div className="font-medium capitalize">
                            {payment.payment_method.replace('_', ' ')}
                          </div>
                        </td>
                        <td className="px-6 py-4 text-sm font-mono text-gray-600">
                          {payment.transaction_reference || '-'}
                        </td>
                        <td className="px-6 py-4 font-semibold">
                          ${payment.amount}
                        </td>
                        <td className="px-6 py-4">{getStatusBadge(payment.status)}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
