import React, { useState, useMemo } from 'react';
import { 
  BookOpen, 
  Plus, 
  ArrowUpRight, 
  ArrowDownRight, 
  Wallet, 
  FileText, 
  PieChart, 
  Download,
  Calendar,
  Filter,
  Search,
  ChevronRight,
  ChevronDown,
  Info,
  DollarSign,
  Plane,
  Receipt
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { motion, AnimatePresence } from 'framer-motion';
import { useApp, Project, Expense } from '@/context/AppContext';
import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';

interface Account {
  id: string;
  name: string;
  type: 'Asset' | 'Liability' | 'Equity' | 'Revenue' | 'Expense';
  balance: number;
  code: string;
}

interface JournalEntry {
  id: string;
  date: string;
  description: string;
  reference?: string;
  debit: number;
  credit: number;
  account: string;
}

export function Bookkeeping() {
  const { projects, expenses, companySettings } = useApp();
  const [view, setView] = useState<'ledger' | 'accounts' | 'reports'>('ledger');
  const [reportType, setReportType] = useState<'pnl' | 'balance_sheet'>('pnl');
  const [searchQuery, setSearchQuery] = useState('');

  // Define Chart of Accounts
  const accounts = useMemo<Account[]>(() => {
    const baseAccounts: Account[] = [
      { id: '1000', code: '1000', name: 'Cash & Bank', type: 'Asset', balance: 0 },
      { id: '1100', code: '1100', name: 'Accounts Receivable', type: 'Asset', balance: 0 },
      { id: '2000', code: '2000', name: 'Accounts Payable', type: 'Liability', balance: 0 },
      { id: '2100', code: '2100', name: 'Tax Payable (VAT)', type: 'Liability', balance: 0 },
      { id: '3000', code: '3000', name: "Owner's Equity", type: 'Equity', balance: 0 },
      { id: '4000', code: '4000', name: 'Project Revenue', type: 'Revenue', balance: 0 },
      { id: '5000', code: '5000', name: 'Engineer Payouts', type: 'Expense', balance: 0 },
      { id: '5100', code: '5100', name: 'Operating Expenses', type: 'Expense', balance: 0 },
      { id: '5200', code: '5200', name: 'Travel & Materials', type: 'Expense', balance: 0 },
      { id: '5300', code: '5300', name: 'Tax Payments', type: 'Expense', balance: 0 },
      { id: '5400', code: '5400', name: 'Vendor Commissions', type: 'Expense', balance: 0 },
    ];

    // Simple conversion utility (in a real app, these would come from an API)
    const convertToUSD = (amount: number, currency?: string) => {
      if (!currency || currency === 'USD' || currency === '$') return amount;
      const rates: Record<string, number> = {
        'EUR': 1.08,
        'Euro': 1.08,
        '€': 1.08,
        'GBP': 1.25,
        '£': 1.25,
        'CAD': 0.74,
        'AED': 0.27,
        'SAR': 0.27
      };
      return amount * (rates[currency] || 1);
    };

    // Calculate balances based on projects and expenses
    projects.forEach(p => {
      const revenue = convertToUSD(p.clientTotalAmount || 0, p.currency);
      const taxAmount = convertToUSD(p.taxAmount || 0, p.currency);
      const netRevenue = revenue - taxAmount;
      const cost = convertToUSD(p.totalAmount || 0, p.currency);
      
      // Revenue (Net of Tax)
      baseAccounts.find(a => a.id === '4000')!.balance += netRevenue;
      
      // Tax Payable
      baseAccounts.find(a => a.id === '2100')!.balance += taxAmount;
      
      // Accounts Receivable (if unpaid)
      if (p.clientInvoiceStatus !== 'Paid') {
        baseAccounts.find(a => a.id === '1100')!.balance += revenue;
      } else {
        baseAccounts.find(a => a.id === '1000')!.balance += revenue;
      }

      // Engineer Cost
      baseAccounts.find(a => a.id === '5000')!.balance += cost;

      // Vendor Commissions
      let commissionsTotal = 0;
      if (p.commissions && p.commissions.length > 0) {
        commissionsTotal = p.commissions.reduce((acc, c) => acc + (c.amount || 0), 0);
      } else if (p.thirdPartyName) {
        const clientAmt = p.clientTotalAmount || p.totalAmount || 0;
        commissionsTotal = p.thirdPartyCommissionAmount || (clientAmt * ((p.thirdPartyCommissionRate || 0) / 100));
      }
      
      const convertedComm = convertToUSD(commissionsTotal, p.currency);
      if (convertedComm > 0) {
        baseAccounts.find(a => a.id === '5400')!.balance += convertedComm;
        if (p.thirdPartyStatus === 'Paid' || (p.commissions && p.commissions.every(c => c.status === 'Paid'))) {
          baseAccounts.find(a => a.id === '1000')!.balance -= convertedComm;
        } else {
          baseAccounts.find(a => a.id === '2000')!.balance += convertedComm;
        }
      }

      // Travel & Materials from Project (included in cost but tracked for cash flow)
      const travelAndMaterials = convertToUSD((p.travelCost || 0) + (p.materialCost || 0), p.currency);
      if (travelAndMaterials > 0) {
        baseAccounts.find(a => a.id === '5200')!.balance += travelAndMaterials;
      }
      
      // Accounts Payable (if unpaid)
      if (p.engineerInvoiceStatus !== 'Paid') {
        baseAccounts.find(a => a.id === '2000')!.balance += cost;
      } else {
        baseAccounts.find(a => a.id === '1000')!.balance -= cost;
      }
    });

    expenses.forEach(e => {
      if (e.status === 'Approved') {
        if (e.category === 'Tax Payment') {
          baseAccounts.find(a => a.id === '5300')!.balance += e.amount;
          baseAccounts.find(a => a.id === '2100')!.balance -= e.amount;
          baseAccounts.find(a => a.id === '1000')!.balance -= e.amount;
        } else if (e.category === 'Travel' || e.category === 'Materials' || e.category === 'Travel & Materials') {
          baseAccounts.find(a => a.id === '5200')!.balance += e.amount;
          baseAccounts.find(a => a.id === '1000')!.balance -= e.amount;
        } else {
          baseAccounts.find(a => a.id === '5100')!.balance += e.amount;
          baseAccounts.find(a => a.id === '1000')!.balance -= e.amount;
        }
      }
    });

    // Calculate Owner's Equity (Assets - Liabilities)
    const assets = baseAccounts.filter(a => a.type === 'Asset').reduce((sum, a) => sum + a.balance, 0);
    const liabilities = baseAccounts.filter(a => a.type === 'Liability').reduce((sum, a) => sum + a.balance, 0);
    const equityAccount = baseAccounts.find(a => a.id === '3000');
    if (equityAccount) {
      equityAccount.balance = assets - liabilities;
    }

    return baseAccounts;
  }, [projects, expenses]);

  // Calculate Tax Summary for KPI cards
  const taxSummary = useMemo(() => {
    // Simple conversion utility (duplicated for inner scope if needed, or moved to a higher scope)
    const convertToUSD = (amount: number, currency?: string) => {
      if (!currency || currency === 'USD' || currency === '$') return amount;
      const rates: Record<string, number> = {
        'EUR': 1.08, 'Euro': 1.08, '€': 1.08,
        'GBP': 1.25, '£': 1.25,
        'CAD': 0.74, 'AED': 0.27, 'SAR': 0.27
      };
      return amount * (rates[currency] || 1);
    };

    let totalRevenue = 0;
    let totalExpenses = 0;
    let actualTaxPayable = 0;
    let totalTaxPaid = 0;

    projects.forEach(p => {
      totalRevenue += convertToUSD(p.clientTotalAmount || 0, p.currency);
      totalExpenses += convertToUSD(p.totalAmount || 0, p.currency);
      actualTaxPayable += convertToUSD(p.taxAmount || 0, p.currency);
    });

    expenses.forEach(e => {
      if (e.status === 'Approved') {
        if (e.category === 'Tax Payment') {
          totalTaxPaid += e.amount;
        } else {
          totalExpenses += e.amount;
        }
      }
    });

    const corporateTaxRate = (companySettings.corporateTaxRate || 25) / 100;
    const netProfit = totalRevenue - totalExpenses;
    const estimatedCorporateTax = Math.max(0, netProfit * corporateTaxRate);
    const estimatedVAT = Math.max(0, actualTaxPayable - totalTaxPaid);

    return {
      corporateTax: estimatedCorporateTax,
      totalEstimate: estimatedCorporateTax + estimatedVAT,
      ownersEquity: accounts.find(a => a.id === '3000')?.balance || 0,
      taxPayments: accounts.find(a => a.id === '5300')?.balance || 0,
      travelMaterials: accounts.find(a => a.id === '5200')?.balance || 0
    };
  }, [projects, expenses, accounts]);

  // Generate Ledger Entries
  const ledgerEntries = useMemo<JournalEntry[]>(() => {
    // Simple conversion utility
    const convertToUSD = (amount: number, currency?: string) => {
      if (!currency || currency === 'USD' || currency === '$') return amount;
      const rates: Record<string, number> = {
        'EUR': 1.08, 'Euro': 1.08, '€': 1.08,
        'GBP': 1.25, '£': 1.25,
        'CAD': 0.74, 'AED': 0.27, 'SAR': 0.27
      };
      return amount * (rates[currency] || 1);
    };

    const entries: JournalEntry[] = [];

    projects.forEach(p => {
      const revenue = convertToUSD(p.clientTotalAmount || 0, p.currency);
      const taxAmount = convertToUSD(p.taxAmount || 0, p.currency);
      const netRevenue = revenue - taxAmount;
      const cost = convertToUSD(p.totalAmount || 0, p.currency);
      const date = p.issueDate || new Date().toISOString().split('T')[0];

      // Revenue Entry
      if (revenue > 0) {
        // Net Revenue
        entries.push({
          id: `JE-REV-NET-${p.id}`,
          date,
          description: `Project Revenue (Net) - ${p.client}`,
          reference: p.ticketId || p.id,
          debit: 0,
          credit: netRevenue,
          account: 'Project Revenue'
        });

        // Tax Component
        if (taxAmount > 0) {
          entries.push({
            id: `JE-TAX-PAY-${p.id}`,
            date,
            description: `Tax Payable (VAT) - ${p.client}`,
            reference: p.ticketId || p.id,
            debit: 0,
            credit: taxAmount,
            account: 'Tax Payable (VAT)'
          });
        }
        
        if (p.clientInvoiceStatus === 'Paid') {
          entries.push({
            id: `JE-CASH-IN-${p.id}`,
            date,
            description: `Cash Receipt - ${p.client}`,
            reference: p.ticketId || p.id,
            debit: revenue,
            credit: 0,
            account: 'Cash & Bank'
          });
        } else {
          entries.push({
            id: `JE-AR-${p.id}`,
            date,
            description: `Accounts Receivable - ${p.client}`,
            reference: p.ticketId || p.id,
            debit: revenue,
            credit: 0,
            account: 'Accounts Receivable'
          });
        }
      }

      // Expense Entry (Engineer)
      if (cost > 0) {
        entries.push({
          id: `JE-ENG-${p.id}`,
          date,
          description: `Engineer Cost - ${p.assignedTo}`,
          reference: p.ticketId || p.id,
          debit: cost,
          credit: 0,
          account: 'Engineer Payouts'
        });

        if (p.engineerInvoiceStatus === 'Paid') {
          entries.push({
            id: `JE-CASH-OUT-${p.id}`,
            date,
            description: `Cash Payment - ${p.assignedTo}`,
            reference: p.ticketId || p.id,
            debit: 0,
            credit: cost,
            account: 'Cash & Bank'
          });
        } else {
          entries.push({
            id: `JE-AP-${p.id}`,
            date,
            description: `Accounts Payable - ${p.assignedTo}`,
            reference: p.ticketId || p.id,
            debit: 0,
            credit: cost,
            account: 'Accounts Payable'
          });
        }
      }

      // Vendor Commission Entries
      let commissions: any[] = [];
      if (p.commissions && p.commissions.length > 0) {
        commissions = p.commissions;
      } else if (p.thirdPartyName) {
        const clientAmt = p.clientTotalAmount || p.totalAmount || 0;
        const commAmt = p.thirdPartyCommissionAmount || (clientAmt * ((p.thirdPartyCommissionRate || 0) / 100));
        commissions = [{
          id: `LEGACY-${p.id}`,
          vendorName: p.thirdPartyName,
          amount: commAmt,
          status: p.thirdPartyStatus || 'Unpaid'
        }];
      }

      commissions.forEach(c => {
        const convertedCommAmt = convertToUSD(c.amount || 0, p.currency);
        if (convertedCommAmt > 0) {
          entries.push({
            id: `JE-COMM-${c.id}`,
            date: date,
            description: `Vendor Commission - ${c.vendorName} (${p.name})`,
            reference: p.ticketId || p.id,
            debit: convertedCommAmt,
            credit: 0,
            account: 'Vendor Commissions'
          });

          if (c.status === 'Paid') {
            entries.push({
              id: `JE-COMM-CASH-${c.id}`,
              date: date,
              description: `Commission Payment - ${c.vendorName}`,
              reference: p.ticketId || p.id,
              debit: 0,
              credit: convertedCommAmt,
              account: 'Cash & Bank'
            });
          } else {
            entries.push({
              id: `JE-COMM-AP-${c.id}`,
              date: date,
              description: `Commission Payable - ${c.vendorName}`,
              reference: p.ticketId || p.id,
              debit: 0,
              credit: convertedCommAmt,
              account: 'Accounts Payable'
            });
          }
        }
      });
    });

    expenses.forEach(e => {
      if (e.status === 'Approved') {
        const isTaxPayment = e.category === 'Tax Payment';
        
        entries.push({
          id: `JE-EXP-${e.id}`,
          date: e.date,
          description: e.description,
          reference: e.reference || e.id,
          debit: e.amount,
          credit: 0,
          account: isTaxPayment ? 'Tax Payments' : 'Operating Expenses'
        });

        if (isTaxPayment) {
          // Reducing Tax Payable
          entries.push({
            id: `JE-TAX-RED-${e.id}`,
            date: e.date,
            description: `Tax Liability Reduction: ${e.description}`,
            reference: e.reference || e.id,
            debit: 0,
            credit: e.amount,
            account: 'Tax Payable (VAT)'
          });
        }

        entries.push({
          id: `JE-EXP-CASH-${e.id}`,
          date: e.date,
          description: `Payment: ${e.description}`,
          reference: e.reference || e.id,
          debit: 0,
          credit: e.amount,
          account: 'Cash & Bank'
        });
      }
    });

    return entries.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [projects, expenses]);

  const filteredEntries = ledgerEntries.filter(e => 
    e.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
    e.account.toLowerCase().includes(searchQuery.toLowerCase()) ||
    e.id.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleDownloadPDF = () => {
    try {
      const doc = new jsPDF();
      const title = reportType === 'pnl' ? 'Profit & Loss Statement' : 'Balance Sheet';
      const date = new Date().toLocaleDateString();

      // Header
      doc.setFontSize(20);
      doc.setTextColor(63, 81, 181); // Indigo
      doc.text('MA IT Tech Services', 14, 22);
      
      doc.setFontSize(16);
      doc.setTextColor(0, 0, 0);
      doc.text(title, 14, 32);
      
      doc.setFontSize(10);
      doc.setTextColor(100, 100, 100);
      doc.text(`Report Date: ${date}`, 14, 40);
      doc.text('Confidential Financial Report', 14, 45);

      const tableData: any[][] = [];
      
      if (reportType === 'pnl') {
        // Revenue
        tableData.push([{ content: 'REVENUE', colSpan: 2, styles: { fillColor: [240, 240, 240], fontStyle: 'bold' } }]);
        accounts.filter(a => a.type === 'Revenue').forEach(a => {
          tableData.push([a.name, `$${a.balance.toLocaleString()}`]);
        });
        const totalRevenue = accounts.filter(a => a.type === 'Revenue').reduce((sum, a) => sum + a.balance, 0);
        tableData.push([{ content: 'Total Revenue', styles: { fontStyle: 'bold' } }, { content: `$${totalRevenue.toLocaleString()}`, styles: { fontStyle: 'bold' } }]);

        // COGS
        tableData.push([{ content: 'COST OF GOODS SOLD', colSpan: 2, styles: { fillColor: [240, 240, 240], fontStyle: 'bold' } }]);
        const cogs = accounts.find(a => a.id === '5000')!;
        tableData.push([cogs.name, `($${cogs.balance.toLocaleString()})`]);
        
        const comms = accounts.find(a => a.id === '5400')!;
        if (comms.balance > 0) {
          tableData.push([comms.name, `($${comms.balance.toLocaleString()})`]);
        }

        tableData.push([{ content: 'Gross Profit', styles: { fontStyle: 'bold' } }, { content: `$${(totalRevenue - cogs.balance - (comms?.balance || 0)).toLocaleString()}`, styles: { fontStyle: 'bold' } }]);

        // Expenses
        tableData.push([{ content: 'OPERATING EXPENSES', colSpan: 2, styles: { fillColor: [240, 240, 240], fontStyle: 'bold' } }]);
        accounts.filter(a => a.type === 'Expense' && a.id !== '5000').forEach(a => {
          tableData.push([a.name, `($${a.balance.toLocaleString()})`]);
        });
        const totalExpenses = accounts.filter(a => a.type === 'Expense').reduce((sum, a) => sum + a.balance, 0);
        tableData.push([{ content: 'Total Expenses', styles: { fontStyle: 'bold' } }, { content: `($${totalExpenses.toLocaleString()})`, styles: { fontStyle: 'bold' } }]);

        // Net Income
        const netIncome = totalRevenue - totalExpenses;
        tableData.push([{ content: 'NET INCOME', styles: { fontStyle: 'bold', textColor: [63, 81, 181] } }, { content: `$${netIncome.toLocaleString()}`, styles: { fontStyle: 'bold', textColor: [63, 81, 181] } }]);
      } else {
        // Assets
        tableData.push([{ content: 'ASSETS', colSpan: 2, styles: { fillColor: [240, 240, 240], fontStyle: 'bold' } }]);
        accounts.filter(a => a.type === 'Asset').forEach(a => {
          tableData.push([a.name, `$${a.balance.toLocaleString()}`]);
        });
        const totalAssets = accounts.filter(a => a.type === 'Asset').reduce((sum, a) => sum + a.balance, 0);
        tableData.push([{ content: 'Total Assets', styles: { fontStyle: 'bold' } }, { content: `$${totalAssets.toLocaleString()}`, styles: { fontStyle: 'bold' } }]);

        // Liabilities
        tableData.push([{ content: 'LIABILITIES', colSpan: 2, styles: { fillColor: [240, 240, 240], fontStyle: 'bold' } }]);
        accounts.filter(a => a.type === 'Liability').forEach(a => {
          tableData.push([a.name, `$${a.balance.toLocaleString()}`]);
        });
        const totalLiabilities = accounts.filter(a => a.type === 'Liability').reduce((sum, a) => sum + a.balance, 0);
        tableData.push([{ content: 'Total Liabilities', styles: { fontStyle: 'bold' } }, { content: `$${totalLiabilities.toLocaleString()}`, styles: { fontStyle: 'bold' } }]);

        // Equity
        tableData.push([{ content: 'EQUITY', colSpan: 2, styles: { fillColor: [240, 240, 240], fontStyle: 'bold' } }]);
        accounts.filter(a => a.type === 'Equity').forEach(a => {
          tableData.push([a.name, `$${a.balance.toLocaleString()}`]);
        });
        const totalEquity = accounts.filter(a => a.type === 'Equity').reduce((sum, a) => sum + a.balance, 0);
        tableData.push([{ content: 'Total Equity', styles: { fontStyle: 'bold' } }, { content: `$${totalEquity.toLocaleString()}`, styles: { fontStyle: 'bold' } }]);

        // Total L+E
        tableData.push([{ content: 'TOTAL LIABILITIES & EQUITY', styles: { fontStyle: 'bold', textColor: [63, 81, 181] } }, { content: `$${(totalLiabilities + totalEquity).toLocaleString()}`, styles: { fontStyle: 'bold', textColor: [63, 81, 181] } }]);
      }

      autoTable(doc, {
        startY: 55,
        head: [['Account', 'Amount']],
        body: tableData,
        theme: 'striped',
        headStyles: { fillColor: [63, 81, 181] },
        alternateRowStyles: { fillColor: [245, 245, 250] },
      });

      doc.save(`${title.replace(/\s+/g, '_').toLowerCase()}_${date.replace(/\//g, '-')}.pdf`);
      toast.success('Financial report downloaded successfully');
    } catch (error) {
      console.error('PDF Generation Error:', error);
      toast.error('Failed to generate PDF report');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-primary/10 text-primary">
            <BookOpen size={24} />
          </div>
          <div>
            <h2 className="text-2xl font-bold tracking-tight">Bookkeeping System</h2>
            <p className="text-sm text-muted-foreground">Double-entry accounting and financial reporting.</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button 
            onClick={() => toast.info('Manual Journal Entry coming soon')}
            className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-bold text-primary-foreground hover:bg-primary/90 transition-all shadow-md active:scale-95"
          >
            <Plus size={18} />
            New Entry
          </button>
        </div>
      </div>

      {/* Navigation Tabs */}
      <div className="flex items-center gap-1 p-1 bg-muted/50 rounded-xl border border-border w-fit">
        <button 
          onClick={() => setView('ledger')}
          className={cn(
            "flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",
            view === 'ledger' ? "bg-card shadow-sm text-primary" : "text-muted-foreground hover:bg-muted"
          )}
        >
          <FileText size={16} />
          General Ledger
        </button>
        <button 
          onClick={() => setView('accounts')}
          className={cn(
            "flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",
            view === 'accounts' ? "bg-card shadow-sm text-primary" : "text-muted-foreground hover:bg-muted"
          )}
        >
          <Wallet size={16} />
          Chart of Accounts
        </button>
        <button 
          onClick={() => setView('reports')}
          className={cn(
            "flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all",
            view === 'reports' ? "bg-card shadow-sm text-primary" : "text-muted-foreground hover:bg-muted"
          )}
        >
          <PieChart size={16} />
          Financial Reports
        </button>
      </div>

      <AnimatePresence mode="wait">
        {view === 'ledger' && (
          <motion.div
            key="ledger"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="space-y-4"
          >
            <div className="flex items-center gap-4">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
                <input
                  type="text"
                  placeholder="Search ledger entries..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="h-10 w-full rounded-lg border border-border bg-background pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <button className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors">
                <Filter size={18} />
                Filter
              </button>
              <button 
                onClick={() => toast.success('Ledger exported to CSV')}
                className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
              >
                <Download size={18} />
                Export
              </button>
            </div>

            <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
              <table className="w-full text-left text-sm">
                <thead className="bg-muted/50 border-b border-border">
                  <tr>
                    <th className="px-4 py-3 font-semibold text-muted-foreground">Date</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground">Description</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground">Account</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground text-right">Debit</th>
                    <th className="px-4 py-3 font-semibold text-muted-foreground text-right">Credit</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {filteredEntries.map((entry) => (
                    <tr key={entry.id} className="hover:bg-muted/30 transition-colors group">
                      <td className="px-4 py-3 text-muted-foreground font-mono text-xs">{entry.date}</td>
                      <td className="px-4 py-3">
                        <div className="flex flex-col">
                          <span className="font-medium">{entry.description}</span>
                          <span className="text-[10px] text-muted-foreground uppercase tracking-wider">{entry.reference}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase bg-muted text-muted-foreground">
                          {entry.account}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right font-mono text-green-500">
                        {entry.debit > 0 ? `$${entry.debit.toLocaleString(undefined, { minimumFractionDigits: 2 })}` : '-'}
                      </td>
                      <td className="px-4 py-3 text-right font-mono text-red-500">
                        {entry.credit > 0 ? `$${entry.credit.toLocaleString(undefined, { minimumFractionDigits: 2 })}` : '-'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </motion.div>
        )}

        {view === 'accounts' && (
          <motion.div
            key="accounts"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="space-y-6"
          >
            {/* KPI Cards for Chart of Accounts */}
            <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
              <div className="rounded-2xl border border-border bg-indigo-600 p-6 text-white shadow-lg shadow-indigo-200/50">
                <div className="flex items-center justify-between mb-4">
                  <div className="p-2 rounded-lg bg-white/20">
                    <PieChart size={20} />
                  </div>
                  <span className="text-[10px] font-bold uppercase tracking-widest text-indigo-100">Tax Planning</span>
                </div>
                <h3 className="text-sm font-medium text-indigo-100 mb-1">Total Tax Estimate</h3>
                <div className="flex items-baseline gap-2">
                  <span className="text-3xl font-bold">${taxSummary.totalEstimate.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                </div>
              </div>

              <div className="rounded-2xl border border-border bg-card p-6 shadow-sm">
                <div className="flex items-center justify-between mb-4">
                  <div className="p-2 rounded-lg bg-primary/10 text-primary">
                    <DollarSign size={20} />
                  </div>
                  <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">Fiscal Year</span>
                </div>
                <h3 className="text-sm font-medium text-muted-foreground mb-1">Estimated Corporate Tax</h3>
                <div className="flex items-baseline gap-2">
                  <span className="text-3xl font-bold text-foreground">${taxSummary.corporateTax.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                </div>
              </div>

              <div className="rounded-2xl border border-border bg-emerald-600 p-6 text-white shadow-lg shadow-emerald-200/50">
                <div className="flex items-center justify-between mb-4">
                  <div className="p-2 rounded-lg bg-white/20">
                    <Wallet size={20} />
                  </div>
                  <span className="text-[10px] font-bold uppercase tracking-widest text-emerald-100">Net Worth</span>
                </div>
                <h3 className="text-sm font-medium text-emerald-100 mb-1">Owner's Equity</h3>
                <div className="flex items-baseline gap-2">
                  <span className="text-3xl font-bold">${taxSummary.ownersEquity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                </div>
              </div>

              <div className="rounded-2xl border border-border bg-orange-600 p-6 text-white shadow-lg shadow-orange-200/50">
                <div className="flex items-center justify-between mb-4">
                  <div className="p-2 rounded-lg bg-white/20">
                    <Receipt size={20} />
                  </div>
                  <span className="text-[10px] font-bold uppercase tracking-widest text-orange-100">Compliance</span>
                </div>
                <h3 className="text-sm font-medium text-orange-100 mb-1">Tax Payments</h3>
                <div className="flex items-baseline gap-2">
                  <span className="text-3xl font-bold">${taxSummary.taxPayments.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                </div>
              </div>

              <div className="rounded-2xl border border-border bg-blue-600 p-6 text-white shadow-lg shadow-blue-200/50">
                <div className="flex items-center justify-between mb-4">
                  <div className="p-2 rounded-lg bg-white/20">
                    <Plane size={20} />
                  </div>
                  <span className="text-[10px] font-bold uppercase tracking-widest text-blue-100">Operations</span>
                </div>
                <h3 className="text-sm font-medium text-blue-100 mb-1">Travel & Materials</h3>
                <div className="flex items-baseline gap-2">
                  <span className="text-3xl font-bold">${taxSummary.travelMaterials.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {accounts.map((account) => (
              <div key={account.id} className="rounded-xl border border-border bg-card p-4 shadow-sm hover:shadow-md transition-all group">
                <div className="flex items-center justify-between mb-4">
                  <div className={cn(
                    "p-2 rounded-lg",
                    account.type === 'Asset' ? "bg-blue-500/10 text-blue-500" :
                    account.type === 'Liability' ? "bg-red-500/10 text-red-500" :
                    account.type === 'Equity' ? "bg-purple-500/10 text-purple-500" :
                    account.type === 'Revenue' ? "bg-green-500/10 text-green-500" :
                    "bg-orange-500/10 text-orange-500"
                  )}>
                    <Wallet size={20} />
                  </div>
                  <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">#{account.code}</span>
                </div>
                <h3 className="text-lg font-bold mb-1">{account.name}</h3>
                <p className="text-xs text-muted-foreground uppercase tracking-wider mb-4">{account.type}</p>
                <div className="flex items-end justify-between">
                  <div className="flex flex-col">
                    <span className="text-[10px] text-muted-foreground uppercase tracking-wider">Current Balance</span>
                    <span className={cn(
                      "text-xl font-bold",
                      account.balance >= 0 ? "text-foreground" : "text-red-500"
                    )}>
                      ${account.balance.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                    </span>
                  </div>
                  <button className="p-2 rounded-lg hover:bg-accent text-muted-foreground transition-colors opacity-0 group-hover:opacity-100">
                    <ChevronRight size={18} />
                  </button>
                </div>
              </div>
            ))}
            </div>
          </motion.div>
        )}

        {view === 'reports' && (
          <motion.div
            key="reports"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="space-y-6"
          >
            <div className="flex items-center gap-2 p-1 bg-muted/50 rounded-xl border border-border w-fit">
              <button 
                onClick={() => setReportType('pnl')}
                className={cn(
                  "px-4 py-2 text-sm font-medium rounded-lg transition-all",
                  reportType === 'pnl' ? "bg-card shadow-sm text-primary" : "text-muted-foreground hover:bg-muted"
                )}
              >
                Profit & Loss
              </button>
              <button 
                onClick={() => setReportType('balance_sheet')}
                className={cn(
                  "px-4 py-2 text-sm font-medium rounded-lg transition-all",
                  reportType === 'balance_sheet' ? "bg-card shadow-sm text-primary" : "text-muted-foreground hover:bg-muted"
                )}
              >
                Balance Sheet
              </button>
            </div>

            <div className="rounded-2xl border border-border bg-card p-8 shadow-sm">
              <div className="flex items-center justify-between mb-8">
                <div>
                  <h3 className="text-2xl font-bold tracking-tight">
                    {reportType === 'pnl' ? 'Profit & Loss Statement' : 'Balance Sheet'}
                  </h3>
                  <p className="text-sm text-muted-foreground">For the period ending {new Date().toLocaleDateString()}</p>
                </div>
                <button 
                  onClick={handleDownloadPDF}
                  className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  <Download size={18} />
                  Download PDF
                </button>
              </div>

              {reportType === 'pnl' ? (
                <div className="space-y-8">
                  <ReportSection 
                    title="Revenue" 
                    items={accounts.filter(a => a.type === 'Revenue').map(a => ({ name: a.name, amount: a.balance }))}
                    totalLabel="Total Revenue"
                  />
                  <ReportSection 
                    title="Cost of Goods Sold" 
                    items={accounts.filter(a => a.id === '5000').map(a => ({ name: a.name, amount: a.balance }))}
                    totalLabel="Total COGS"
                    isNegative
                  />
                  <div className="pt-4 border-t border-border flex justify-between items-center">
                    <span className="text-lg font-bold uppercase tracking-wider">Gross Profit</span>
                    <span className="text-xl font-bold">
                      ${(accounts.find(a => a.id === '4000')!.balance - accounts.find(a => a.id === '5000')!.balance - (accounts.find(a => a.id === '5400')?.balance || 0)).toLocaleString()}
                    </span>
                  </div>
                  <ReportSection 
                    title="Operating Expenses" 
                    items={accounts.filter(a => a.type === 'Expense' && a.id !== '5000').map(a => ({ name: a.name, amount: a.balance }))}
                    totalLabel="Total Expenses"
                    isNegative
                  />
                  <div className="pt-6 border-t-2 border-primary flex justify-between items-center">
                    <span className="text-xl font-bold uppercase tracking-widest text-primary">Net Income</span>
                    <span className="text-3xl font-bold text-primary">
                      ${(
                        accounts.filter(a => a.type === 'Revenue').reduce((sum, a) => sum + a.balance, 0) -
                        accounts.filter(a => a.type === 'Expense').reduce((sum, a) => sum + a.balance, 0)
                      ).toLocaleString()}
                    </span>
                  </div>
                </div>
              ) : (
                <div className="space-y-8">
                  <ReportSection 
                    title="Assets" 
                    items={accounts.filter(a => a.type === 'Asset').map(a => ({ name: a.name, amount: a.balance }))}
                    totalLabel="Total Assets"
                  />
                  <ReportSection 
                    title="Liabilities" 
                    items={accounts.filter(a => a.type === 'Liability').map(a => ({ name: a.name, amount: a.balance }))}
                    totalLabel="Total Liabilities"
                  />
                  <ReportSection 
                    title="Equity" 
                    items={accounts.filter(a => a.type === 'Equity').map(a => ({ name: a.name, amount: a.balance }))}
                    totalLabel="Total Equity"
                  />
                  <div className="pt-6 border-t-2 border-primary flex justify-between items-center">
                    <span className="text-xl font-bold uppercase tracking-widest text-primary">Total Liabilities & Equity</span>
                    <span className="text-3xl font-bold text-primary">
                      ${(
                        accounts.filter(a => a.type === 'Liability' || a.type === 'Equity').reduce((sum, a) => sum + a.balance, 0)
                      ).toLocaleString()}
                    </span>
                  </div>
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

function ReportSection({ title, items, totalLabel, isNegative }: { title: string, items: { name: string, amount: number }[], totalLabel: string, isNegative?: boolean }) {
  const total = items.reduce((sum, item) => sum + item.amount, 0);
  
  return (
    <div className="space-y-4">
      <h4 className="text-sm font-bold uppercase tracking-widest text-muted-foreground border-b border-border pb-2">{title}</h4>
      <div className="space-y-2">
        {items.map((item, i) => (
          <div key={i} className="flex justify-between items-center text-sm">
            <span>{item.name}</span>
            <span className="font-mono">${item.amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}</span>
          </div>
        ))}
      </div>
      <div className="flex justify-between items-center pt-2 font-bold">
        <span>{totalLabel}</span>
        <span className={cn(isNegative && "text-red-500")}>
          {isNegative ? `($${total.toLocaleString()})` : `$${total.toLocaleString()}`}
        </span>
      </div>
    </div>
  );
}
