import React, { useState, useMemo, useEffect, useRef } from 'react';
import { useSearchParams } from 'react-router-dom';
import { 
  Receipt, 
  Plus, 
  Search, 
  Filter, 
  Download,
  Calendar,
  ArrowUpRight,
  ArrowDownRight,
  Clock,
  CheckCircle2,
  AlertCircle,
  X,
  Edit,
  Trash2,
  Upload,
  DollarSign,
  Tag,
  CreditCard,
  FileText
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer,
  Cell,
  PieChart,
  Pie
} from 'recharts';
import { useApp, Expense } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';
import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';

const DEFAULT_CATEGORIES = ['Operations', 'Technology', 'Entertainment', 'Travel', 'Marketing', 'Legal', 'Rent', 'Utilities', 'Engineer bills'];
const PAYMENT_METHODS = ['Corporate Card', 'Direct Debit', 'Reimbursement', 'Bank Transfer', 'Cash'];

export function Expenses() {
  const { expenses, addExpense, updateExpense, deleteExpense, companySettings, currencies, addCurrency } = useApp();
  const { hasPermission } = useAuth();
  const [categories, setCategories] = useState(DEFAULT_CATEGORIES);
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchQuery, setSearchQuery] = useState('');
  const [isInvoiceModalOpen, setIsInvoiceModalOpen] = useState(false);
  const [invoiceFormData, setInvoiceFormData] = useState({
    invoiceId: '',
    date: '',
    fromName: '',
    fromEmail: '',
    fromPhone: '',
    fromAddress: '',
    billToName: '',
    billToEmail: '',
    billToPhone: '',
    billToAddress: '',
    description: '',
    amount: 0,
    currency: '$'
  });

  const handleGenerateInvoice = (expense: Expense) => {
    const invId = `INV-${Math.floor(100000 + Math.random() * 900000)}`;
    setInvoiceFormData({
      invoiceId: invId,
      date: new Date().toISOString().split('T')[0],
      fromName: companySettings.name || 'MA IT TECH',
      fromEmail: companySettings.email || 'support@ma-it-tech.com',
      fromPhone: companySettings.phone || '+971 4 123 4567',
      fromAddress: companySettings.location || 'Dubai, UAE',
      billToName: 'Recipient Name',
      billToEmail: '',
      billToPhone: '',
      billToAddress: '',
      description: expense.description,
      amount: expense.amount,
      currency: '$'
    });
    setIsInvoiceModalOpen(true);
  };

  useEffect(() => {
    const create = searchParams.get('create');
    if (create === 'true') {
      setIsModalOpen(true);
      const newParams = new URLSearchParams(searchParams);
      newParams.delete('create');
      setSearchParams(newParams, { replace: true });
    }
  }, [searchParams, setSearchParams]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingExpense, setEditingExpense] = useState<Expense | null>(null);
  const [viewingExpense, setViewingExpense] = useState<Expense | null>(null);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [expenseToDelete, setExpenseToDelete] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  // Manage Cards State
  const [isCardsModalOpen, setIsCardsModalOpen] = useState(false);
  const [isIssueCardModalOpen, setIsIssueCardModalOpen] = useState(false);
  const [editingCardId, setEditingCardId] = useState<string | null>(null);
  const [newLimitValue, setNewLimitValue] = useState<number>(0);
  const [cards, setCards] = useState([
    { id: '1', holder: 'John Doe', number: '•••• 4242', type: 'Visa', limit: 5000, spent: 1240.50 },
    { id: '2', holder: 'Jane Smith', number: '•••• 8888', type: 'Mastercard', limit: 3000, spent: 450.20 },
  ]);

  const [newCardData, setNewCardData] = useState({
    holder: '',
    type: 'Visa',
    limit: 1000
  });

  const handleUpdateCardLimit = (cardId: string) => {
    if (newLimitValue <= 0) {
      toast.error('Limit must be greater than 0');
      return;
    }
    setCards(cards.map(c => c.id === cardId ? { ...c, limit: newLimitValue } : c));
    setEditingCardId(null);
    toast.success('Card limit updated');
  };

  const handleIssueNewCard = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newCardData.holder) {
      toast.error('Card holder name is required');
      return;
    }
    
    const newCard = {
      id: Math.random().toString(36).substr(2, 9),
      holder: newCardData.holder,
      number: `•••• ${Math.floor(1000 + Math.random() * 9000)}`,
      type: newCardData.type,
      limit: newCardData.limit,
      spent: 0
    };
    
    setCards([...cards, newCard]);
    setIsIssueCardModalOpen(false);
    setNewCardData({ holder: '', type: 'Visa', limit: 1000 });
    toast.success('New corporate card issued');
  };

  // Filter State
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [filterCategory, setFilterCategory] = useState('All');
  const [filterStatus, setFilterStatus] = useState('All');
  const [filterPaymentMethod, setFilterPaymentMethod] = useState('All');
  const filterRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (filterRef.current && !filterRef.current.contains(event.target as Node)) {
        setIsFilterOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const [newExpense, setNewExpense] = useState<Partial<Expense>>({
    description: '',
    category: 'Operations',
    amount: 0,
    date: new Date().toISOString().split('T')[0],
    status: 'Pending',
    paymentMethod: 'Corporate Card'
  });

  const filteredExpenses = useMemo(() => {
    return expenses.filter(e => {
      const matchesSearch = e.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
        e.category.toLowerCase().includes(searchQuery.toLowerCase()) ||
        e.id.toLowerCase().includes(searchQuery.toLowerCase());
      
      const matchesCategory = filterCategory === 'All' || e.category === filterCategory;
      const matchesStatus = filterStatus === 'All' || e.status === filterStatus;
      const matchesPayment = filterPaymentMethod === 'All' || e.paymentMethod === filterPaymentMethod;
      
      return matchesSearch && matchesCategory && matchesStatus && matchesPayment;
    });
  }, [expenses, searchQuery, filterCategory, filterStatus, filterPaymentMethod]);

  const stats = useMemo(() => {
    const total = expenses.reduce((sum, e) => sum + e.amount, 0);
    const pending = expenses.filter(e => e.status === 'Pending').reduce((sum, e) => sum + e.amount, 0);
    const approved = expenses.filter(e => e.status === 'Approved').reduce((sum, e) => sum + e.amount, 0);
    
    const categoryData = categories.map(cat => ({
      name: cat,
      value: expenses.filter(e => e.category === cat).reduce((sum, e) => sum + e.amount, 0)
    })).filter(d => d.value > 0);

    return { total, pending, approved, categoryData };
  }, [expenses, categories]);

  const handleAddExpense = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;

    setIsSubmitting(true);
    try {
      if (editingExpense) {
        await updateExpense(editingExpense.id, newExpense);
        toast.success('Expense updated successfully');
      } else {
        const expense: Expense = {
          id: `EXP-${Math.floor(Math.random() * 10000).toString().padStart(3, '0')}`,
          description: newExpense.description || 'New Expense',
          category: newExpense.category || 'Operations',
          amount: Number(newExpense.amount) || 0,
          date: newExpense.date || new Date().toISOString().split('T')[0],
          status: (newExpense.status as any) || 'Pending',
          paymentMethod: newExpense.paymentMethod || 'Corporate Card',
          reference: newExpense.reference
        };
        await addExpense(expense);
        toast.success('Expense recorded successfully');
      }

      setIsModalOpen(false);
      setEditingExpense(null);
      setNewExpense({
        description: '',
        category: 'Operations',
        amount: 0,
        date: new Date().toISOString().split('T')[0],
        status: 'Pending',
        paymentMethod: 'Corporate Card'
      });
    } catch (error) {
      console.error('Save expense error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleEdit = (expense: Expense) => {
    setEditingExpense(expense);
    setNewExpense(expense);
    setIsModalOpen(true);
  };

  const handleDeleteClick = (id: string) => {
    setExpenseToDelete(id);
    setIsDeleteModalOpen(true);
  };

  const confirmDelete = async () => {
    if (expenseToDelete && !isSubmitting) {
      setIsSubmitting(true);
      try {
        await deleteExpense(expenseToDelete);
        toast.success('Expense deleted');
        setIsDeleteModalOpen(false);
        setExpenseToDelete(null);
      } catch (error) {
        console.error('Delete expense error:', error);
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  const handleExportCSV = () => {
    if (filteredExpenses.length === 0) {
      toast.error('No expenses to export');
      return;
    }

    const headers = ['ID', 'Description', 'Category', 'Date', 'Amount', 'Status', 'Payment Method', 'Reference'];
    const csvRows = [
      headers.join(','),
      ...filteredExpenses.map(e => [
        `"${e.id}"`,
        `"${e.description}"`,
        `"${e.category}"`,
        `"${e.date}"`,
        e.amount.toFixed(2),
        `"${e.status}"`,
        `"${e.paymentMethod}"`,
        `"${e.reference || ''}"`
      ].join(','))
    ];

    const csvContent = csvRows.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `company_expenses_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    toast.success('Expenses exported successfully');
  };

  const handleImportCSV = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || isSubmitting) return;

    setIsSubmitting(true);
    const reader = new FileReader();
    reader.onload = async (event) => {
      try {
        const text = event.target?.result as string;
        const rows = text.split('\n').filter(row => row.trim() !== '');
        if (rows.length < 2) {
          toast.error('Invalid CSV file format');
          return;
        }

        const newExpenses: Expense[] = [];
        for (let i = 1; i < rows.length; i++) {
          const matches = rows[i].match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
          if (!matches || matches.length < 6) continue;

          const clean = (val: string) => val.replace(/^"|"$/g, '').trim();
          
          const expense: Expense = {
            id: clean(matches[0]),
            description: clean(matches[1]),
            category: clean(matches[2]),
            date: clean(matches[3]),
            amount: parseFloat(clean(matches[4])) || 0,
            status: clean(matches[5]) as any,
            paymentMethod: clean(matches[6]) || 'Corporate Card',
            reference: matches[7] ? clean(matches[7]) : undefined
          };
          newExpenses.push(expense);
        }

        if (newExpenses.length === 0) {
          toast.error('No valid data found in CSV');
          return;
        }

        const existingIds = new Set(expenses.map(e => e.id));
        const uniqueNewExpenses = newExpenses.filter(e => !existingIds.has(e.id));
        
        if (uniqueNewExpenses.length === 0) {
          toast.info('All records in CSV already exist in the system');
        } else {
          for (const exp of uniqueNewExpenses) {
            await addExpense(exp);
          }
          toast.success(`Successfully imported ${uniqueNewExpenses.length} new expenses`);
        }
      } catch (error) {
        console.error('Import error:', error);
        toast.error('Failed to parse CSV file');
      } finally {
        setIsSubmitting(false);
        if (e.target) e.target.value = '';
      }
    };
    reader.readAsText(file);
  };

  const handleGeneratePDFReport = () => {
    if (filteredExpenses.length === 0) {
      toast.error('No expenses to report');
      return;
    }

    const doc = new jsPDF();
    
    // Add Title
    doc.setFontSize(20);
    doc.text('Company Expense Report', 14, 22);
    
    // Add Date
    doc.setFontSize(11);
    doc.setTextColor(100);
    doc.text(`Generated on: ${new Date().toLocaleString()}`, 14, 30);
    
    // Add Summary
    doc.setFontSize(12);
    doc.setTextColor(0);
    doc.text(`Total Expenses: $${stats.total.toLocaleString()}`, 14, 40);
    doc.text(`Approved: $${stats.approved.toLocaleString()}`, 14, 47);
    doc.text(`Pending: $${stats.pending.toLocaleString()}`, 14, 54);

    // Add Table
    autoTable(doc, {
      startY: 65,
      head: [['Description', 'Category', 'Date', 'Amount', 'Status']],
      body: filteredExpenses.map(e => [
        e.description,
        e.category,
        e.date,
        `$${e.amount.toFixed(2)}`,
        e.status
      ]),
      headStyles: { fillColor: [79, 70, 229] }, // Indigo-600
    });

    doc.save(`expense_report_${new Date().toISOString().split('T')[0]}.pdf`);
    toast.success('PDF Report generated successfully');
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Company Expenses</h1>
          <p className="text-muted-foreground">Track and manage all operational expenditures.</p>
        </div>
        {hasPermission('finance.create') && (
          <button 
            onClick={() => setIsModalOpen(true)}
            className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors shadow-sm"
          >
            <Plus size={18} />
            Record Expense
          </button>
        )}
      </div>

      {/* KPI Cards */}
      <div className="grid gap-4 sm:grid-cols-3">
        <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-primary/10 text-primary">
              <DollarSign size={20} />
            </div>
            <div>
              <p className="text-sm text-muted-foreground">Total Expenses</p>
              <p className="text-2xl font-bold">${stats.total.toLocaleString(undefined, { minimumFractionDigits: 2 })}</p>
            </div>
          </div>
        </div>
        <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-yellow-500/10 text-yellow-500">
              <Clock size={20} />
            </div>
            <div>
              <p className="text-sm text-muted-foreground">Pending Approval</p>
              <p className="text-2xl font-bold">${stats.pending.toLocaleString(undefined, { minimumFractionDigits: 2 })}</p>
            </div>
          </div>
        </div>
        <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-green-500/10 text-green-500">
              <CheckCircle2 size={20} />
            </div>
            <div>
              <p className="text-sm text-muted-foreground">Approved This Month</p>
              <p className="text-2xl font-bold">${stats.approved.toLocaleString(undefined, { minimumFractionDigits: 2 })}</p>
            </div>
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Expense List */}
        <div className="lg:col-span-2 space-y-4">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center justify-between">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
              <input
                type="text"
                placeholder="Search expenses..."
                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>
            <div className="flex items-center gap-2">
              <div className="relative" ref={filterRef}>
                <button 
                  onClick={() => setIsFilterOpen(!isFilterOpen)}
                  className={cn(
                    "flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium hover:bg-accent transition-colors",
                    (filterCategory !== 'All' || filterStatus !== 'All' || filterPaymentMethod !== 'All') && "border-primary text-primary"
                  )}
                >
                  <Filter size={16} />
                  Filter
                  {(filterCategory !== 'All' || filterStatus !== 'All' || filterPaymentMethod !== 'All') && (
                    <span className="flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground">
                      {[filterCategory, filterStatus, filterPaymentMethod].filter(f => f !== 'All').length}
                    </span>
                  )}
                </button>

                {isFilterOpen && (
                  <div className="absolute right-0 mt-2 z-50 w-64 rounded-xl border border-border bg-card p-4 shadow-lg animate-in fade-in slide-in-from-top-2 duration-200">
                    <div className="flex items-center justify-between mb-4">
                      <h4 className="font-bold text-sm">Filter Expenses</h4>
                      <button 
                        onClick={() => {
                          setFilterCategory('All');
                          setFilterStatus('All');
                          setFilterPaymentMethod('All');
                        }}
                        className="text-[10px] font-bold uppercase tracking-wider text-primary hover:underline"
                      >
                        Reset
                      </button>
                    </div>
                    
                    <div className="space-y-4">
                      <div className="space-y-2">
                        <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Category</label>
                        <select 
                          value={filterCategory}
                          onChange={(e) => setFilterCategory(e.target.value)}
                          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                        >
                          <option value="All">All Categories</option>
                          {categories.map(cat => (
                            <option key={cat} value={cat}>{cat}</option>
                          ))}
                        </select>
                      </div>

                      <div className="space-y-2">
                        <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Status</label>
                        <select 
                          value={filterStatus}
                          onChange={(e) => setFilterStatus(e.target.value)}
                          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                        >
                          <option value="All">All Statuses</option>
                          <option value="Pending">Pending</option>
                          <option value="Approved">Approved</option>
                          <option value="Rejected">Rejected</option>
                        </select>
                      </div>

                      <div className="space-y-2">
                        <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Payment Method</label>
                        <select 
                          value={filterPaymentMethod}
                          onChange={(e) => setFilterPaymentMethod(e.target.value)}
                          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                        >
                          <option value="All">All Methods</option>
                          {PAYMENT_METHODS.map(method => (
                            <option key={method} value={method}>{method}</option>
                          ))}
                        </select>
                      </div>
                    </div>
                  </div>
                )}
              </div>
              <div className="flex items-center gap-2">
                {hasPermission('finance.create') && (
                  <div className="relative">
                    <input 
                      type="file" 
                      accept=".csv"
                      className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                      onChange={handleImportCSV}
                    />
                    <button className="flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium hover:bg-accent transition-colors">
                      <Upload size={16} />
                      Import
                    </button>
                  </div>
                )}
                {hasPermission('finance.export') && (
                  <button 
                    onClick={handleExportCSV}
                    className="flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium hover:bg-accent transition-colors"
                  >
                    <Download size={16} />
                    Export
                  </button>
                )}
              </div>
            </div>
          </div>

          <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
            <div className="overflow-x-auto">
              <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-medium">Description</th>
                    <th className="px-4 py-3 font-medium">Category</th>
                    <th className="px-4 py-3 font-medium">Date</th>
                    <th className="px-4 py-3 font-medium">Amount</th>
                    <th className="px-4 py-3 font-medium">Status</th>
                    <th className="px-4 py-3 font-medium text-right">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {filteredExpenses.map((expense) => (
                    <tr key={expense.id} className="hover:bg-accent/30 transition-colors group">
                      <td className="px-4 py-4">
                        <div>
                          <p className="font-medium">{expense.description}</p>
                          <p className="text-[10px] text-muted-foreground">{expense.id} • {expense.paymentMethod}</p>
                        </div>
                      </td>
                      <td className="px-4 py-4">
                        <span className="inline-flex items-center gap-1 rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
                          <Tag size={10} />
                          {expense.category}
                        </span>
                      </td>
                      <td className="px-4 py-4 text-muted-foreground">
                        {expense.date}
                      </td>
                      <td className="px-4 py-4 font-bold">
                        ${expense.amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                      </td>
                      <td className="px-4 py-4">
                        <span className={cn(
                          "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",
                          expense.status === 'Approved' ? "bg-green-500/10 text-green-500" :
                          expense.status === 'Pending' ? "bg-yellow-500/10 text-yellow-500" :
                          "bg-red-500/10 text-red-500"
                        )}>
                          {expense.status === 'Approved' ? <CheckCircle2 size={12} /> : 
                           expense.status === 'Pending' ? <Clock size={12} /> : <AlertCircle size={12} />}
                          {expense.status}
                        </span>
                      </td>
                      <td className="px-4 py-4 text-right">
                        <div className="flex items-center justify-end gap-2">
                          <button 
                            onClick={() => setViewingExpense(expense)}
                            className="p-1.5 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                            title="View Details"
                          >
                            <FileText size={16} />
                          </button>
                          {hasPermission('finance.edit') && (
                            <button 
                              onClick={() => handleEdit(expense)}
                              className="p-1.5 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                              title="Edit"
                            >
                              <Edit size={16} />
                            </button>
                          )}
                          {hasPermission('finance.delete') && (
                            <button 
                              onClick={() => handleDeleteClick(expense.id)}
                              className="p-1.5 hover:bg-destructive/10 rounded-md text-destructive transition-colors"
                              title="Delete"
                            >
                              <Trash2 size={16} />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* Charts & Summary */}
        <div className="space-y-6">
          <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
            <h3 className="text-lg font-bold mb-4">Expense by Category</h3>
            <div className="h-[300px]">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={stats.categoryData}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={80}
                    paddingAngle={5}
                    dataKey="value"
                  >
                    {stats.categoryData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={`hsl(var(--primary) / ${100 - (index * 15)}%)`} />
                    ))}
                  </Pie>
                  <Tooltip 
                    contentStyle={{ backgroundColor: 'hsl(var(--card))', borderColor: 'hsl(var(--border))', borderRadius: '8px' }}
                    itemStyle={{ color: 'hsl(var(--foreground))' }}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <div className="mt-4 space-y-2">
              {stats.categoryData.map((data, index) => (
                <div key={data.name} className="flex items-center justify-between text-sm">
                  <div className="flex items-center gap-2">
                    <div className="h-3 w-3 rounded-full" style={{ backgroundColor: `hsl(var(--primary) / ${100 - (index * 15)}%)` }} />
                    <span className="text-muted-foreground">{data.name}</span>
                  </div>
                  <span className="font-medium">${data.value.toLocaleString()}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
            <h3 className="text-lg font-bold mb-4">Quick Actions</h3>
            <div className="grid grid-cols-2 gap-3">
              {hasPermission('finance.export') && (
                <button 
                  onClick={handleGeneratePDFReport}
                  className="flex flex-col items-center justify-center gap-2 p-4 rounded-xl border border-border hover:bg-accent transition-colors"
                >
                  <FileText className="text-primary" size={24} />
                  <span className="text-xs font-medium">Generate Report</span>
                </button>
              )}
              {hasPermission('finance.edit') && (
                <button 
                  onClick={() => setIsCardsModalOpen(true)}
                  className="flex flex-col items-center justify-center gap-2 p-4 rounded-xl border border-border hover:bg-accent transition-colors"
                >
                  <CreditCard className="text-primary" size={24} />
                  <span className="text-xs font-medium">Manage Cards</span>
                </button>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Record Expense Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-2xl animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">{editingExpense ? 'Edit Expense' : 'Record New Expense'}</h2>
              <button 
                onClick={() => {
                  setIsModalOpen(false);
                  setEditingExpense(null);
                  setNewExpense({
                    description: '',
                    category: 'Operations',
                    amount: 0,
                    date: new Date().toISOString().split('T')[0],
                    status: 'Pending',
                    paymentMethod: 'Corporate Card'
                  });
                }}
                className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleAddExpense} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Description *</label>
                <input 
                  type="text" 
                  placeholder="e.g. Office Supplies"
                  value={newExpense.description || ''}
                  onChange={(e) => setNewExpense({...newExpense, description: e.target.value})}
                  className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <label className="text-sm font-medium">Category</label>
                    <button 
                      type="button"
                      onClick={() => {
                        const newCat = prompt('Enter new category name:');
                        if (newCat && newCat.trim()) {
                          const trimmedCat = newCat.trim();
                          if (!categories.includes(trimmedCat)) {
                            setCategories(prev => [...prev, trimmedCat]);
                            setNewExpense(prev => ({...prev, category: trimmedCat}));
                          } else {
                            toast.error('Category already exists');
                          }
                        }
                      }}
                      className="text-[10px] font-bold text-primary hover:underline flex items-center gap-1"
                    >
                      <Plus size={10} /> Add New
                    </button>
                  </div>
                  <select 
                    value={newExpense.category || 'Operations'}
                    onChange={(e) => setNewExpense({...newExpense, category: e.target.value})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                  >
                    {categories.map(cat => (
                      <option key={cat} value={cat}>{cat}</option>
                    ))}
                  </select>
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Amount ($) *</label>
                  <input 
                    type="number" 
                    step="0.01"
                    placeholder="0.00"
                    value={newExpense.amount ?? 0}
                    onChange={(e) => setNewExpense({...newExpense, amount: parseFloat(e.target.value)})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    required
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Date</label>
                  <input 
                    type="date" 
                    value={newExpense.date || ''}
                    onChange={(e) => setNewExpense({...newExpense, date: e.target.value})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Payment Method</label>
                  <select 
                    value={newExpense.paymentMethod || 'Corporate Card'}
                    onChange={(e) => setNewExpense({...newExpense, paymentMethod: e.target.value})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                  >
                    {PAYMENT_METHODS.map(method => (
                      <option key={method} value={method}>{method}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium">Status</label>
                <select 
                  value={newExpense.status || 'Pending'}
                  onChange={(e) => setNewExpense({...newExpense, status: e.target.value as any})}
                  className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                >
                  <option value="Pending">Pending</option>
                  <option value="Approved">Approved</option>
                  <option value="Rejected">Rejected</option>
                </select>
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium">Reference (Optional)</label>
                <input 
                  type="text" 
                  placeholder="e.g. Receipt #123"
                  value={newExpense.reference || ''}
                  onChange={(e) => setNewExpense({...newExpense, reference: e.target.value})}
                  className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>

              <div className="pt-4 flex items-center gap-3">
                <button 
                  type="button"
                  onClick={() => {
                    setIsModalOpen(false);
                    setEditingExpense(null);
                    setNewExpense({
                      description: '',
                      category: 'Operations',
                      amount: 0,
                      date: new Date().toISOString().split('T')[0],
                      status: 'Pending',
                      paymentMethod: 'Corporate Card'
                    });
                  }}
                  className="flex-1 px-4 py-2 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  disabled={isSubmitting}
                  className="flex-1 bg-primary px-4 py-2 text-sm font-medium text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors shadow-sm disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {isSubmitting ? (
                    <>
                      <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />
                      Saving...
                    </>
                  ) : (
                    editingExpense ? 'Update Expense' : 'Save Expense'
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Manage Cards Modal */}
      {isCardsModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-lg rounded-xl border border-border bg-card p-6 shadow-2xl animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-lg bg-primary/10 text-primary">
                  <CreditCard size={20} />
                </div>
                <h2 className="text-xl font-bold">Manage Corporate Cards</h2>
              </div>
              <button 
                onClick={() => setIsCardsModalOpen(false)}
                className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <div className="space-y-4">
              {cards.map(card => (
                <div key={card.id} className="p-4 rounded-xl border border-border bg-muted/30">
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-10 rounded-full bg-card flex items-center justify-center border border-border">
                        <CreditCard size={18} className="text-muted-foreground" />
                      </div>
                      <div>
                        <p className="font-bold">{card.holder}</p>
                        <p className="text-xs text-muted-foreground">{card.type} • {card.number}</p>
                      </div>
                    </div>
                    {editingCardId === card.id ? (
                      <div className="flex items-center gap-2">
                        <input 
                          type="number"
                          value={newLimitValue}
                          onChange={(e) => setNewLimitValue(parseFloat(e.target.value))}
                          className="w-20 h-8 rounded border border-border bg-background px-2 text-xs focus:outline-none focus:ring-1 focus:ring-primary"
                          autoFocus
                        />
                        <button 
                          onClick={() => handleUpdateCardLimit(card.id)}
                          className="text-[10px] font-bold text-primary hover:underline"
                        >
                          SAVE
                        </button>
                        <button 
                          onClick={() => setEditingCardId(null)}
                          className="text-[10px] font-bold text-muted-foreground hover:underline"
                        >
                          CANCEL
                        </button>
                      </div>
                    ) : (
                      <button 
                        onClick={() => {
                          setEditingCardId(card.id);
                          setNewLimitValue(card.limit);
                        }}
                        className="text-xs font-bold text-primary hover:underline"
                      >
                        Edit Limit
                      </button>
                    )}
                  </div>
                  <div className="space-y-1">
                    <div className="flex justify-between text-xs">
                      <span className="text-muted-foreground">Monthly Spend</span>
                      <span className="font-medium">${card.spent.toLocaleString()} / ${card.limit.toLocaleString()}</span>
                    </div>
                    <div className="h-2 w-full bg-muted rounded-full overflow-hidden">
                      <div 
                        className="h-full bg-primary transition-all duration-500" 
                        style={{ width: `${(card.spent / card.limit) * 100}%` }}
                      />
                    </div>
                  </div>
                </div>
              ))}
              
              <button 
                onClick={() => setIsIssueCardModalOpen(true)}
                className="w-full py-3 rounded-xl border border-dashed border-border text-muted-foreground text-sm font-medium hover:border-primary hover:text-primary transition-all flex items-center justify-center gap-2"
              >
                <Plus size={16} />
                Issue New Card
              </button>
            </div>

            <div className="mt-6 pt-6 border-t border-border">
              <button 
                onClick={() => setIsCardsModalOpen(false)}
                className="w-full px-4 py-2 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Issue New Card Modal */}
      {isIssueCardModalOpen && (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-2xl animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">Issue New Card</h2>
              <button 
                onClick={() => setIsIssueCardModalOpen(false)}
                className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleIssueNewCard} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Card Holder Name *</label>
                <input 
                  type="text" 
                  placeholder="e.g. Alex Johnson"
                  value={newCardData.holder}
                  onChange={(e) => setNewCardData({...newCardData, holder: e.target.value})}
                  className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Card Type</label>
                  <select 
                    value={newCardData.type}
                    onChange={(e) => setNewCardData({...newCardData, type: e.target.value})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                  >
                    <option value="Visa">Visa</option>
                    <option value="Mastercard">Mastercard</option>
                    <option value="Amex">Amex</option>
                  </select>
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Credit Limit ($) *</label>
                  <input 
                    type="number" 
                    value={newCardData.limit}
                    onChange={(e) => setNewCardData({...newCardData, limit: parseFloat(e.target.value)})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    required
                  />
                </div>
              </div>

              <div className="pt-4 flex items-center gap-3">
                <button 
                  type="button"
                  onClick={() => setIsIssueCardModalOpen(false)}
                  className="flex-1 px-4 py-2 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  className="flex-1 bg-primary px-4 py-2 text-sm font-medium text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors shadow-sm"
                >
                  Issue Card
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {isDeleteModalOpen && (
        <div className="fixed inset-0 z-[300] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-2xl animate-in fade-in zoom-in duration-200">
            <div className="flex items-center gap-3 mb-4 text-destructive">
              <div className="p-2 rounded-full bg-destructive/10">
                <AlertCircle size={24} />
              </div>
              <h2 className="text-xl font-bold">Confirm Deletion</h2>
            </div>
            <p className="text-sm text-muted-foreground mb-6">
              Are you sure you want to delete this expense record? This action cannot be undone.
            </p>
            <div className="flex items-center gap-3">
              <button 
                onClick={() => {
                  setIsDeleteModalOpen(false);
                  setExpenseToDelete(null);
                }}
                className="flex-1 px-4 py-2 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors"
              >
                Cancel
              </button>
              <button 
                onClick={confirmDelete}
                disabled={isSubmitting}
                className="flex-1 bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground rounded-lg hover:bg-destructive/90 transition-colors shadow-sm disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {isSubmitting ? (
                  <>
                    <div className="h-4 w-4 animate-spin rounded-full border-2 border-destructive-foreground border-t-transparent" />
                    Deleting...
                  </>
                ) : (
                  'Delete'
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* View Expense Modal */}
      {viewingExpense && (
        <div className="fixed inset-0 z-[300] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-xl border border-border bg-card shadow-2xl animate-in fade-in zoom-in duration-200 overflow-hidden">
            <div className="bg-primary/5 border-b border-border p-6 flex items-center justify-between">
              <h2 className="text-xl font-bold">Expense Details</h2>
              <button 
                onClick={() => setViewingExpense(null)}
                className="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            <div className="p-6 space-y-6">
              <div className="flex items-center gap-4">
                <div className="p-3 rounded-xl bg-primary/10 text-primary">
                  <Receipt size={24} />
                </div>
                <div>
                  <h3 className="font-bold text-lg">{viewingExpense.description}</h3>
                  <p className="text-sm text-muted-foreground">{viewingExpense.id}</p>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1">
                  <p className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Amount</p>
                  <p className="text-xl font-bold text-primary">${viewingExpense.amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Status</p>
                  <span className={cn(
                    "inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-bold uppercase",
                    viewingExpense.status === 'Approved' ? "bg-green-500/10 text-green-500" :
                    viewingExpense.status === 'Pending' ? "bg-yellow-500/10 text-yellow-500" :
                    "bg-red-500/10 text-red-500"
                  )}>
                    {viewingExpense.status}
                  </span>
                </div>
                <div className="space-y-1">
                  <p className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Category</p>
                  <p className="text-sm font-medium">{viewingExpense.category}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Date</p>
                  <p className="text-sm font-medium">{viewingExpense.date}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Payment Method</p>
                  <p className="text-sm font-medium">{viewingExpense.paymentMethod}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Reference</p>
                  <p className="text-sm font-medium">{viewingExpense.reference || 'N/A'}</p>
                </div>
              </div>

              <div className="pt-4 flex flex-col gap-3">
                <div className="flex gap-3">
                  <button 
                    onClick={() => {
                      handleEdit(viewingExpense);
                      setViewingExpense(null);
                    }}
                    className="flex-1 h-11 flex items-center justify-center gap-2 rounded-xl bg-accent text-sm font-bold hover:bg-accent/80 transition-all shadow-sm"
                  >
                    <Edit size={18} />
                    Edit Expense
                  </button>
                  <button 
                    onClick={() => {
                      handleGenerateInvoice(viewingExpense);
                      setViewingExpense(null);
                    }}
                    className="flex-1 h-11 flex items-center justify-center gap-2 rounded-xl bg-primary text-sm font-bold text-primary-foreground hover:bg-primary/90 transition-all shadow-sm"
                  >
                    <FileText size={18} />
                    Generate Invoice
                  </button>
                </div>
                <button 
                  onClick={() => setViewingExpense(null)}
                  className="w-full h-11 text-sm font-bold border border-border rounded-xl hover:bg-accent transition-all"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
      {/* Expense Invoice Template Modal */}
      {isInvoiceModalOpen && (
        <div className="fixed inset-0 z-[400] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm overflow-y-auto">
          <div className="w-full max-w-4xl rounded-xl border border-border bg-card shadow-2xl animate-in fade-in zoom-in duration-200 my-8">
            <div className="p-8 space-y-8">
              {/* Invoice Header */}
              <div className="flex justify-between items-start">
                <div>
                  <h2 className="text-3xl font-bold text-primary mb-1 tracking-tight">EXPENSE INVOICE</h2>
                  <div className="flex items-center gap-2">
                    <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Invoice ID:</span>
                    <input 
                      type="text" 
                      value={invoiceFormData.invoiceId}
                      onChange={(e) => setInvoiceFormData({...invoiceFormData, invoiceId: e.target.value})}
                      className="text-xs font-mono bg-muted/50 border border-border rounded px-2 py-0.5 focus:outline-none focus:ring-1 focus:ring-primary/20 w-32"
                    />
                  </div>
                </div>
                <div className="text-right">
                  <div className="flex items-center gap-2 mb-4 justify-end">
                    <button 
                      onClick={() => setIsInvoiceModalOpen(false)}
                      className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
                    >
                      <X size={20} />
                    </button>
                  </div>
                  <div className="space-y-1">
                    <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Date Issued</p>
                    <input 
                      type="date" 
                      value={invoiceFormData.date}
                      onChange={(e) => setInvoiceFormData({...invoiceFormData, date: e.target.value})}
                      className="text-sm font-medium bg-transparent border-none p-0 focus:ring-0 text-right w-full"
                    />
                  </div>
                </div>
              </div>

              {/* Billing Info Grid */}
              <div className="grid grid-cols-2 gap-12 border-t border-b border-border py-8">
                {/* From Section */}
                <div className="space-y-4">
                  <h3 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">From</h3>
                  <div className="space-y-3">
                    <input 
                      type="text" 
                      value={invoiceFormData.fromName}
                      onChange={(e) => setInvoiceFormData({...invoiceFormData, fromName: e.target.value})}
                      className="w-full font-bold bg-transparent border-none p-0 focus:ring-0 text-lg"
                      placeholder="Company Name"
                    />
                    <div className="space-y-2">
                      <div className="flex items-center gap-2 text-sm text-muted-foreground">
                        <input 
                          type="email" 
                          value={invoiceFormData.fromEmail}
                          onChange={(e) => setInvoiceFormData({...invoiceFormData, fromEmail: e.target.value})}
                          className="w-full bg-transparent border-none p-0 focus:ring-0 text-sm"
                          placeholder="email@company.com"
                        />
                      </div>
                      <div className="flex items-center gap-2 text-sm text-muted-foreground">
                        <input 
                          type="text" 
                          value={invoiceFormData.fromPhone}
                          onChange={(e) => setInvoiceFormData({...invoiceFormData, fromPhone: e.target.value})}
                          className="w-full bg-transparent border-none p-0 focus:ring-0 text-sm"
                          placeholder="Phone Number"
                        />
                      </div>
                      <textarea 
                        value={invoiceFormData.fromAddress}
                        onChange={(e) => setInvoiceFormData({...invoiceFormData, fromAddress: e.target.value})}
                        className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground resize-none h-20"
                        placeholder="Company Address"
                      />
                    </div>
                  </div>
                </div>

                {/* Bill To Section */}
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <h3 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Bill To</h3>
                    <button 
                      type="button"
                      onClick={() => {
                        const code = prompt('Enter currency code (e.g., JPY):');
                        if (code && code.trim()) {
                          const symbol = prompt('Enter currency symbol (e.g., ¥):') || code.trim();
                          if (!currencies.find(c => c.code === code.trim().toUpperCase())) {
                            addCurrency(code.trim().toUpperCase(), symbol);
                            setInvoiceFormData(prev => ({...prev, currency: symbol}));
                          } else {
                            toast.error('Currency already exists');
                          }
                        }
                      }}
                      className="text-[10px] font-bold text-primary hover:underline flex items-center gap-1"
                    >
                      <Plus size={10} /> +Currency
                    </button>
                  </div>
                  <div className="space-y-3">
                    <input 
                      type="text" 
                      value={invoiceFormData.billToName}
                      onChange={(e) => setInvoiceFormData({...invoiceFormData, billToName: e.target.value})}
                      className="w-full font-bold bg-transparent border-none p-0 focus:ring-0 text-lg"
                      placeholder="Recipient Name"
                    />
                    <div className="space-y-2">
                      <input 
                        type="email" 
                        value={invoiceFormData.billToEmail}
                        onChange={(e) => setInvoiceFormData({...invoiceFormData, billToEmail: e.target.value})}
                        className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                        placeholder="recipient@email.com"
                      />
                      <input 
                        type="text" 
                        value={invoiceFormData.billToPhone}
                        onChange={(e) => setInvoiceFormData({...invoiceFormData, billToPhone: e.target.value})}
                        className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                        placeholder="Recipient Phone"
                      />
                      <textarea 
                        value={invoiceFormData.billToAddress}
                        onChange={(e) => setInvoiceFormData({...invoiceFormData, billToAddress: e.target.value})}
                        className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground resize-none h-20"
                        placeholder="Recipient Address"
                      />
                    </div>
                  </div>
                </div>
              </div>

              {/* Items Table */}
              <div className="space-y-4">
                <table className="w-full text-left text-sm">
                  <thead className="border-b border-border">
                    <tr>
                      <th className="py-3 font-bold uppercase tracking-wider text-muted-foreground text-xs">Description</th>
                      <th className="py-3 font-bold uppercase tracking-wider text-muted-foreground text-xs text-right">Amount</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    <tr>
                      <td className="py-4">
                        <input 
                          type="text" 
                          value={invoiceFormData.description}
                          onChange={(e) => setInvoiceFormData({...invoiceFormData, description: e.target.value})}
                          className="w-full bg-transparent border-none p-0 focus:ring-0 font-medium"
                          placeholder="Expense Description"
                        />
                      </td>
                      <td className="py-4 text-right">
                        <div className="flex items-center justify-end gap-1">
                          <select 
                            value={currencies.find(c => c.symbol === invoiceFormData.currency)?.code || ''}
                            onChange={(e) => {
                              const curr = currencies.find(c => c.code === e.target.value);
                              if (curr) setInvoiceFormData({...invoiceFormData, currency: curr.symbol});
                            }}
                            className="bg-transparent border-none p-0 focus:ring-0 font-bold text-primary appearance-none cursor-pointer text-right min-w-[3rem]"
                          >
                            {currencies.map(curr => (
                              <option key={curr.code} value={curr.code}>{curr.symbol}</option>
                            ))}
                          </select>
                          <input 
                            type="number" 
                            value={invoiceFormData.amount}
                            onChange={(e) => setInvoiceFormData({...invoiceFormData, amount: parseFloat(e.target.value)})}
                            className="w-24 text-right bg-transparent border-none p-0 focus:ring-0 font-bold text-primary"
                          />
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* Summary */}
              <div className="flex justify-end pt-4">
                <div className="w-64 space-y-4">
                  <div className="flex justify-between text-sm p-3 rounded-lg bg-primary/5 border border-primary/10">
                    <span className="text-muted-foreground font-medium">Total Amount</span>
                    <span className="font-bold text-lg text-primary">
                      {invoiceFormData.currency}{invoiceFormData.amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                    </span>
                  </div>
                </div>
              </div>

              <div className="flex justify-end gap-3 pt-6 border-t border-border">
                <button
                  type="button"
                  onClick={() => setIsInvoiceModalOpen(false)}
                  className="rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    const doc = new jsPDF();
                    
                    // Header Background
                    doc.setFillColor(15, 23, 42); // slate-900
                    doc.rect(0, 0, 210, 45, 'F');
                    
                    doc.setTextColor(255, 255, 255);
                    doc.setFontSize(24);
                    doc.text('EXPENSE INVOICE', 20, 28);
                    
                    doc.setFontSize(10);
                    doc.setTextColor(200, 200, 200);
                    doc.text(`Invoice ID: ${invoiceFormData.invoiceId}`, 20, 36);
                    
                    // Main content
                    doc.setTextColor(15, 23, 42);
                    doc.setFontSize(11);
                    doc.setFont('helvetica', 'bold');
                    doc.setTextColor(100, 116, 139);
                    doc.text('FROM:', 20, 60);
                    doc.text('BILL TO:', 110, 60);
                    
                    doc.setFontSize(10);
                    doc.setTextColor(15, 23, 42);
                    
                    // From details
                    let fromY = 68;
                    doc.setFont('helvetica', 'bold');
                    doc.text(invoiceFormData.fromName, 20, fromY);
                    doc.setFont('helvetica', 'normal');
                    fromY += 5;
                    doc.text(invoiceFormData.fromEmail, 20, fromY);
                    fromY += 5;
                    if (invoiceFormData.fromPhone) {
                      doc.text(invoiceFormData.fromPhone, 20, fromY);
                      fromY += 5;
                    }
                    if (invoiceFormData.fromAddress) {
                      const splitFrom = doc.splitTextToSize(invoiceFormData.fromAddress, 80);
                      doc.text(splitFrom, 20, fromY);
                    }
                    
                    // Bill To details
                    let toY = 68;
                    doc.setFont('helvetica', 'bold');
                    doc.text(invoiceFormData.billToName, 110, toY);
                    doc.setFont('helvetica', 'normal');
                    toY += 5;
                    if (invoiceFormData.billToEmail) {
                      doc.text(invoiceFormData.billToEmail, 110, toY);
                      toY += 5;
                    }
                    if (invoiceFormData.billToPhone) {
                      doc.text(invoiceFormData.billToPhone, 110, toY);
                      toY += 5;
                    }
                    if (invoiceFormData.billToAddress) {
                      const splitTo = doc.splitTextToSize(invoiceFormData.billToAddress, 80);
                      doc.text(splitTo, 110, toY);
                    }

                    // Table
                    autoTable(doc, {
                      head: [['Description', 'Amount']],
                      body: [[
                        invoiceFormData.description,
                        `${invoiceFormData.currency}${invoiceFormData.amount.toLocaleString()}`
                      ]],
                      startY: 100,
                      theme: 'grid',
                      headStyles: { fillColor: [15, 23, 42] }
                    });

                    // Total
                    const finalY = (doc as any).lastAutoTable.finalY + 10;
                    doc.setFontSize(14);
                    doc.setFont('helvetica', 'bold');
                    doc.text('TOTAL AMOUNT:', 110, finalY);
                    doc.text(`${invoiceFormData.currency}${invoiceFormData.amount.toLocaleString()}`, 190, finalY, { align: 'right' });
                    
                    doc.save(`${invoiceFormData.invoiceId}.pdf`);
                    toast.success('Expense Invoice generated');
                    setIsInvoiceModalOpen(false);
                  }}
                  className="rounded-lg bg-primary px-6 py-2 text-sm font-bold text-primary-foreground hover:bg-primary/90 transition-colors shadow-lg shadow-primary/20 flex items-center gap-2"
                >
                  <Download size={18} />
                  Download PDF
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
