import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { 
  DollarSign, 
  Plus, 
  Search, 
  Filter, 
  MoreHorizontal, 
  TrendingUp, 
  TrendingDown, 
  CreditCard, 
  Users,
  Percent,
  FileText, 
  Download,
  Calendar,
  ArrowUpRight,
  ArrowDownRight,
  Clock,
  CheckCircle2,
  AlertCircle,
  X,
  Edit
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer,
  Cell,
  LineChart,
  Line
} from 'recharts';
import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';
import { motion, AnimatePresence } from 'framer-motion';

import { useApp, Project } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';

import { Bookkeeping } from '@/components/Finance/Bookkeeping';
import { TaxModule } from '@/components/Finance/TaxModule';

interface Transaction {
  id: string;
  invoiceId: string;
  description: string;
  category: string;
  amount: string;
  type: 'Income' | 'Expense';
  date: string;
  status: 'Completed' | 'Pending' | 'Failed' | 'Cancelled';
}

interface Invoice {
  id: string;
  assignedOrder: string;
  requestedOrder: string;
  amount: string;
  clientAmount?: string;
  issueDate?: string;
  dueDate: string;
  completedDate?: string;
  status: 'Paid' | 'Unpaid' | 'Overdue';
  engineerStatus: 'Paid' | 'Unpaid' | 'Overdue';
  clientStatus: 'Paid' | 'Unpaid' | 'Overdue';
  project?: Project;
  issuedMonth?: string;
  taxRate?: number;
  taxAmount?: number;
}

const INITIAL_INVOICES: Invoice[] = [];

export function Finance() {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const { projects: allProjects, tasks, addProject, updateProject, expenses, companySettings, currencies, addCurrency } = useApp();
  const { hasPermission } = useAuth();
  const getSymbol = (currency?: string) => {
    if (!currency) return '$';
    const c = currencies.find(curr => curr.code === currency || curr.code === (currency === 'Euro' ? 'EUR' : currency));
    return c ? c.symbol : '$';
  };
  
  const projects = useMemo(() => allProjects.filter(p => p.status === 'Completed'), [allProjects]);
  const [activeTab, setActiveTab] = useState<'overview' | 'transactions' | 'invoices' | 'client_invoices' | 'engineer_invoices' | 'bookkeeping' | 'tax' | 'commissions'>('overview');
  const parseTotalTime = (timeStr?: string) => {
    if (!timeStr) return 0;
    const hoursMatch = timeStr.match(/(\d+)h/);
    const minsMatch = timeStr.match(/(\d+)m/);
    const hours = hoursMatch ? parseInt(hoursMatch[1]) : 0;
    const mins = minsMatch ? parseInt(minsMatch[1]) : 0;
    return hours + mins / 60;
  };

  const transactions = useMemo(() => {
    const projectTransactions: Transaction[] = [];
    
    projects.forEach(p => {
      const hours = parseTotalTime(p.totalTime);
      
      // Internal/Engineer rates (Expenses)
      const hourlyTotal = (p.hourlyRate || 0) * hours;
      const internalAmount = p.totalAmount && p.totalAmount > 0 ? p.totalAmount : 
        (hourlyTotal + (p.travelCost || 0) + (p.materialCost || 0) + (p.halfDayRate || 0) + (p.fullDayRate || 0) + (p.monthlyRate || 0));
      
      // Client rates (Revenue)
      const clientHourlyTotal = (p.clientHourlyRate || 0) * hours;
      const clientAmount = p.clientTotalAmount && p.clientTotalAmount > 0 ? p.clientTotalAmount : 
        (clientHourlyTotal + (p.clientTravelCost || 0) + (p.clientMaterialCost || 0) + (p.clientHalfDayRate || 0) + (p.clientFullDayRate || 0) + (p.clientMonthlyRate || 0));

      const symbol = getSymbol(p.currency);
      
      // Third-party commissions
      (p.commissions || []).forEach(c => {
        projectTransactions.push({
          id: `TX-COMM-${c.id}`,
          invoiceId: p.ticketId || p.id,
          description: `Commission - ${c.vendorName} (${p.name})`,
          category: 'Vendor Commission',
          amount: `${symbol}${c.amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
          type: 'Expense',
          date: p.issueDate || new Date().toISOString().split('T')[0],
          status: c.status === 'Paid' ? 'Completed' : 'Pending'
        });
      });

      // Legacy commission support
      if (p.thirdPartyName && (!p.commissions || p.commissions.length === 0)) {
        const clientAmt = p.clientTotalAmount || p.totalAmount || 0;
        const commAmt = p.thirdPartyCommissionAmount || (clientAmt * ((p.thirdPartyCommissionRate || 0) / 100));
        projectTransactions.push({
          id: `TX-COMM-LEGACY-${p.id}`,
          invoiceId: p.ticketId || p.id,
          description: `Commission - ${p.thirdPartyName} (${p.name})`,
          category: 'Vendor Commission',
          amount: `${symbol}${commAmt.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
          type: 'Expense',
          date: p.issueDate || new Date().toISOString().split('T')[0],
          status: p.thirdPartyStatus === 'Paid' ? 'Completed' : 'Pending'
        });
      }

      // Income transaction (Client Payment)
      projectTransactions.push({
        id: `TX-IN-${p.ticketId || p.id}`,
        invoiceId: p.ticketId || p.id,
        description: `Client Payment - ${p.client || p.name}`,
        category: 'Project Revenue',
        amount: `${symbol}${clientAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
        type: 'Income',
        date: p.issueDate || new Date().toISOString().split('T')[0],
        status: (p.clientInvoiceStatus === 'Paid' || (!p.clientInvoiceStatus && p.clientStatus === 'Completed')) ? 'Completed' : 
                (p.clientInvoiceStatus === 'Overdue' || (!p.clientInvoiceStatus && p.clientStatus === 'Cancelled')) ? 'Cancelled' : 'Pending'
      });

      // Expense transaction (Engineer Payout)
      projectTransactions.push({
        id: `TX-EX-${p.ticketId || p.id}`,
        invoiceId: p.ticketId || p.id,
        description: `Engineer Payout - ${p.assignedTo || 'Unassigned'}`,
        category: 'Engineer Payout',
        amount: `${symbol}${internalAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
        type: 'Expense',
        date: p.issueDate || new Date().toISOString().split('T')[0],
        status: (p.engineerInvoiceStatus === 'Paid' || (!p.engineerInvoiceStatus && p.status === 'Completed')) ? 'Completed' : 
                (p.engineerInvoiceStatus === 'Overdue' || (!p.engineerInvoiceStatus && p.status === 'Cancelled')) ? 'Cancelled' : 'Pending'
      });
    });

    // Add Company Expenses (from the expenses collection)
    expenses.forEach(e => {
      projectTransactions.push({
        id: `TX-EXP-${e.id}`,
        invoiceId: e.reference || e.id,
        description: e.description,
        category: e.category,
        amount: `$${e.amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
        type: 'Expense',
        date: e.date,
        status: e.status === 'Approved' ? 'Completed' : e.status === 'Rejected' ? 'Cancelled' : 'Pending'
      });
    });

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


  // Map projects to invoices for the Finance page
  const invoices = useMemo(() => {
    return projects.map(project => {
      const calculateAmounts = (p: Project) => {
        const hours = parseTotalTime(p.totalTime);
        
        // Internal/Engineer rates
        const hourlyTotal = (p.hourlyRate || 0) * hours;
        const calculated = hourlyTotal + (p.travelCost || 0) + (p.materialCost || 0) + 
               (p.halfDayRate || 0) + (p.fullDayRate || 0) + (p.monthlyRate || 0);
        const internalAmount = p.totalAmount && p.totalAmount > 0 ? p.totalAmount : calculated;

        // Client rates
        const clientHourlyTotal = (p.clientHourlyRate || 0) * hours;
        const clientCalculated = clientHourlyTotal + (p.clientTravelCost || 0) + (p.clientMaterialCost || 0) + 
               (p.clientHalfDayRate || 0) + (p.clientFullDayRate || 0) + (p.clientMonthlyRate || 0);
        const clientAmount = p.clientTotalAmount && p.clientTotalAmount > 0 ? p.clientTotalAmount : clientCalculated;
        
        return { internalAmount, clientAmount };
      };

      const { internalAmount, clientAmount } = calculateAmounts(project);
      const symbol = getSymbol(project.currency);
      
      return {
        id: project.ticketId || project.id,
        assignedOrder: project.assignedTo || 'Unassigned',
        requestedOrder: project.client || project.name,
        amount: `${symbol}${internalAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
        clientAmount: `${symbol}${clientAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
        issueDate: project.issueDate || new Date().toISOString().split('T')[0],
        dueDate: project.deadline,
        completedDate: project.completedDate,
        engineerStatus: project.engineerInvoiceStatus || (project.status === 'Completed' ? 'Paid' : project.status === 'Cancelled' ? 'Overdue' : 'Unpaid'),
        clientStatus: project.clientInvoiceStatus || (project.clientStatus === 'Completed' ? 'Paid' : project.clientStatus === 'Cancelled' ? 'Overdue' : 'Unpaid'),
        status: (activeTab === 'client_invoices' ? (project.clientInvoiceStatus || (project.clientStatus === 'Completed' ? 'Paid' : project.clientStatus === 'Cancelled' ? 'Overdue' : 'Unpaid')) : (project.engineerInvoiceStatus || (project.status === 'Completed' ? 'Paid' : project.status === 'Cancelled' ? 'Overdue' : 'Unpaid'))) as 'Paid' | 'Unpaid' | 'Overdue',
        project: project, // Keep reference
        issuedMonth: project.issuedMonth
      };
    });
  }, [projects, activeTab]);

  const allCommissions = useMemo(() => {
    const list: any[] = [];
    projects.forEach(p => {
      // Legacy single commission
      if (p.thirdPartyName && (!p.commissions || p.commissions.length === 0)) {
        const clientAmt = p.clientTotalAmount || p.totalAmount || 0;
        const commAmt = p.thirdPartyCommissionAmount || (clientAmt * ((p.thirdPartyCommissionRate || 0) / 100));
        list.push({
          id: `LEGACY-${p.id}`,
          projectId: p.id,
          projectTicket: p.ticketId || p.id,
          projectName: p.name,
          client: p.client,
          vendorName: p.thirdPartyName,
          rate: p.thirdPartyCommissionRate || 0,
          amount: commAmt,
          status: p.thirdPartyStatus || 'Unpaid',
          project: p,
          isLegacy: true
        });
      }
      
      // Dynamic commissions
      (p.commissions || []).forEach(c => {
        list.push({
          ...c,
          projectId: p.id,
          projectTicket: p.ticketId || p.id,
          projectName: p.name,
          client: p.client,
          project: p
        });
      });
    });
    return list;
  }, [projects]);

  const toggleCommissionStatus = async (projectId: string, commissionId: string, currentStatus: string) => {
    if (isSubmitting) return;
    const project = projects.find(p => p.id === projectId);
    if (!project) return;
    
    setIsSubmitting(true);
    try {
      const newStatus = currentStatus === 'Paid' ? 'Unpaid' : 'Paid';
      
      if (project.commissions && !commissionId.startsWith('LEGACY-')) {
        const newComms = project.commissions.map(c => 
          c.id === commissionId ? { ...c, status: newStatus as any } : c
        );
        await updateProject(projectId, { commissions: newComms });
      } else {
        // legacy or manually set legacy
        await updateProject(projectId, { thirdPartyStatus: newStatus as any });
        
        // Also update in commissions array if exists
        if (project.commissions) {
           const newComms = project.commissions.map(c => 
             c.id === commissionId ? { ...c, status: newStatus as any } : c
           );
           await updateProject(projectId, { commissions: newComms });
        }
      }
      toast.success(`Commission marked as ${newStatus}`);
    } catch (error) {
      toast.error('Failed to update commission status');
    } finally {
      setIsSubmitting(false);
    }
  };

  const [searchQuery, setSearchQuery] = useState('');
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [filterType, setFilterType] = useState('All');
  const [filterCategory, setFilterCategory] = useState('All');
  const [filterStatus, setFilterStatus] = useState('All');
  const filterRef = React.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 stats = useMemo(() => {
    let totalRevenue = 0;
    let totalExpenses = 0;
    let totalCommissions = 0;
    let pendingAmount = 0;
    let pendingCount = 0;
    
    const now = new Date();
    const currentMonthStr = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`;
    let currentMonthInflow = 0;
    let currentMonthOutflow = 0;

    // Monthly data for chart (last 6 months)
    const monthlyMap = new Map<string, { revenue: number, expenses: number }>();
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const mStr = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}`;
      monthlyMap.set(mStr, { revenue: 0, expenses: 0 });
    }

    projects.forEach(p => {
      const hours = parseTotalTime(p.totalTime);
      
      // Internal/Engineer rates (Expenses)
      const hourlyTotal = (p.hourlyRate || 0) * hours;
      const internalAmount = p.totalAmount && p.totalAmount > 0 ? p.totalAmount : 
        (hourlyTotal + (p.travelCost || 0) + (p.materialCost || 0) + (p.halfDayRate || 0) + (p.fullDayRate || 0) + (p.monthlyRate || 0));
      
      // Client rates (Revenue)
      const clientHourlyTotal = (p.clientHourlyRate || 0) * hours;
      const clientAmount = p.clientTotalAmount && p.clientTotalAmount > 0 ? p.clientTotalAmount : 
        (clientHourlyTotal + (p.clientTravelCost || 0) + (p.clientMaterialCost || 0) + (p.clientHalfDayRate || 0) + (p.clientFullDayRate || 0) + (p.clientMonthlyRate || 0));

      // Third-party commissions
      const pComms = (p.commissions || []).reduce((acc, c) => acc + (c.amount || 0), 0);
      
      // Handle legacy commission amount in stats
      let legacyComm = 0;
      if (p.thirdPartyName && (!p.commissions || p.commissions.length === 0)) {
        const clientAmt = p.clientTotalAmount || p.totalAmount || 0;
        legacyComm = p.thirdPartyCommissionAmount || (clientAmt * ((p.thirdPartyCommissionRate || 0) / 100));
      }
      
      const totalPComms = pComms + legacyComm;
      totalCommissions += totalPComms;

      totalRevenue += clientAmount;
      totalExpenses += internalAmount + totalPComms;

      const pMonth = p.issuedMonth || (p.issueDate ? p.issueDate.substring(0, 7) : '');
      
      if (pMonth === currentMonthStr) {
        const isClientPaid = p.clientInvoiceStatus === 'Paid' || (!p.clientInvoiceStatus && p.clientStatus === 'Completed');
        const isEngineerPaid = p.engineerInvoiceStatus === 'Paid' || (!p.engineerInvoiceStatus && p.status === 'Completed');
        
        // Check if commissions are paid for cash flow
        const isCommPaid = (p.commissions?.every(c => c.status === 'Paid') ?? true) && (p.thirdPartyStatus === 'Paid' || !p.thirdPartyName);

        if (isClientPaid) currentMonthInflow += clientAmount;
        if (isEngineerPaid) currentMonthOutflow += internalAmount;
        if (isCommPaid) currentMonthOutflow += totalPComms;
      }

      if (monthlyMap.has(pMonth)) {
        const mData = monthlyMap.get(pMonth)!;
        mData.revenue += clientAmount;
        mData.expenses += (internalAmount + totalPComms);
      }

      const isClientPaid = p.clientInvoiceStatus === 'Paid' || (!p.clientInvoiceStatus && p.clientStatus === 'Completed');
      const isClientCancelled = p.clientInvoiceStatus === 'Overdue' || (!p.clientInvoiceStatus && p.clientStatus === 'Cancelled');
      
      if (!isClientPaid && !isClientCancelled) {
        pendingAmount += clientAmount;
        pendingCount++;
      }
    });

    // Add Company Expenses to totals
    expenses.forEach(e => {
      if (e.status === 'Approved') {
        totalExpenses += e.amount;
      }
      
      const eMonth = (e.date || '').substring(0, 7);
      if (eMonth === currentMonthStr) {
        if (e.status === 'Approved') {
          currentMonthOutflow += e.amount;
        }
      }

      if (monthlyMap.has(eMonth)) {
        const mData = monthlyMap.get(eMonth)!;
        if (e.status === 'Approved') {
          mData.expenses += e.amount;
        }
      }
    });

    const netProfit = totalRevenue - totalExpenses;
    const margin = totalRevenue > 0 ? (netProfit / totalRevenue) * 100 : 0;

    const chartData = Array.from(monthlyMap.entries()).map(([month, data]) => {
      const parts = (month || '').split('-');
      if (parts.length < 2) return { month: month, revenue: data.revenue, expenses: data.expenses };
      const [year, m] = parts;
      const date = new Date(parseInt(year), parseInt(m) - 1);
      return {
        month: date.toLocaleString('default', { month: 'short' }),
        revenue: data.revenue,
        expenses: data.expenses
      };
    });

    return {
      totalRevenue,
      totalExpenses,
      totalCommissions,
      netProfit,
      margin,
      pendingAmount,
      pendingCount,
      chartData,
      currentMonthInflow,
      currentMonthOutflow
    };
  }, [projects, expenses]);
  const [showAllInvoices, setShowAllInvoices] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isInvoiceModalOpen, setIsInvoiceModalOpen] = useState(false);
  const [isCommissionModalOpen, setIsCommissionModalOpen] = useState(false);
  const [commissionFormData, setCommissionFormData] = useState({
    invoiceId: '',
    fromName: '',
    fromEmail: '',
    fromPhone: '',
    fromAddress: '',
    billToName: '',
    billToEmail: '',
    billToPhone: '',
    billToAddress: '',
    description: '',
    projectRef: '',
    amount: 0,
    date: new Date().toISOString().split('T')[0],
    currency: 'USD'
  });
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editingProject, setEditingProject] = useState<Project | null>(null);
  const [newInvoice, setNewInvoice] = useState<Partial<Invoice>>({
    assignedOrder: '',
    requestedOrder: '',
    amount: '',
    issueDate: new Date().toISOString().split('T')[0],
    dueDate: '',
    status: 'Unpaid'
  });

  useEffect(() => {
    const create = searchParams.get('create');
    if (create === 'true') {
      setIsInvoiceModalOpen(true);
      const newParams = new URLSearchParams(searchParams);
      newParams.delete('create');
      setSearchParams(newParams, { replace: true });
    }
  }, [searchParams, setSearchParams]);

  const handleAddInvoice = () => {
    toast.info('Create new projects in the Projects page to generate invoices');
  };

  const handleCreateInvoice = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;
    
    setIsSubmitting(true);
    try {
      const id = `PRJ-${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}`;
      const newPrj: Project = {
        id,
        name: newInvoice.requestedOrder || 'Manual Invoice',
        client: newInvoice.requestedOrder || 'N/A',
        assignedTo: newInvoice.assignedOrder || 'Unassigned',
        status: newInvoice.status === 'Paid' ? 'Completed' : 'In Progress',
        engineerInvoiceStatus: (newInvoice.status as any) || 'Unpaid',
        clientInvoiceStatus: (newInvoice.status as any) || 'Unpaid',
        team: 1,
        deadline: newInvoice.dueDate || '',
        issueDate: newInvoice.issueDate || new Date().toISOString().split('T')[0],
        totalAmount: parseFloat(newInvoice.amount || '0'),
        clientTotalAmount: parseFloat(newInvoice.amount || '0'),
        currency: companySettings.currency || 'USD',
        ticketId: `INV-${new Date().getFullYear()}-${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`
      };

      await addProject(newPrj);
      toast.success('Invoice generated successfully');
      setIsInvoiceModalOpen(false);
      setNewInvoice({
        assignedOrder: '',
        requestedOrder: '',
        amount: '',
        issueDate: new Date().toISOString().split('T')[0],
        dueDate: '',
        status: 'Unpaid'
      });
    } catch (error) {
      toast.error('Failed to generate invoice');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDownloadInvoice = (invoice: Invoice, isClientOverride?: boolean) => {
    const isClient = isClientOverride !== undefined ? isClientOverride : activeTab === 'client_invoices';
    const project = invoice.project;
    
    const doc = new jsPDF();
    
    // Header
    doc.setFillColor(249, 250, 251);
    doc.rect(0, 0, 210, 45, 'F');
    
    doc.setFontSize(24);
    doc.setTextColor(15, 23, 42); // slate-900
    doc.text(isClient ? 'CLIENT INVOICE' : 'ENGINEER INVOICE', 20, 28);
    
    doc.setFontSize(10);
    doc.setTextColor(100, 116, 139); // slate-500
    doc.text(`Invoice ID: #${invoice.id}`, 20, 36);
    
    // Status Badge in PDF
    const status = isClient ? invoice.clientStatus : invoice.engineerStatus;
    doc.setFontSize(9);
    doc.setFont('helvetica', 'bold');
    if (status === 'Paid') {
      doc.setFillColor(34, 197, 94); // green-500
      doc.setTextColor(255, 255, 255);
    } else if (status === 'Overdue') {
      doc.setFillColor(239, 68, 68); // red-500
      doc.setTextColor(255, 255, 255);
    } else {
      doc.setFillColor(234, 179, 8); // yellow-500
      doc.setTextColor(255, 255, 255);
    }
    doc.rect(20, 40, 25, 6, 'F');
    doc.text(status.toUpperCase(), 32.5, 44.5, { align: 'center' });
    doc.setTextColor(15, 23, 42); // Reset to dark
    
    // Dates
    doc.setFontSize(10);
    doc.setTextColor(15, 23, 42);
    doc.setFont('helvetica', 'bold');
    doc.text('Date Issued:', 140, 20);
    doc.setFont('helvetica', 'normal');
    doc.text(invoice.issueDate || 'N/A', 170, 20);
    
    doc.setFont('helvetica', 'bold');
    doc.text('Issued Month:', 140, 27);
    doc.setFont('helvetica', 'normal');
    const formatMonth = (m: string) => {
      if (!m) return 'N/A';
      if (m.includes('-')) {
        const [year, month] = m.split('-');
        const date = new Date(parseInt(year), parseInt(month) - 1);
        return date.toLocaleString('default', { month: 'long', year: 'numeric' });
      }
      return m;
    };
    const issueMonth = formatMonth(invoice.issuedMonth || (invoice.issueDate ? invoice.issueDate.substring(0, 7) : ''));
    doc.text(issueMonth, 170, 27);
    
    doc.setFont('helvetica', 'bold');
    doc.text('Due Date:', 140, 34);
    doc.setFont('helvetica', 'normal');
    doc.text(invoice.dueDate || 'N/A', 170, 34);

    // From / To
    doc.setFontSize(11);
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(100, 116, 139);
    doc.text(isClient ? 'FROM (COMPANY)' : 'FROM (ENGINEER)', 20, 60);
    doc.text('BILL TO (CLIENT)', 110, 60);
    
    doc.setFontSize(10);
    doc.setTextColor(15, 23, 42);
    
    // From details
    let fromY = 68;
    doc.setFont('helvetica', 'bold');
    if (isClient) {
      doc.text(project?.companyName || 'Your Company Name', 20, fromY);
      doc.setFont('helvetica', 'normal');
      fromY += 5;
      doc.text(project?.companyEmail || 'billing@company.com', 20, fromY);
      fromY += 5;
      doc.text(project?.companyPhone || '+1 555 0123', 20, fromY);
      fromY += 5;
      if (project?.companyAddress) {
        const splitCompanyAddress = doc.splitTextToSize(project.companyAddress, 80);
        doc.text(splitCompanyAddress, 20, fromY);
        fromY += (splitCompanyAddress.length * 5);
      }
    } else {
      doc.text(invoice.assignedOrder || 'N/A', 20, fromY);
      doc.setFont('helvetica', 'normal');
      fromY += 5;
      if (project?.assignedEmail) {
        doc.text(project.assignedEmail, 20, fromY);
        fromY += 5;
      } else if (project?.email) {
        // Fallback to general email if assignedEmail is missing
        doc.text(project.email, 20, fromY);
        fromY += 5;
      }
      if (project?.assignedContactNumber) {
        doc.text(project.assignedContactNumber, 20, fromY);
        fromY += 5;
      }
    }
    if (project?.address) {
      const splitAddress = doc.splitTextToSize(project.address, 80);
      doc.text(splitAddress, 20, fromY);
    }
    
    // To details
    let toY = 68;
    doc.setFont('helvetica', 'bold');
    if (isClient) {
      doc.text(invoice.requestedOrder || 'N/A', 110, toY);
      doc.setFont('helvetica', 'normal');
      toY += 5;
      
      if (project?.personName) {
        doc.text(`Attn: ${project.personName}`, 110, toY);
        toY += 5;
      }
      
      if (project?.email) {
        doc.text(project.email, 110, toY);
        toY += 5;
      }
      
      if (project?.contactNumber) {
        doc.text(project.contactNumber, 110, toY);
        toY += 5;
      }
      
      if (project?.clientAddress) {
        const splitClientAddress = doc.splitTextToSize(project.clientAddress, 80);
        doc.text(splitClientAddress, 110, toY);
      }
    } else {
      // Engineer billing the company
      doc.text(project?.companyName || 'Your Company Name', 110, toY);
      doc.setFont('helvetica', 'normal');
      toY += 5;
      doc.text(project?.companyEmail || 'billing@company.com', 110, toY);
      toY += 5;
      doc.text(project?.companyPhone || '+1 555 0123', 110, toY);
      toY += 5;
      if (project?.companyAddress) {
        const splitCompanyAddress = doc.splitTextToSize(project.companyAddress, 80);
        doc.text(splitCompanyAddress, 110, toY);
      }
    }

    // Items Table Header
    doc.setFillColor(249, 250, 251);
    doc.rect(20, 110, 170, 12, 'F');
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(100, 116, 139);
    doc.text('DESCRIPTION', 25, 118);
    doc.text('QTY/TIME', 110, 118);
    doc.text('RATE', 140, 118);
    doc.text('AMOUNT', 170, 118);
    
    // Items
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(15, 23, 42);
    let itemY = 130;
    const symbol = project?.currency === 'Euro' ? '€' : project?.currency === 'GBP' ? '£' : '$';

    const addItem = (desc: string, qty: string, rate: number, amount: number) => {
      if (amount > 0) {
        doc.text(desc, 25, itemY);
        doc.text(qty, 110, itemY);
        doc.text(`${symbol}${rate.toLocaleString(undefined, {minimumFractionDigits: 2})}`, 140, itemY);
        doc.text(`${symbol}${amount.toLocaleString(undefined, {minimumFractionDigits: 2})}`, 170, itemY);
        itemY += 8;
      }
    };

    if (project) {
      const hours = parseTotalTime(project.totalTime);
      const hRate = isClient ? (project.clientHourlyRate || 0) : (project.hourlyRate || 0);
      addItem('Professional Services (Hourly)', project.totalTime || '0h', hRate, hRate * hours);
      
      const hdRate = isClient ? (project.clientHalfDayRate || 0) : (project.halfDayRate || 0);
      addItem('Professional Services (Half Day)', '1', hdRate, hdRate);
      
      const fdRate = isClient ? (project.clientFullDayRate || 0) : (project.fullDayRate || 0);
      addItem('Professional Services (Full Day)', '1', fdRate, fdRate);
      
      const mRate = isClient ? (project.clientMonthlyRate || 0) : (project.monthlyRate || 0);
      addItem('Professional Services (Monthly)', '1', mRate, mRate);
      
      const tCost = isClient ? (project.clientTravelCost || 0) : (project.travelCost || 0);
      addItem('Travel Expenses', '1', tCost, tCost);
      
      const matCost = isClient ? (project.clientMaterialCost || 0) : (project.materialCost || 0);
      addItem('Material & Equipment', '1', matCost, matCost);
    } else {
      // Fallback for manual invoices
      const fallbackSymbol = getSymbol(invoice.project?.currency || 'USD');
      doc.text(invoice.requestedOrder, 25, itemY);
      doc.text(isClient ? invoice.clientAmount : invoice.amount, 170, itemY);
      itemY += 8;
    }
    
    // Total
    doc.setDrawColor(226, 232, 240); // slate-200
    doc.line(20, itemY + 5, 190, itemY + 5);
    
    doc.setFontSize(10);
    doc.setFont('helvetica', 'normal');
    doc.text('Subtotal', 110, itemY + 12);
    
    const subtotal = isClient ? 
      ((project?.clientHourlyRate || 0) * parseTotalTime(project?.totalTime) + (project?.clientHalfDayRate || 0) + (project?.clientFullDayRate || 0) + (project?.clientMonthlyRate || 0) + (project?.clientTravelCost || 0) + (project?.clientMaterialCost || 0)) :
      ((project?.hourlyRate || 0) * parseTotalTime(project?.totalTime) + (project?.halfDayRate || 0) + (project?.fullDayRate || 0) + (project?.monthlyRate || 0) + (project?.travelCost || 0) + (project?.materialCost || 0));
    
    doc.text(`${symbol}${subtotal.toLocaleString(undefined, {minimumFractionDigits: 2})}`, 170, itemY + 12);

    if (project?.taxAmount && project.taxAmount > 0) {
      doc.text(`Tax (${project.taxRate || 0}%)`, 110, itemY + 18);
      doc.text(`${symbol}${project.taxAmount.toLocaleString(undefined, {minimumFractionDigits: 2})}`, 170, itemY + 18);
      itemY += 6;
    }

    doc.setFontSize(14);
    doc.setFont('helvetica', 'bold');
    doc.text('Total Amount', 110, itemY + 25);
    doc.text(isClient ? invoice.clientAmount : invoice.amount, 170, itemY + 25);
    
    // Footer
    doc.setFontSize(9);
    doc.setTextColor(148, 163, 184); // slate-400
    doc.text('Thank you for your business!', 105, 275, { align: 'center' });
    doc.text('If you have any questions, please contact us.', 105, 280, { align: 'center' });
    
    doc.save(`Invoice_${invoice.id}.pdf`);
    toast.success(`Invoice ${invoice.id} downloaded as PDF`);
  };

  const handleExportTransactionsPDF = () => {
    const doc = new jsPDF();
    
    doc.setFontSize(18);
    doc.text('Transactions Report', 14, 20);
    doc.setFontSize(10);
    doc.text(`Generated on: ${new Date().toLocaleString()}`, 14, 28);

    const headers = [['TX ID', 'Invoice ID', 'Description', 'Category', 'Amount', 'Type', 'Date', 'Status']];
    const data = filteredTransactions.map(tx => [
      tx.id,
      tx.invoiceId,
      tx.description,
      tx.category,
      tx.amount,
      tx.type,
      tx.date,
      tx.status
    ]);

    autoTable(doc, {
      head: headers,
      body: data,
      startY: 40,
      theme: 'striped',
      headStyles: { fillColor: [15, 23, 42] }
    });

    doc.save(`transactions_report_${new Date().toISOString().split('T')[0]}.pdf`);
    toast.success('Transactions report exported as PDF');
  };

  const handleExportInvoicesPDF = () => {
    const isAll = activeTab === 'invoices';
    const isEngineer = activeTab === 'engineer_invoices';
    const isClient = activeTab === 'client_invoices';
    
    const doc = new jsPDF('l', 'mm', 'a4'); // Landscape orientation
    
    doc.setFontSize(18);
    doc.text('Invoices Report', 14, 20);
    doc.setFontSize(10);
    doc.text(`Generated on: ${new Date().toLocaleString()}`, 14, 28);
    doc.text(`View: ${isAll ? 'All Invoices' : isEngineer ? 'Engineer Invoices' : 'Client Invoices'}`, 14, 34);

    const headers = [
      'ID', 
      ...(isClient ? [] : ['Assigned']), 
      ...(isEngineer ? [] : ['Requested']),
      ...(isAll ? ['Eng. Amt', 'Cli. Amt'] : [activeTab === 'client_invoices' ? 'Cli. Amt' : 'Eng. Amt']),
      'Issue Date',
      'Month',
      'Due Date', 
      ...(isAll ? ['Eng. Status', 'Cli. Status'] : ['Status'])
    ];

    const data = invoices.map(inv => [
      inv.id,
      ...(isClient ? [] : [inv.assignedOrder]),
      ...(isEngineer ? [] : [inv.requestedOrder]),
      ...(isAll ? [inv.amount, inv.clientAmount || '0'] : [activeTab === 'client_invoices' ? inv.clientAmount : inv.amount]),
      inv.issueDate || '',
      inv.issuedMonth ? (inv.issuedMonth.includes('-') ? new Date(parseInt(inv.issuedMonth.split('-')[0]), parseInt(inv.issuedMonth.split('-')[1]) - 1).toLocaleString('default', { month: 'short', year: 'numeric' }) : inv.issuedMonth) : '',
      inv.dueDate,
      ...(isAll ? [inv.engineerStatus, inv.clientStatus] : [inv.status])
    ]);

    autoTable(doc, {
      head: [headers],
      body: data,
      startY: 40,
      theme: 'grid',
      styles: { fontSize: 8 },
      headStyles: { fillColor: [15, 23, 42] }
    });

    doc.save(`invoices_report_${new Date().toISOString().split('T')[0]}.pdf`);
    toast.success('Invoices report exported as PDF');
  };

  const handleExportRowPDF = (invoice: Invoice) => {
    const doc = new jsPDF();
    
    doc.setFontSize(18);
    doc.text(`Invoice Report: ${invoice.id}`, 14, 20);
    doc.setFontSize(10);
    doc.text(`Generated on: ${new Date().toLocaleString()}`, 14, 28);

    const headers = [['Field', 'Value']];
    const data = [
      ['Invoice ID', invoice.id],
      ['Assigned Order', invoice.assignedOrder],
      ['Requested Order', invoice.requestedOrder],
      ['Engineer Amount', invoice.amount],
      ['Client Amount', invoice.clientAmount || '0'],
      ['Issue Date', invoice.issueDate || 'N/A'],
      ['Issued Month', invoice.issuedMonth ? (invoice.issuedMonth.includes('-') ? new Date(parseInt(invoice.issuedMonth.split('-')[0]), parseInt(invoice.issuedMonth.split('-')[1]) - 1).toLocaleString('default', { month: 'long', year: 'numeric' }) : invoice.issuedMonth) : 'N/A'],
      ['Due Date', invoice.dueDate || 'N/A'],
      ['Completed Date', invoice.completedDate || 'N/A'],
      ['Status', invoice.status]
    ];

    autoTable(doc, {
      head: headers,
      body: data,
      startY: 40,
      theme: 'striped',
      headStyles: { fillColor: [15, 23, 42] }
    });

    doc.save(`invoice_${invoice.id}_report.pdf`);
    toast.success(`Invoice ${invoice.id} report exported as PDF`);
  };

  const handleRecordExpense = () => {
    navigate('/expenses');
  };

  const handleEditInvoice = (invoice: Invoice) => {
    if (invoice.project) {
      // Ensure issueDate and company info are set if they were missing
      const projectWithDefaults = {
        ...invoice.project,
        issueDate: invoice.project.issueDate || invoice.issueDate || new Date().toISOString().split('T')[0],
        issuedMonth: invoice.project.issuedMonth || (invoice.project.issueDate || invoice.issueDate ? (invoice.project.issueDate || invoice.issueDate || '').substring(0, 7) : new Date().toISOString().substring(0, 7)),
        companyName: invoice.project.companyName || companySettings.name || 'Your Company Name',
        companyEmail: invoice.project.companyEmail || companySettings.email || 'billing@company.com',
        companyPhone: invoice.project.companyPhone || companySettings.phone || '+1 555 0123',
        companyAddress: invoice.project.companyAddress || companySettings.location || '123 Business Ave, Suite 100\nNew York, NY 10001'
      };
      setEditingProject(projectWithDefaults);
      setIsEditModalOpen(true);
    } else {
      toast.error('Cannot edit this invoice: No associated project found');
    }
  };

  const handleUpdateInvoice = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;
    if (editingProject) {
      setIsSubmitting(true);
      try {
        await updateProject(editingProject.id, editingProject);
        toast.success('Invoice updated successfully');
        setIsEditModalOpen(false);
        setEditingProject(null);
      } catch (error) {
        toast.error('Failed to update invoice');
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  const filteredTransactions = transactions.filter(t => {
    const matchesSearch = t.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      t.category.toLowerCase().includes(searchQuery.toLowerCase()) ||
      t.id.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesType = filterType === 'All' || t.type === filterType;
    const matchesCategory = filterCategory === 'All' || t.category === filterCategory;
    const matchesStatus = filterStatus === 'All' || t.status === filterStatus;
    
    return matchesSearch && matchesType && matchesCategory && matchesStatus;
  });

  return (
    <div className="space-y-6">
      {/* Edit Invoice Modal */}
      {isEditModalOpen && editingProject && (
        <div className="fixed inset-0 z-[100] flex items-start justify-center p-4 bg-background/80 backdrop-blur-sm overflow-y-auto">
          <div className={cn(
            "w-full rounded-xl border border-border bg-card shadow-2xl animate-in fade-in zoom-in duration-200 my-8",
            (activeTab === 'engineer_invoices' || activeTab === 'client_invoices') ? "max-w-3xl" : "max-w-md p-6"
          )}>
            {(activeTab === 'engineer_invoices' || activeTab === 'client_invoices') ? (
              <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">
                      {activeTab === 'client_invoices' ? 'CLIENT INVOICE' : 'ENGINEER INVOICE'}
                    </h2>
                    <p className="text-sm text-muted-foreground">#{editingProject.ticketId || editingProject.id}</p>
                  </div>
                  <div className="text-right">
                    <div className="flex items-center gap-2 mb-4 justify-end">
                      <button 
                        onClick={() => {
                          if (editingProject) {
                            const symbol = editingProject.currency === 'Euro' ? '€' : editingProject.currency === 'GBP' ? '£' : '$';
                            const hours = parseTotalTime(editingProject.totalTime);
                            
                            // Internal/Engineer rates
                            const hourlyTotal = (editingProject.hourlyRate || 0) * hours;
                            const calculated = hourlyTotal + (editingProject.travelCost || 0) + (editingProject.materialCost || 0) + 
                                   (editingProject.halfDayRate || 0) + (editingProject.fullDayRate || 0) + (editingProject.monthlyRate || 0);
                            const internalAmount = editingProject.totalAmount && editingProject.totalAmount > 0 ? editingProject.totalAmount : calculated;

                            // Client rates
                            const clientHourlyTotal = (editingProject.clientHourlyRate || 0) * hours;
                            const clientCalculated = clientHourlyTotal + (editingProject.clientTravelCost || 0) + (editingProject.clientMaterialCost || 0) + 
                                   (editingProject.clientHalfDayRate || 0) + (editingProject.clientFullDayRate || 0) + (editingProject.clientMonthlyRate || 0);
                            const clientAmount = editingProject.clientTotalAmount && editingProject.clientTotalAmount > 0 ? editingProject.clientTotalAmount : clientCalculated;

                            const invoiceToDownload: Invoice = {
                              id: editingProject.ticketId || editingProject.id,
                              assignedOrder: editingProject.assignedTo || 'Unassigned',
                              requestedOrder: editingProject.client || editingProject.name,
                              amount: `${symbol}${internalAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
                              clientAmount: `${symbol}${clientAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
                              issueDate: editingProject.issueDate || new Date().toISOString().split('T')[0],
                              dueDate: editingProject.deadline,
                              completedDate: editingProject.completedDate,
                              status: editingProject.status === 'Completed' ? 'Paid' : editingProject.status === 'Cancelled' ? 'Overdue' : 'Unpaid',
                              engineerStatus: editingProject.status === 'Completed' ? 'Paid' : editingProject.status === 'Cancelled' ? 'Overdue' : 'Unpaid',
                              clientStatus: editingProject.clientStatus === 'Completed' ? 'Paid' : editingProject.clientStatus === 'Cancelled' ? 'Overdue' : 'Unpaid',
                              project: editingProject,
                              issuedMonth: editingProject.issuedMonth
                            };
                            handleDownloadInvoice(invoiceToDownload);
                          }
                        }}
                        className="flex items-center gap-2 px-3 py-1.5 text-xs font-medium rounded-lg border border-border hover:bg-accent transition-colors text-primary"
                      >
                        <Download size={14} />
                        Download PDF
                      </button>
                      <button 
                        onClick={() => setIsEditModalOpen(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-sm font-bold">Date Issued</p>
                      <input 
                        type="date" 
                        value={editingProject.issueDate || ''}
                        onChange={(e) => setEditingProject({...editingProject, issueDate: e.target.value})}
                        className="text-sm text-muted-foreground bg-transparent border-none p-0 focus:ring-0 text-right w-full"
                      />
                    </div>
                    <div className="space-y-1">
                      <p className="text-sm font-bold">Issued Month</p>
                      <input 
                        type="month" 
                        value={editingProject.issuedMonth || ''}
                        onChange={(e) => setEditingProject({...editingProject, issuedMonth: e.target.value})}
                        className="text-sm text-muted-foreground bg-transparent border-none p-0 focus:ring-0 text-right w-full"
                      />
                    </div>
                  </div>
                </div>

                {/* Billing Info */}
                <div className="grid grid-cols-2 gap-12 border-t border-b border-border py-8">
                  <div className="space-y-3">
                    <h3 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                      {activeTab === 'client_invoices' ? 'From (Company)' : 'From (Engineer)'}
                    </h3>
                    <div className="space-y-2">
                      <input 
                        type="text" 
                        value={activeTab === 'client_invoices' ? (editingProject.companyName || '') : (editingProject.assignedTo || '')}
                        onChange={(e) => {
                          if (activeTab === 'engineer_invoices') {
                            setEditingProject({...editingProject, assignedTo: e.target.value});
                          } else {
                            setEditingProject({...editingProject, companyName: e.target.value});
                          }
                        }}
                        className="w-full font-bold bg-transparent border-none p-0 focus:ring-0 text-lg"
                        placeholder={activeTab === 'client_invoices' ? 'Company Name' : 'Engineer Name'}
                      />
                      {activeTab === 'engineer_invoices' ? (
                        <>
                          <input 
                            type="email" 
                            value={editingProject.assignedEmail || ''}
                            onChange={(e) => setEditingProject({...editingProject, assignedEmail: e.target.value})}
                            className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                            placeholder="engineer@example.com"
                          />
                          <input 
                            type="text" 
                            value={editingProject.assignedContactNumber || ''}
                            onChange={(e) => setEditingProject({...editingProject, assignedContactNumber: e.target.value})}
                            className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                            placeholder="Engineer Contact"
                          />
                        </>
                      ) : (
                        <>
                          <input 
                            type="email" 
                            value={editingProject.companyEmail || ''}
                            onChange={(e) => setEditingProject({...editingProject, companyEmail: e.target.value})}
                            className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                            placeholder="billing@company.com"
                          />
                          <input 
                            type="text" 
                            value={editingProject.companyPhone || ''}
                            onChange={(e) => setEditingProject({...editingProject, companyPhone: e.target.value})}
                            className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                            placeholder="Company Contact"
                          />
                        </>
                      )}
                      <textarea 
                        value={activeTab === 'client_invoices' ? (editingProject.companyAddress || '') : (editingProject.address || '')}
                        onChange={(e) => {
                          if (activeTab === 'client_invoices') {
                            setEditingProject({...editingProject, companyAddress: e.target.value});
                          } else {
                            setEditingProject({...editingProject, address: e.target.value});
                          }
                        }}
                        className="w-full text-xs bg-transparent border-none p-0 focus:ring-0 text-muted-foreground resize-none"
                        placeholder={activeTab === 'client_invoices' ? 'Company Address' : 'Sender Address'}
                        rows={2}
                      />
                    </div>
                  </div>
                  <div className="space-y-3">
                    <h3 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                      {activeTab === 'client_invoices' ? 'Bill To (Client)' : 'Bill To (Company)'}
                    </h3>
                    <div className="space-y-2">
                      {activeTab === 'client_invoices' ? (
                        <>
                          <input 
                            type="text" 
                            value={editingProject.client || ''}
                            onChange={(e) => setEditingProject({...editingProject, client: e.target.value})}
                            className="w-full font-bold bg-transparent border-none p-0 focus:ring-0 text-lg"
                            placeholder="Client Name"
                          />
                          <input 
                            type="text" 
                            value={editingProject.personName || ''}
                            onChange={(e) => setEditingProject({...editingProject, personName: e.target.value})}
                            className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                            placeholder="Contact Person"
                          />
                          <input 
                            type="email" 
                            value={editingProject.email || ''}
                            onChange={(e) => setEditingProject({...editingProject, email: e.target.value})}
                            className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                            placeholder="Client Email"
                          />
                          <input 
                            type="text" 
                            value={editingProject.contactNumber || ''}
                            onChange={(e) => setEditingProject({...editingProject, contactNumber: e.target.value})}
                            className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                            placeholder="Client Contact"
                          />
                          <textarea 
                            value={editingProject.clientAddress || ''}
                            onChange={(e) => setEditingProject({...editingProject, clientAddress: e.target.value})}
                            className="w-full text-xs bg-transparent border-none p-0 focus:ring-0 text-muted-foreground resize-none"
                            placeholder="Client Address"
                            rows={2}
                          />
                        </>
                      ) : (
                        <>
                          <input 
                            type="text" 
                            value={editingProject.companyName || ''}
                            onChange={(e) => setEditingProject({...editingProject, companyName: e.target.value})}
                            className="w-full font-bold bg-transparent border-none p-0 focus:ring-0 text-lg"
                            placeholder="Company Name"
                          />
                          <input 
                            type="email" 
                            value={editingProject.companyEmail || ''}
                            onChange={(e) => setEditingProject({...editingProject, companyEmail: e.target.value})}
                            className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                            placeholder="billing@company.com"
                          />
                          <input 
                            type="text" 
                            value={editingProject.companyPhone || ''}
                            onChange={(e) => setEditingProject({...editingProject, companyPhone: e.target.value})}
                            className="w-full text-sm bg-transparent border-none p-0 focus:ring-0 text-muted-foreground"
                            placeholder="Company Contact"
                          />
                          <textarea 
                            value={editingProject.companyAddress || ''}
                            onChange={(e) => setEditingProject({...editingProject, companyAddress: e.target.value})}
                            className="w-full text-xs bg-transparent border-none p-0 focus:ring-0 text-muted-foreground resize-none"
                            placeholder="Company Address"
                            rows={2}
                          />
                        </>
                      )}
                    </div>
                  </div>
                </div>

                {/* Invoice Items Table */}
                <div className="space-y-4">
                  <div className="grid grid-cols-12 gap-4 pb-2 border-b border-border text-xs font-bold uppercase tracking-wider text-muted-foreground">
                    <div className="col-span-6">Description</div>
                    <div className="col-span-2 text-center">Quantity/Time</div>
                    <div className="col-span-2 text-right">Rate</div>
                    <div className="col-span-2 text-right">Amount</div>
                  </div>

                  {/* Hourly Rate Row */}
                  <div className="grid grid-cols-12 gap-4 items-center py-2 border-b border-border/50">
                    <div className="col-span-6 text-sm font-medium">Professional Services (Hourly)</div>
                    <div className="col-span-2">
                      <input 
                        type="text" 
                        value={editingProject.totalTime || '0h'}
                        onChange={(e) => setEditingProject({...editingProject, totalTime: e.target.value})}
                        className="w-full text-center text-sm bg-transparent border-none p-0 focus:ring-0"
                      />
                    </div>
                    <div className="col-span-2">
                      <input 
                        type="number" 
                        value={activeTab === 'client_invoices' ? (editingProject.clientHourlyRate || 0) : (editingProject.hourlyRate || 0)}
                        onChange={(e) => {
                          const val = parseFloat(e.target.value) || 0;
                          if (activeTab === 'client_invoices') {
                            setEditingProject({...editingProject, clientHourlyRate: val});
                          } else {
                            setEditingProject({...editingProject, hourlyRate: val});
                          }
                        }}
                        className="w-full text-right text-sm bg-transparent border-none p-0 focus:ring-0"
                      />
                    </div>
                    <div className="col-span-2 text-right text-sm font-medium">
                      {((activeTab === 'client_invoices' ? (editingProject.clientHourlyRate || 0) : (editingProject.hourlyRate || 0)) * parseTotalTime(editingProject.totalTime)).toFixed(2)}
                    </div>
                  </div>

                  {/* Half Day Rate Row */}
                  <div className="grid grid-cols-12 gap-4 items-center py-2 border-b border-border/50">
                    <div className="col-span-6 text-sm font-medium">Professional Services (Half Day)</div>
                    <div className="col-span-2 text-center text-sm text-muted-foreground">1</div>
                    <div className="col-span-2">
                      <input 
                        type="number" 
                        value={activeTab === 'client_invoices' ? (editingProject.clientHalfDayRate || 0) : (editingProject.halfDayRate || 0)}
                        onChange={(e) => {
                          const val = parseFloat(e.target.value) || 0;
                          if (activeTab === 'client_invoices') {
                            setEditingProject({...editingProject, clientHalfDayRate: val});
                          } else {
                            setEditingProject({...editingProject, halfDayRate: val});
                          }
                        }}
                        className="w-full text-right text-sm bg-transparent border-none p-0 focus:ring-0"
                      />
                    </div>
                    <div className="col-span-2 text-right text-sm font-medium">
                      {(activeTab === 'client_invoices' ? (editingProject.clientHalfDayRate || 0) : (editingProject.halfDayRate || 0)).toFixed(2)}
                    </div>
                  </div>

                  {/* Full Day Rate Row */}
                  <div className="grid grid-cols-12 gap-4 items-center py-2 border-b border-border/50">
                    <div className="col-span-6 text-sm font-medium">Professional Services (Full Day)</div>
                    <div className="col-span-2 text-center text-sm text-muted-foreground">1</div>
                    <div className="col-span-2">
                      <input 
                        type="number" 
                        value={activeTab === 'client_invoices' ? (editingProject.clientFullDayRate || 0) : (editingProject.fullDayRate || 0)}
                        onChange={(e) => {
                          const val = parseFloat(e.target.value) || 0;
                          if (activeTab === 'client_invoices') {
                            setEditingProject({...editingProject, clientFullDayRate: val});
                          } else {
                            setEditingProject({...editingProject, fullDayRate: val});
                          }
                        }}
                        className="w-full text-right text-sm bg-transparent border-none p-0 focus:ring-0"
                      />
                    </div>
                    <div className="col-span-2 text-right text-sm font-medium">
                      {(activeTab === 'client_invoices' ? (editingProject.clientFullDayRate || 0) : (editingProject.fullDayRate || 0)).toFixed(2)}
                    </div>
                  </div>

                  {/* Monthly Rate Row */}
                  <div className="grid grid-cols-12 gap-4 items-center py-2 border-b border-border/50">
                    <div className="col-span-6 text-sm font-medium">Professional Services (Monthly)</div>
                    <div className="col-span-2 text-center text-sm text-muted-foreground">1</div>
                    <div className="col-span-2">
                      <input 
                        type="number" 
                        value={activeTab === 'client_invoices' ? (editingProject.clientMonthlyRate || 0) : (editingProject.monthlyRate || 0)}
                        onChange={(e) => {
                          const val = parseFloat(e.target.value) || 0;
                          if (activeTab === 'client_invoices') {
                            setEditingProject({...editingProject, clientMonthlyRate: val});
                          } else {
                            setEditingProject({...editingProject, monthlyRate: val});
                          }
                        }}
                        className="w-full text-right text-sm bg-transparent border-none p-0 focus:ring-0"
                      />
                    </div>
                    <div className="col-span-2 text-right text-sm font-medium">
                      {(activeTab === 'client_invoices' ? (editingProject.clientMonthlyRate || 0) : (editingProject.monthlyRate || 0)).toFixed(2)}
                    </div>
                  </div>

                  {/* Travel Cost Row */}
                  <div className="grid grid-cols-12 gap-4 items-center py-2 border-b border-border/50">
                    <div className="col-span-6 text-sm font-medium">Travel Expenses</div>
                    <div className="col-span-2 text-center text-sm text-muted-foreground">1</div>
                    <div className="col-span-2">
                      <input 
                        type="number" 
                        value={activeTab === 'client_invoices' ? (editingProject.clientTravelCost || 0) : (editingProject.travelCost || 0)}
                        onChange={(e) => {
                          const val = parseFloat(e.target.value) || 0;
                          if (activeTab === 'client_invoices') {
                            setEditingProject({...editingProject, clientTravelCost: val});
                          } else {
                            setEditingProject({...editingProject, travelCost: val});
                          }
                        }}
                        className="w-full text-right text-sm bg-transparent border-none p-0 focus:ring-0"
                      />
                    </div>
                    <div className="col-span-2 text-right text-sm font-medium">
                      {(activeTab === 'client_invoices' ? (editingProject.clientTravelCost || 0) : (editingProject.travelCost || 0)).toFixed(2)}
                    </div>
                  </div>

                  {/* Material Cost Row */}
                  <div className="grid grid-cols-12 gap-4 items-center py-2 border-b border-border/50">
                    <div className="col-span-6 text-sm font-medium">Material & Equipment</div>
                    <div className="col-span-2 text-center text-sm text-muted-foreground">1</div>
                    <div className="col-span-2">
                      <input 
                        type="number" 
                        value={activeTab === 'client_invoices' ? (editingProject.clientMaterialCost || 0) : (editingProject.materialCost || 0)}
                        onChange={(e) => {
                          const val = parseFloat(e.target.value) || 0;
                          if (activeTab === 'client_invoices') {
                            setEditingProject({...editingProject, clientMaterialCost: val});
                          } else {
                            setEditingProject({...editingProject, materialCost: val});
                          }
                        }}
                        className="w-full text-right text-sm bg-transparent border-none p-0 focus:ring-0"
                      />
                    </div>
                    <div className="col-span-2 text-right text-sm font-medium">
                      {(activeTab === 'client_invoices' ? (editingProject.clientMaterialCost || 0) : (editingProject.materialCost || 0)).toFixed(2)}
                    </div>
                  </div>
                </div>

                {/* Summary & Totals */}
                <div className="flex justify-between items-start pt-4">
                  <div className="w-1/2 space-y-6">
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">Status</label>
                        <select 
                          value={activeTab === 'client_invoices' ? (editingProject.clientStatus === 'Completed' ? 'Paid' : editingProject.clientStatus === 'Cancelled' ? 'Overdue' : 'Unpaid') : (editingProject.status === 'Completed' ? 'Paid' : editingProject.status === 'Cancelled' ? 'Overdue' : 'Unpaid')}
                          onChange={(e) => {
                            const val = e.target.value;
                            let status = 'In Progress';
                            if (val === 'Paid') status = 'Completed';
                            if (val === 'Overdue') status = 'Cancelled';
                            if (activeTab === 'client_invoices') {
                              setEditingProject({...editingProject, clientStatus: status});
                            } else {
                              setEditingProject({...editingProject, status});
                            }
                          }}
                          className="block w-full h-9 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="Unpaid">Unpaid</option>
                          <option value="Paid">Paid</option>
                          <option value="Overdue">Overdue</option>
                        </select>
                      </div>
                      <div className="space-y-2">
                        <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">Due Date</label>
                        <input 
                          type="date" 
                          value={editingProject.deadline || ''}
                          onChange={(e) => setEditingProject({...editingProject, deadline: e.target.value})}
                          className="block w-full h-9 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-[10px] font-bold uppercase tracking-wider text-muted-foreground">Status</label>
                      <select 
                        value={activeTab === 'client_invoices' ? (editingProject.clientInvoiceStatus || 'Unpaid') : (editingProject.engineerInvoiceStatus || 'Unpaid')}
                        onChange={(e) => {
                          const val = e.target.value as any;
                          if (activeTab === 'client_invoices') {
                            setEditingProject({...editingProject, clientInvoiceStatus: val});
                          } else {
                            setEditingProject({...editingProject, engineerInvoiceStatus: val});
                          }
                        }}
                        className="block w-full h-9 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="Unpaid">Unpaid</option>
                        <option value="Paid">Paid</option>
                        <option value="Overdue">Overdue</option>
                      </select>
                    </div>
                    </div>

                    <div className="space-y-2">
                      <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">Notes / Payment Terms</label>
                      <textarea 
                        rows={3}
                        className="w-full rounded-lg border border-border bg-background p-3 text-xs focus:outline-none focus:ring-2 focus:ring-primary/20 resize-none"
                        placeholder="e.g. Please pay within 30 days. Bank details: ..."
                        defaultValue={activeTab === 'client_invoices' ? "Payment is due within 30 days. Thank you for your business!" : "Please process this invoice at your earliest convenience."}
                      />
                    </div>
                  </div>
                  <div className="w-1/3 space-y-3">
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Subtotal</span>
                      <span className="font-medium">
                        {(
                          (activeTab === 'client_invoices' ? (editingProject.clientHourlyRate || 0) : (editingProject.hourlyRate || 0)) * parseTotalTime(editingProject.totalTime) + 
                          (activeTab === 'client_invoices' ? (editingProject.clientHalfDayRate || 0) : (editingProject.halfDayRate || 0)) + 
                          (activeTab === 'client_invoices' ? (editingProject.clientFullDayRate || 0) : (editingProject.fullDayRate || 0)) + 
                          (activeTab === 'client_invoices' ? (editingProject.clientMonthlyRate || 0) : (editingProject.monthlyRate || 0)) + 
                          (activeTab === 'client_invoices' ? (editingProject.clientTravelCost || 0) : (editingProject.travelCost || 0)) + 
                          (activeTab === 'client_invoices' ? (editingProject.clientMaterialCost || 0) : (editingProject.materialCost || 0))
                        ).toFixed(2)}
                      </span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Tax ({editingProject.taxRate || 0}%)</span>
                      <span className="font-medium">
                        {((editingProject.taxAmount || 0)).toFixed(2)}
                      </span>
                    </div>
                    <div className="flex justify-between items-center pt-3 border-t border-border">
                      <span className="text-lg font-bold">Total</span>
                      <div className="flex items-center gap-2">
                        <span className="text-muted-foreground text-sm">{getSymbol(editingProject.currency)}</span>
                        <div className="flex flex-col items-end">
                          <input 
                            type="number" 
                            value={activeTab === 'client_invoices' ? (editingProject.clientTotalAmount || 0) : (editingProject.totalAmount || 0)}
                            onChange={(e) => {
                              const val = parseFloat(e.target.value) || 0;
                              if (activeTab === 'client_invoices') {
                                setEditingProject({...editingProject, clientTotalAmount: val});
                              } else {
                                setEditingProject({...editingProject, totalAmount: val});
                              }
                            }}
                            className="w-24 text-right text-2xl font-bold bg-transparent border-none p-0 focus:ring-0"
                          />
                          <div className="flex items-center gap-2 mt-1">
                            <span className="text-[10px] text-muted-foreground">Tax Rate:</span>
                            <input 
                              type="number"
                              value={editingProject.taxRate || 0}
                              onChange={(e) => {
                                const rate = parseFloat(e.target.value) || 0;
                                const subtotal = (
                                  (activeTab === 'client_invoices' ? (editingProject.clientHourlyRate || 0) : (editingProject.hourlyRate || 0)) * parseTotalTime(editingProject.totalTime) + 
                                  (activeTab === 'client_invoices' ? (editingProject.clientHalfDayRate || 0) : (editingProject.halfDayRate || 0)) + 
                                  (activeTab === 'client_invoices' ? (editingProject.clientFullDayRate || 0) : (editingProject.fullDayRate || 0)) + 
                                  (activeTab === 'client_invoices' ? (editingProject.clientMonthlyRate || 0) : (editingProject.monthlyRate || 0)) + 
                                  (activeTab === 'client_invoices' ? (editingProject.clientTravelCost || 0) : (editingProject.travelCost || 0)) + 
                                  (activeTab === 'client_invoices' ? (editingProject.clientMaterialCost || 0) : (editingProject.materialCost || 0))
                                );
                                const taxAmount = subtotal * (rate / 100);
                                const total = subtotal + taxAmount;
                                
                                if (activeTab === 'client_invoices') {
                                  setEditingProject({
                                    ...editingProject, 
                                    taxRate: rate, 
                                    taxAmount: taxAmount,
                                    clientTotalAmount: total
                                  });
                                } else {
                                  setEditingProject({
                                    ...editingProject, 
                                    taxRate: rate, 
                                    taxAmount: taxAmount,
                                    totalAmount: total
                                  });
                                }
                              }}
                              className="w-12 text-right text-[10px] border border-border rounded px-1"
                            />
                            <span className="text-[10px] text-muted-foreground">%</span>
                          </div>
                          
                          {/* Dynamic Third Party Commissions Section */}
                          <div className="flex flex-col mt-4 pt-4 border-t border-border/50">
                            <div className="flex items-center justify-between mb-2 text-right">
                              <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">Third-Party Commissions</span>
                              <button 
                                type="button"
                                onClick={() => {
                                  const newComm = {
                                    id: Math.random().toString(36).substr(2, 9),
                                    vendorName: '',
                                    rate: 0,
                                    amount: 0,
                                    status: 'Unpaid' as const
                                  };
                                  setEditingProject({
                                    ...editingProject,
                                    commissions: [...(editingProject.commissions || []), newComm]
                                  });
                                }}
                                className="text-[10px] font-bold text-primary hover:underline flex items-center gap-1"
                              >
                                <Plus size={10} /> Add Vendor
                              </button>
                            </div>
                            
                            <div className="space-y-2">
                              {(editingProject.commissions || []).map((comm, idx) => (
                                <div key={comm.id || idx} className="flex items-center gap-2 bg-muted/10 p-2 rounded-lg">
                                  <input 
                                    type="text"
                                    placeholder="Vendor"
                                    value={comm.vendorName}
                                    onChange={(e) => {
                                      const newComms = JSON.parse(JSON.stringify(editingProject.commissions || []));
                                      newComms[idx].vendorName = e.target.value;
                                      setEditingProject({...editingProject, commissions: newComms});
                                    }}
                                    className="flex-1 text-[10px] h-7 bg-background border border-border rounded px-2 outline-none focus:ring-1 focus:ring-primary/20"
                                  />
                                  <div className="flex items-center gap-1">
                                    <input 
                                      type="number"
                                      value={comm.rate}
                                      onChange={(e) => {
                                        const rate = parseFloat(e.target.value) || 0;
                                        const totalAmt = activeTab === 'client_invoices' ? (editingProject.clientTotalAmount || 0) : (editingProject.totalAmount || 0);
                                        const newComms = JSON.parse(JSON.stringify(editingProject.commissions || []));
                                        newComms[idx].rate = rate;
                                        newComms[idx].amount = totalAmt * (rate / 100);
                                        setEditingProject({...editingProject, commissions: newComms});
                                      }}
                                      className="w-10 text-right text-[10px] h-7 bg-background border border-border rounded px-1 outline-none focus:ring-1 focus:ring-primary/20"
                                    />
                                    <span className="text-[10px] text-muted-foreground">%</span>
                                  </div>
                                  <div className="w-16 text-right text-[10px] font-bold text-primary truncate">
                                    {editingProject.currency === 'Euro' ? '€' : editingProject.currency === 'GBP' ? '£' : '$'}
                                    {comm.amount.toLocaleString(undefined, {minimumFractionDigits: 2})}
                                  </div>
                                  <button 
                                    type="button"
                                    onClick={() => {
                                      const newComms = (editingProject.commissions || []).filter((_, i) => i !== idx);
                                      setEditingProject({...editingProject, commissions: newComms});
                                    }}
                                    className="p-1 text-red-500 hover:bg-red-50 rounded transition-colors"
                                  >
                                    <X size={12} />
                                  </button>
                                </div>
                              ))}
                              {(editingProject.commissions || []).length === 0 && (
                                <p className="text-[10px] text-muted-foreground italic text-center py-2">No commissions assigned</p>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Actions */}
                <div className="flex justify-end gap-4 pt-8 border-t border-border">
                  <button 
                    type="button"
                    onClick={() => {
                      if (editingProject) {
                        const symbol = editingProject.currency === 'Euro' ? '€' : editingProject.currency === 'GBP' ? '£' : '$';
                        const hours = parseTotalTime(editingProject.totalTime);
                        
                        // Internal/Engineer rates
                        const hourlyTotal = (editingProject.hourlyRate || 0) * hours;
                        const calculated = hourlyTotal + (editingProject.travelCost || 0) + (editingProject.materialCost || 0) + 
                               (editingProject.halfDayRate || 0) + (editingProject.fullDayRate || 0) + (editingProject.monthlyRate || 0);
                        const internalAmount = editingProject.totalAmount && editingProject.totalAmount > 0 ? editingProject.totalAmount : calculated;

                        // Client rates
                        const clientHourlyTotal = (editingProject.clientHourlyRate || 0) * hours;
                        const clientCalculated = clientHourlyTotal + (editingProject.clientTravelCost || 0) + (editingProject.clientMaterialCost || 0) + 
                               (editingProject.clientHalfDayRate || 0) + (editingProject.clientFullDayRate || 0) + (editingProject.clientMonthlyRate || 0);
                        const clientAmount = editingProject.clientTotalAmount && editingProject.clientTotalAmount > 0 ? editingProject.clientTotalAmount : clientCalculated;

                        const invoiceToDownload: Invoice = {
                          id: editingProject.ticketId || editingProject.id,
                          assignedOrder: editingProject.assignedTo || 'Unassigned',
                          requestedOrder: editingProject.client || editingProject.name,
                          amount: `${symbol}${internalAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
                          clientAmount: `${symbol}${clientAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
                          issueDate: editingProject.issueDate || new Date().toISOString().split('T')[0],
                          dueDate: editingProject.deadline,
                          completedDate: editingProject.completedDate,
                          status: editingProject.status === 'Completed' ? 'Paid' : editingProject.status === 'Cancelled' ? 'Overdue' : 'Unpaid',
                          engineerStatus: editingProject.status === 'Completed' ? 'Paid' : editingProject.status === 'Cancelled' ? 'Overdue' : 'Unpaid',
                          clientStatus: editingProject.clientStatus === 'Completed' ? 'Paid' : editingProject.clientStatus === 'Cancelled' ? 'Overdue' : 'Unpaid',
                          project: editingProject,
                          issuedMonth: editingProject.issuedMonth
                        };
                        handleDownloadInvoice(invoiceToDownload);
                      }
                    }}
                    className="px-6 py-2.5 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors flex items-center gap-2"
                  >
                    <Download size={16} />
                    Download PDF
                  </button>
                  <button 
                    type="button"
                    onClick={() => setIsEditModalOpen(false)}
                    className="px-6 py-2.5 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors"
                  >
                    Discard Changes
                  </button>
                  <button 
                    onClick={handleUpdateInvoice}
                    disabled={isSubmitting}
                    className="px-8 py-2.5 bg-primary text-primary-foreground text-sm font-medium rounded-lg hover:bg-primary/90 transition-colors shadow-lg shadow-primary/20 disabled:opacity-50"
                  >
                    {isSubmitting ? 'Saving...' : 'Save & Update Invoice'}
                  </button>
                </div>
              </div>
            ) : (
              <>
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-bold">Edit Invoice</h2>
                  <div className="flex items-center gap-2">
                    <button 
                      type="button"
                      onClick={() => {
                        if (editingProject) {
                          const symbol = editingProject.currency === 'Euro' ? '€' : editingProject.currency === 'GBP' ? '£' : '$';
                          const hours = parseTotalTime(editingProject.totalTime);
                          
                          // Internal/Engineer rates
                          const hourlyTotal = (editingProject.hourlyRate || 0) * hours;
                          const calculated = hourlyTotal + (editingProject.travelCost || 0) + (editingProject.materialCost || 0) + 
                                 (editingProject.halfDayRate || 0) + (editingProject.fullDayRate || 0) + (editingProject.monthlyRate || 0);
                          const internalAmount = editingProject.totalAmount && editingProject.totalAmount > 0 ? editingProject.totalAmount : calculated;

                          // Client rates
                          const clientHourlyTotal = (editingProject.clientHourlyRate || 0) * hours;
                          const clientCalculated = clientHourlyTotal + (editingProject.clientTravelCost || 0) + (editingProject.clientMaterialCost || 0) + 
                                 (editingProject.clientHalfDayRate || 0) + (editingProject.clientFullDayRate || 0) + (editingProject.clientMonthlyRate || 0);
                          const clientAmount = editingProject.clientTotalAmount && editingProject.clientTotalAmount > 0 ? editingProject.clientTotalAmount : clientCalculated;

                          const invoiceToDownload: Invoice = {
                            id: editingProject.ticketId || editingProject.id,
                            assignedOrder: editingProject.assignedTo || 'Unassigned',
                            requestedOrder: editingProject.client || editingProject.name,
                            amount: `${symbol}${internalAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
                            clientAmount: `${symbol}${clientAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
                            issueDate: editingProject.issueDate || new Date().toISOString().split('T')[0],
                            dueDate: editingProject.deadline,
                            completedDate: editingProject.completedDate,
                            status: editingProject.status === 'Completed' ? 'Paid' : editingProject.status === 'Cancelled' ? 'Overdue' : 'Unpaid',
                            engineerStatus: editingProject.status === 'Completed' ? 'Paid' : editingProject.status === 'Cancelled' ? 'Overdue' : 'Unpaid',
                            clientStatus: editingProject.clientStatus === 'Completed' ? 'Paid' : editingProject.clientStatus === 'Cancelled' ? 'Overdue' : 'Unpaid',
                            project: editingProject,
                            issuedMonth: editingProject.issuedMonth
                          };
                          handleDownloadInvoice(invoiceToDownload);
                        }
                      }}
                      className="flex items-center gap-2 px-3 py-1.5 text-xs font-medium rounded-lg border border-border hover:bg-accent transition-colors text-primary"
                    >
                      <Download size={14} />
                      Download PDF
                    </button>
                    <button 
                      type="button"
                      onClick={() => setIsEditModalOpen(false)}
                      className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
                    >
                      <X size={20} />
                    </button>
                  </div>
                </div>

                <form onSubmit={handleUpdateInvoice} className="space-y-4">
                  {(activeTab === 'invoices' || activeTab === 'engineer_invoices') && (
                    <div className="space-y-2">
                      <label className="text-sm font-medium">Assigned Order (Engineer)</label>
                      <input 
                        type="text" 
                        value={editingProject.assignedTo || ''}
                        onChange={(e) => setEditingProject({...editingProject, assignedTo: 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>
                  )}

                  {(activeTab === 'invoices' || activeTab === 'client_invoices') && (
                    <div className="space-y-2">
                      <label className="text-sm font-medium">Requested Order (Client)</label>
                      <input 
                        type="text" 
                        value={editingProject.client || ''}
                        onChange={(e) => setEditingProject({...editingProject, client: 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="grid grid-cols-2 gap-4">
                    {(activeTab === 'invoices' || activeTab === 'engineer_invoices') && (
                      <div className="space-y-2">
                        <label className="text-sm font-medium">Engineer Amount</label>
                        <input 
                          type="number" 
                          value={editingProject.totalAmount || 0}
                          onChange={(e) => setEditingProject({...editingProject, totalAmount: parseFloat(e.target.value) || 0})}
                          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>
                    )}
                    {(activeTab === 'invoices' || activeTab === 'client_invoices') && (
                      <div className={cn(
                        "space-y-2",
                        activeTab === 'client_invoices' ? "col-span-2" : ""
                      )}>
                        <label className="text-sm font-medium">Client Amount</label>
                        <input 
                          type="number" 
                          value={editingProject.clientTotalAmount || 0}
                          onChange={(e) => setEditingProject({...editingProject, clientTotalAmount: parseFloat(e.target.value) || 0})}
                          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>

                  <div className="grid grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <label className="text-sm font-medium">Issue Date</label>
                      <input 
                        type="date" 
                        value={editingProject.issueDate || ''}
                        onChange={(e) => setEditingProject({...editingProject, issueDate: 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">Issued Month</label>
                      <input 
                        type="month" 
                        value={editingProject.issuedMonth || ''}
                        onChange={(e) => setEditingProject({...editingProject, issuedMonth: 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">Due Date</label>
                      <input 
                        type="date" 
                        value={editingProject.deadline || ''}
                        onChange={(e) => setEditingProject({...editingProject, deadline: 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>

                  <div className="grid grid-cols-2 gap-4">
                    {(activeTab === 'invoices' || activeTab === 'engineer_invoices') && (
                      <div className={cn(
                        "space-y-2",
                        activeTab === 'engineer_invoices' ? "col-span-2" : ""
                      )}>
                        <label className="text-sm font-medium">Engineer Status</label>
                        <select 
                          value={editingProject.engineerInvoiceStatus || (editingProject.status === 'Completed' ? 'Paid' : editingProject.status === 'Cancelled' ? 'Overdue' : 'Unpaid')}
                          onChange={(e) => {
                            const val = e.target.value as any;
                            setEditingProject({...editingProject, engineerInvoiceStatus: val});
                          }}
                          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="Unpaid">Unpaid</option>
                          <option value="Paid">Paid</option>
                          <option value="Overdue">Overdue</option>
                        </select>
                      </div>
                    )}
                    {(activeTab === 'invoices' || activeTab === 'client_invoices') && (
                      <div className={cn(
                        "space-y-2",
                        activeTab === 'client_invoices' ? "col-span-2" : ""
                      )}>
                        <label className="text-sm font-medium">Client Status</label>
                        <select 
                          value={editingProject.clientInvoiceStatus || (editingProject.clientStatus === 'Completed' ? 'Paid' : editingProject.clientStatus === 'Cancelled' ? 'Overdue' : 'Unpaid')}
                          onChange={(e) => {
                            const val = e.target.value as any;
                            setEditingProject({...editingProject, clientInvoiceStatus: val});
                          }}
                          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="Unpaid">Unpaid</option>
                          <option value="Paid">Paid</option>
                          <option value="Overdue">Overdue</option>
                        </select>
                      </div>
                    )}
                  </div>

                  <div className="pt-4 flex gap-3">
                    <button 
                      type="button"
                      onClick={() => setIsEditModalOpen(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"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </>
            )}
          </div>
        </div>
      )}

      {/* Create Invoice Modal */}
      {isInvoiceModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-start justify-center p-4 bg-background/80 backdrop-blur-sm overflow-y-auto">
          <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 my-8">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">Create New Invoice</h2>
              <button 
                onClick={() => setIsInvoiceModalOpen(false)}
                className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleCreateInvoice} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Assigned Order</label>
                <input 
                  type="text" 
                  placeholder="e.g. Alex Rivera"
                  value={newInvoice.assignedOrder || ''}
                  onChange={(e) => setNewInvoice({...newInvoice, assignedOrder: 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="space-y-2">
                <label className="text-sm font-medium">Requested Order (Company Name)</label>
                <input 
                  type="text" 
                  placeholder="e.g. TechCorp"
                  value={newInvoice.requestedOrder || ''}
                  onChange={(e) => setNewInvoice({...newInvoice, requestedOrder: 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="space-y-2">
                <label className="text-sm font-medium">{activeTab === 'client_invoices' ? 'Amount' : 'Engineer Amount'}</label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm">
                    {getSymbol(companySettings.currency || 'USD')}
                  </span>
                  <input 
                    type="text" 
                    placeholder="0.00"
                    value={newInvoice.amount || ''}
                    onChange={(e) => setNewInvoice({...newInvoice, amount: e.target.value})}
                    className="h-10 w-full rounded-lg border border-border bg-background pl-7 pr-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    required
                  />
                </div>
              </div>

              <div className="grid grid-cols-3 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Issue Date</label>
                  <input 
                    type="date" 
                    value={newInvoice.issueDate || ''}
                    onChange={(e) => setNewInvoice({...newInvoice, issueDate: 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="space-y-2">
                  <label className="text-sm font-medium">Issued Month</label>
                  <input 
                    type="month" 
                    value={newInvoice.issuedMonth || ''}
                    onChange={(e) => setNewInvoice({...newInvoice, issuedMonth: 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">Due Date</label>
                  <input 
                    type="date" 
                    value={newInvoice.dueDate || ''}
                    onChange={(e) => setNewInvoice({...newInvoice, dueDate: 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="space-y-2">
                <label className="text-sm font-medium">Initial Status</label>
                <select 
                  value={newInvoice.status || 'Unpaid'}
                  onChange={(e) => setNewInvoice({...newInvoice, 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="Unpaid">Unpaid</option>
                  <option value="Paid">Paid</option>
                  <option value="Overdue">Overdue</option>
                </select>
              </div>

              <div className="pt-4 flex gap-3">
                <button 
                  type="button"
                  onClick={() => setIsInvoiceModalOpen(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"
                >
                  Create Invoice
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      <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">Finance Management</h1>
          <p className="text-muted-foreground">Monitor cash flow, manage invoices, and track business expenses.</p>
        </div>
        <div className="flex items-center gap-2">
          <button 
            onClick={handleRecordExpense}
            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"
          >
            <TrendingDown size={18} className="text-red-500" />
            Record Expense
          </button>
          <button 
            onClick={handleAddInvoice}
            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"
          >
            <Plus size={18} />
            Create Invoice
          </button>
        </div>
      </div>

      {/* Financial KPIs */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
        <FinanceStatCard 
          title="Total Revenue" 
          value={`$${stats.totalRevenue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`} 
          icon={TrendingUp} 
          trend="Total billings" 
          trendType="neutral"
          description="Total client billings"
        />
        <FinanceStatCard 
          title="Total Expenses" 
          value={`$${stats.totalExpenses.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`} 
          icon={TrendingDown} 
          trend="Payouts + Comms" 
          trendType="neutral"
          description="Total payouts & commissions"
        />
        <FinanceStatCard 
          title="3rd-party Comms" 
          value={`$${stats.totalCommissions.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`} 
          icon={Users} 
          trend={`${((stats.totalCommissions / (stats.totalRevenue || 1)) * 100).toFixed(1)}% of Rev`} 
          trendType="neutral"
          description="Third-party commissions"
        />
        <FinanceStatCard 
          title="Net Profit" 
          value={`$${stats.netProfit.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`} 
          icon={DollarSign} 
          trend={`${stats.margin.toFixed(1)}%`} 
          trendType="up"
          description="Profit margin"
        />
        <FinanceStatCard 
          title="Pending Invoices" 
          value={`$${stats.pendingAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`} 
          icon={Clock} 
          trend={`${stats.pendingCount} invoices`} 
          trendType="neutral"
          description="Awaiting payment"
        />
      </div>

      {/* Tab Switcher */}
      <div className="flex border-b border-border">
        <button
          onClick={() => setActiveTab('overview')}
          className={cn(
            "px-6 py-3 text-sm font-medium transition-all relative",
            activeTab === 'overview' ? "text-primary" : "text-muted-foreground hover:text-foreground"
          )}
        >
          Overview
          {activeTab === 'overview' && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />}
        </button>
        <button
          onClick={() => setActiveTab('transactions')}
          className={cn(
            "px-6 py-3 text-sm font-medium transition-all relative",
            activeTab === 'transactions' ? "text-primary" : "text-muted-foreground hover:text-foreground"
          )}
        >
          Transactions
          {activeTab === 'transactions' && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />}
        </button>
        <button
          onClick={() => setActiveTab('invoices')}
          className={cn(
            "px-6 py-3 text-sm font-medium transition-all relative",
            activeTab === 'invoices' ? "text-primary" : "text-muted-foreground hover:text-foreground"
          )}
        >
          All Invoices
          {activeTab === 'invoices' && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />}
        </button>
        <button
          onClick={() => setActiveTab('engineer_invoices')}
          className={cn(
            "px-6 py-3 text-sm font-medium transition-all relative",
            activeTab === 'engineer_invoices' ? "text-primary" : "text-muted-foreground hover:text-foreground"
          )}
        >
          Engineer Invoices
          {activeTab === 'engineer_invoices' && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />}
        </button>
        <button
          onClick={() => setActiveTab('client_invoices')}
          className={cn(
            "px-6 py-3 text-sm font-medium transition-all relative",
            activeTab === 'client_invoices' ? "text-primary" : "text-muted-foreground hover:text-foreground"
          )}
        >
          Client Invoices
          {activeTab === 'client_invoices' && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />}
        </button>
        <button
          onClick={() => setActiveTab('bookkeeping')}
          className={cn(
            "px-6 py-3 text-sm font-medium transition-all relative",
            activeTab === 'bookkeeping' ? "text-primary" : "text-muted-foreground hover:text-foreground"
          )}
        >
          Bookkeeping
          {activeTab === 'bookkeeping' && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />}
        </button>
        <button
          onClick={() => setActiveTab('tax')}
          className={cn(
            "px-6 py-3 text-sm font-medium transition-all relative",
            activeTab === 'tax' ? "text-primary" : "text-muted-foreground hover:text-foreground"
          )}
        >
          Government Tax
          {activeTab === 'tax' && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />}
        </button>
        <button
          onClick={() => setActiveTab('commissions')}
          className={cn(
            "px-6 py-3 text-sm font-medium transition-all relative",
            activeTab === 'commissions' ? "text-primary" : "text-muted-foreground hover:text-foreground"
          )}
        >
          Third-party Commission
          {activeTab === 'commissions' && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary" />}
        </button>
      </div>

      {activeTab === 'commissions' && (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -10 }}
          className="space-y-6"
        >
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-lg font-bold">Third-party Vendor Commissions</h3>
              <p className="text-sm text-muted-foreground">Manage and track commission payouts to third-party agents or vendors.</p>
            </div>
            <div className="flex gap-2">
               <button 
                onClick={() => {
                  const doc = new jsPDF('l', 'mm', 'a4');
                  doc.setFontSize(18);
                  doc.text('Commission Report', 14, 20);
                  doc.setFontSize(10);
                  doc.text(`Generated on: ${new Date().toLocaleString()}`, 14, 28);
                  
                  const headers = [['Project ID', 'Client', 'Project Name', 'Third Party', 'Rate (%)', 'Commission Amount', 'Status']];
                  const data = allCommissions.map(c => {
                    const symbol = c.project?.currency === 'Euro' ? '€' : c.project?.currency === 'GBP' ? '£' : '$';
                    return [
                      c.projectTicket,
                      c.client || 'N/A',
                      c.projectName,
                      c.vendorName || 'N/A',
                      `${c.rate || 0}%`,
                      `${symbol}${c.amount.toLocaleString()}`,
                      c.status || 'Unpaid'
                    ];
                  });

                  autoTable(doc, {
                    head: headers,
                    body: data,
                    startY: 35,
                    theme: 'striped',
                    headStyles: { fillColor: [15, 23, 42] }
                  });

                  doc.save('commission_report.pdf');
                  toast.success('Commission report exported');
                }}
                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={16} />
                Export CSV
              </button>
            </div>
          </div>

          <div className="grid gap-4 md:grid-cols-3">
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">Total Commissions</p>
              <p className="text-2xl font-bold">
                ${allCommissions.reduce((acc, c) => acc + c.amount, 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              </p>
            </div>
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">Paid Commissions</p>
              <p className="text-2xl font-bold text-green-500">
                ${allCommissions.filter(c => c.status === 'Paid').reduce((acc, c) => acc + c.amount, 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              </p>
            </div>
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">Pending Commissions</p>
              <p className="text-2xl font-bold text-orange-500">
                ${allCommissions.filter(c => c.status !== 'Paid').reduce((acc, c) => acc + c.amount, 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              </p>
            </div>
          </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-6 py-4 font-semibold">Project & Client</th>
                  <th className="px-6 py-4 font-semibold">Third Party Vendor</th>
                  <th className="px-6 py-4 font-semibold">Commission %</th>
                  <th className="px-6 py-4 font-semibold">Amount</th>
                  <th className="px-6 py-4 font-semibold">Status</th>
                  <th className="px-6 py-4 font-semibold text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {allCommissions.map((c) => {
                  const symbol = c.project?.currency === 'Euro' ? '€' : c.project?.currency === 'GBP' ? '£' : '$';
                  
                  return (
                    <tr key={`${c.projectId}-${c.id}`} className="hover:bg-accent/30 transition-colors">
                      <td className="px-6 py-4">
                        <p className="font-medium">{c.projectName}</p>
                        <p className="text-xs text-muted-foreground">{c.client}</p>
                        <p className="text-[10px] text-muted-foreground mt-0.5">ID: {c.projectTicket}</p>
                      </td>
                      <td className="px-6 py-4">
                        {c.vendorName ? (
                          <span className="font-medium">{c.vendorName}</span>
                        ) : (
                          <span className="text-muted-foreground italic text-xs">Not assigned</span>
                        )}
                      </td>
                      <td className="px-6 py-4 font-mono">
                        {c.rate || 0}%
                      </td>
                      <td className="px-6 py-4 font-bold text-primary">
                        {symbol}{c.amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                      </td>
                      <td className="px-6 py-4">
                        <span className={cn(
                          "inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider",
                          c.status === 'Paid' ? "bg-green-500/10 text-green-500" : "bg-orange-500/10 text-orange-500"
                        )}>
                          {c.status || 'Unpaid'}
                        </span>
                      </td>
                      <td className="px-6 py-4 text-right">
                        <div className="flex justify-end gap-2">
                          {hasPermission('finance.edit') && (
                            <button 
                              onClick={() => {
                                const inv = invoices.find(inv => inv.id === c.projectTicket);
                                if (inv) handleEditInvoice(inv as Invoice);
                              }}
                              className="p-1.5 rounded-lg border border-border bg-card hover:bg-accent transition-colors text-muted-foreground hover:text-foreground"
                              title="Edit project details"
                            >
                              <Edit size={14} />
                            </button>
                          )}
                          {hasPermission('finance.export') && (
                            <button 
                              onClick={() => {
                                const symbol = c.project?.currency === 'Euro' ? '€' : c.project?.currency === 'GBP' ? '£' : '$';
                                setCommissionFormData({
                                  invoiceId: `COMM-${c.id.substring(0, 8).toUpperCase()}`,
                                  fromName: c.project?.companyName || companySettings.name || 'MA IT TECH',
                                  fromEmail: c.project?.companyEmail || companySettings.email || 'billing@ma-it-tech.com',
                                  fromPhone: c.project?.companyPhone || companySettings.phone || '',
                                  fromAddress: c.project?.companyAddress || companySettings.location || '',
                                  billToName: c.vendorName || '',
                                  billToEmail: '',
                                  billToPhone: '',
                                  billToAddress: '',
                                  description: `Commission for ${c.projectName}`,
                                  projectRef: c.projectTicket,
                                  amount: c.amount,
                                  date: new Date().toISOString().split('T')[0],
                                  currency: symbol
                                });
                                setIsCommissionModalOpen(true);
                              }}
                              className="p-1.5 rounded-lg border border-border bg-card hover:bg-accent transition-colors text-primary hover:text-primary-foreground hover:bg-primary"
                              title="Generate Commission Invoice"
                            >
                              <FileText size={14} />
                            </button>
                          )}
                          {hasPermission('finance.edit') && (
                            <button 
                              onClick={() => toggleCommissionStatus(c.projectId, c.id, c.status)}
                              className={cn(
                                "p-1.5 rounded-lg border border-border bg-card transition-colors",
                                c.status === 'Paid' ? "text-green-500 bg-green-50" : "text-muted-foreground hover:bg-accent"
                              )}
                              title={c.status === 'Paid' ? "Mark as Unpaid" : "Mark as Paid"}
                            >
                              <CheckCircle2 size={14} />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })}
                {allCommissions.length === 0 && (
                  <tr>
                    <td colSpan={6} className="px-6 py-12 text-center text-muted-foreground italic">
                      No third-party commissions found.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </motion.div>
      )}

      {activeTab === 'tax' && (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -10 }}
        >
          <TaxModule />
        </motion.div>
      )}

      {activeTab === 'bookkeeping' && (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -10 }}
        >
          <Bookkeeping />
        </motion.div>
      )}

      {activeTab === 'overview' && (
        <div className="grid gap-6 lg:grid-cols-2">
          {/* Revenue vs Expenses Chart */}
          <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
            <div className="flex items-center justify-between mb-6">
              <h3 className="font-semibold">Revenue vs Expenses</h3>
              <select className="text-xs border border-border rounded px-2 py-1 bg-background outline-none">
                <option>Last 6 Months</option>
                <option>Last Year</option>
              </select>
            </div>
            <div className="h-[300px] w-full">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={stats.chartData}>
                  <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                  <XAxis 
                    dataKey="month" 
                    axisLine={false} 
                    tickLine={false} 
                    tick={{ fontSize: 12, fill: 'hsl(var(--muted-foreground))' }} 
                  />
                  <YAxis 
                    axisLine={false} 
                    tickLine={false} 
                    tick={{ fontSize: 12, fill: 'hsl(var(--muted-foreground))' }}
                    tickFormatter={(value) => `$${value/1000}k`}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: 'hsl(var(--card))', borderColor: 'hsl(var(--border))', borderRadius: '8px' }}
                    itemStyle={{ fontSize: '12px' }}
                    formatter={(value: number) => [`$${value.toLocaleString()}`, '']}
                  />
                  <Bar dataKey="revenue" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} barSize={30} />
                  <Bar dataKey="expenses" fill="hsl(var(--muted))" radius={[4, 4, 0, 0]} barSize={30} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Cash Flow Summary */}
          <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
            <h3 className="font-semibold mb-6">Cash Flow Summary</h3>
            <div className="space-y-6">
              <div className="flex items-center justify-between p-4 rounded-lg bg-accent/30">
                <div className="flex items-center gap-4">
                  <div className="h-10 w-10 rounded-full bg-green-500/10 flex items-center justify-center text-green-500">
                    <ArrowUpRight size={20} />
                  </div>
                  <div>
                    <p className="text-sm font-medium">Total Inflow</p>
                    <p className="text-xs text-muted-foreground">Payments received this month</p>
                  </div>
                </div>
                <p className="text-lg font-bold text-green-500">+${stats.currentMonthInflow.toLocaleString()}</p>
              </div>
              <div className="flex items-center justify-between p-4 rounded-lg bg-accent/30">
                <div className="flex items-center gap-4">
                  <div className="h-10 w-10 rounded-full bg-red-500/10 flex items-center justify-center text-red-500">
                    <ArrowDownRight size={20} />
                  </div>
                  <div>
                    <p className="text-sm font-medium">Total Outflow</p>
                    <p className="text-xs text-muted-foreground">Expenses paid this month</p>
                  </div>
                </div>
                <p className="text-lg font-bold text-red-500">-${stats.currentMonthOutflow.toLocaleString()}</p>
              </div>
              <div className="pt-4 border-t border-border">
                <div className="flex items-center justify-between">
                  <p className="font-semibold">Net Cash Flow</p>
                  <p className={cn(
                    "text-xl font-bold",
                    (stats.currentMonthInflow - stats.currentMonthOutflow) >= 0 ? "text-green-500" : "text-red-500"
                  )}>
                    {(stats.currentMonthInflow - stats.currentMonthOutflow) >= 0 ? '+' : '-'}${Math.abs(stats.currentMonthInflow - stats.currentMonthOutflow).toLocaleString()}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'transactions' && (
        <div className="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 transactions, categories..."
                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">
              {(activeTab === 'transactions') && hasPermission('finance.export') && (
                <button 
                  onClick={handleExportTransactionsPDF}
                  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 PDF
                </button>
              )}
              <div className="relative" ref={filterRef}>
                <button 
                  onClick={() => setIsFilterOpen(!isFilterOpen)}
                  className={cn(
                    "flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium transition-colors hover:bg-accent",
                    (filterType !== 'All' || filterCategory !== 'All' || filterStatus !== 'All') && "border-primary text-primary"
                  )}
                >
                  <Filter size={18} />
                  Filters
                  {(filterType !== 'All' || filterCategory !== 'All' || filterStatus !== 'All') && (
                    <span className="flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground">
                      {[filterType, filterCategory, filterStatus].filter(f => f !== 'All').length}
                    </span>
                  )}
                </button>

                {isFilterOpen && (
                  <div className="absolute right-0 mt-2 z-50 w-72 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 Transactions</h4>
                      <button 
                        onClick={() => {
                          setFilterType('All');
                          setFilterCategory('All');
                          setFilterStatus('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">Type</label>
                        <select 
                          value={filterType}
                          onChange={(e) => setFilterType(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 Types</option>
                          <option value="Income">Income</option>
                          <option value="Expense">Expense</option>
                        </select>
                      </div>

                      <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>
                          {Array.from(new Set(transactions.map(t => t.category))).sort().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="Completed">Completed</option>
                          <option value="Pending">Pending</option>
                          <option value="Cancelled">Cancelled</option>
                        </select>
                      </div>
                    </div>
                  </div>
                )}
              </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">Transaction</th>
                    <th className="px-4 py-3 font-medium">Invoice ID</th>
                    <th className="px-4 py-3 font-medium">Category</th>
                    <th className="px-4 py-3 font-medium">Amount</th>
                    <th className="px-4 py-3 font-medium">Date</th>
                    <th className="px-4 py-3 font-medium">Status</th>
                    <th className="px-4 py-3 font-medium"></th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {filteredTransactions.map((tx) => (
                    <tr key={tx.id} className="hover:bg-accent/30 transition-colors group">
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-3">
                          <div className={cn(
                            "h-8 w-8 rounded-lg flex items-center justify-center",
                            tx.type === 'Income' ? "bg-green-500/10 text-green-500" : "bg-red-500/10 text-red-500"
                          )}>
                            {tx.type === 'Income' ? <ArrowUpRight size={16} /> : <ArrowDownRight size={16} />}
                          </div>
                          <div>
                            <p className="font-medium">{tx.description}</p>
                            <p className="text-xs text-muted-foreground">{tx.id}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-4 font-mono text-xs text-muted-foreground">#{tx.invoiceId}</td>
                      <td className="px-4 py-4 text-muted-foreground">{tx.category}</td>
                      <td className={cn(
                        "px-4 py-4 font-semibold",
                        tx.type === 'Income' ? "text-green-500" : "text-red-500"
                      )}>
                        {tx.type === 'Income' ? '+' : '-'}{tx.amount}
                      </td>
                      <td className="px-4 py-4 text-muted-foreground">{tx.date}</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",
                          tx.status === 'Completed' ? "bg-green-500/10 text-green-500" :
                          tx.status === 'Pending' ? "bg-yellow-500/10 text-yellow-500" :
                          "bg-red-500/10 text-red-500"
                        )}>
                          {tx.status}
                        </span>
                      </td>
                      <td className="px-4 py-4 text-right">
                        <button className="p-1 hover:bg-accent rounded-md text-muted-foreground transition-colors">
                          <MoreHorizontal size={18} />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {(activeTab === 'invoices' || activeTab === 'client_invoices' || activeTab === 'engineer_invoices') && (
        <div className="space-y-4">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center justify-between">
            <h3 className="text-lg font-semibold">
              {activeTab === 'invoices' ? 'All Invoices' : 
               activeTab === 'engineer_invoices' ? 'Engineer Invoices (Engineer Rates)' : 
               'Client Invoices (Client Rates)'}
            </h3>
            <div className="flex items-center gap-2">
              {hasPermission('finance.export') && (
                <button 
                  onClick={handleExportInvoicesPDF}
                  className="px-4 py-2 text-sm font-medium rounded-lg border border-border hover:bg-accent transition-colors flex items-center gap-2"
                >
                  <Download size={16} />
                  Export PDF
                </button>
              )}
              <button 
                onClick={() => {
                  setShowAllInvoices(!showAllInvoices);
                  toast.info(showAllInvoices ? 'Showing limited invoices' : 'Displaying all invoices');
                }}
                className="px-4 py-2 text-sm font-medium rounded-lg border border-border hover:bg-accent transition-colors"
              >
                {showAllInvoices ? 'Show Less' : 'Show All Invoices'}
              </button>
            </div>
          </div>
          {showAllInvoices ? (
            <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">Invoice</th>
                      {activeTab !== 'client_invoices' && (
                        <th className="px-4 py-3 font-medium">Assigned Order</th>
                      )}
                      {activeTab !== 'engineer_invoices' && (
                        <th className="px-4 py-3 font-medium">Requested Order</th>
                      )}
                      {activeTab === 'invoices' ? (
                        <>
                          <th className="px-4 py-3 font-medium">Engineer Amount</th>
                          <th className="px-4 py-3 font-medium">Client Amount</th>
                        </>
                      ) : (
                        <th className="px-4 py-3 font-medium">{activeTab === 'client_invoices' ? 'Client Amount' : 'Engineer Amount'}</th>
                      )}
                      <th className="px-4 py-3 font-medium">Issue Date</th>
                      <th className="px-4 py-3 font-medium">Issued Month</th>
                      <th className="px-4 py-3 font-medium">Due Date</th>
                      <th className="px-4 py-3 font-medium">Completed Date</th>
                      {activeTab === 'invoices' ? (
                        <>
                          <th className="px-4 py-3 font-medium">Eng. Status</th>
                          <th className="px-4 py-3 font-medium">Client Status</th>
                        </>
                      ) : (
                        <th className="px-4 py-3 font-medium">{activeTab === 'client_invoices' ? 'Client Status' : 'Engineer Status'}</th>
                      )}
                      <th className="px-4 py-3 font-medium text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {invoices.map((inv) => (
                      <tr key={inv.id} className="hover:bg-accent/30 transition-colors group">
                        <td className="px-4 py-4 font-medium">{inv.id}</td>
                        {activeTab !== 'client_invoices' && (
                          <td className="px-4 py-4">{inv.assignedOrder}</td>
                        )}
                        {activeTab !== 'engineer_invoices' && (
                          <td className="px-4 py-4 text-muted-foreground">{inv.requestedOrder}</td>
                        )}
                        {activeTab === 'invoices' ? (
                          <>
                            <td className="px-4 py-4 font-bold">{inv.amount}</td>
                            <td className="px-4 py-4 font-bold text-emerald-600">{inv.clientAmount}</td>
                          </>
                        ) : (
                          <td className="px-4 py-4 font-bold">
                            {activeTab === 'client_invoices' ? inv.clientAmount : inv.amount}
                          </td>
                        )}
                        <td className="px-4 py-4 text-muted-foreground">{inv.issueDate}</td>
                        <td className="px-4 py-4 text-muted-foreground">
                          {inv.issuedMonth ? (inv.issuedMonth.includes('-') ? new Date(parseInt(inv.issuedMonth.split('-')[0]), parseInt(inv.issuedMonth.split('-')[1]) - 1).toLocaleString('default', { month: 'long', year: 'numeric' }) : inv.issuedMonth) : '-'}
                        </td>
                        <td className="px-4 py-4 text-muted-foreground">{inv.dueDate}</td>
                        <td className="px-4 py-4 text-muted-foreground">{inv.completedDate || '-'}</td>
                        {activeTab === 'invoices' ? (
                          <>
                            <td className="px-4 py-4">
                              <span className={cn(
                                "inline-flex items-center rounded-full px-2.5 py-0.5 text-[10px] font-medium",
                                inv.engineerStatus === 'Paid' ? "bg-green-500/10 text-green-500" :
                                inv.engineerStatus === 'Overdue' ? "bg-red-500/10 text-red-500" :
                                "bg-yellow-500/10 text-yellow-500"
                              )}>
                                {inv.engineerStatus}
                              </span>
                            </td>
                            <td className="px-4 py-4">
                              <span className={cn(
                                "inline-flex items-center rounded-full px-2.5 py-0.5 text-[10px] font-medium",
                                inv.clientStatus === 'Paid' ? "bg-green-500/10 text-green-500" :
                                inv.clientStatus === 'Overdue' ? "bg-red-500/10 text-red-500" :
                                "bg-yellow-500/10 text-yellow-500"
                              )}>
                                {inv.clientStatus}
                              </span>
                            </td>
                          </>
                        ) : (
                          <td className="px-4 py-4">
                            <span className={cn(
                              "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",
                              inv.status === 'Paid' ? "bg-green-500/10 text-green-500" :
                              inv.status === 'Overdue' ? "bg-red-500/10 text-red-500" :
                              "bg-yellow-500/10 text-yellow-500"
                            )}>
                              {inv.status}
                            </span>
                          </td>
                        )}
                        <td className="px-4 py-4 text-right">
                          <div className="flex justify-end gap-2">
                            <button 
                              onClick={() => handleEditInvoice(inv)}
                              className="p-2 rounded-lg border border-border hover:bg-accent transition-colors text-muted-foreground"
                              title="Edit"
                            >
                              <Edit size={14} />
                            </button>
                            {activeTab === 'invoices' ? (
                              <>
                                <button 
                                  onClick={() => handleExportRowPDF(inv)}
                                  className="p-2 rounded-lg border border-border hover:bg-accent transition-colors text-orange-500"
                                  title="Download Row Report (PDF)"
                                >
                                  <FileText size={14} />
                                </button>
                                <button 
                                  onClick={() => handleDownloadInvoice(inv, false)}
                                  className="p-2 rounded-lg border border-border hover:bg-accent transition-colors text-blue-500"
                                  title="Download Engineer Invoice (PDF)"
                                >
                                  <Download size={14} />
                                </button>
                                <button 
                                  onClick={() => handleDownloadInvoice(inv, true)}
                                  className="p-2 rounded-lg border border-border hover:bg-accent transition-colors text-emerald-600"
                                  title="Download Client Invoice (PDF)"
                                >
                                  <Download size={14} />
                                </button>
                              </>
                            ) : (
                              <>
                                <button 
                                  onClick={() => handleExportRowPDF(inv)}
                                  className="p-2 rounded-lg border border-border hover:bg-accent transition-colors text-orange-500"
                                  title="Download Row Report (PDF)"
                                >
                                  <FileText size={14} />
                                </button>
                                <button 
                                  onClick={() => handleDownloadInvoice(inv)}
                                  className="p-2 rounded-lg border border-border hover:bg-accent transition-colors"
                                  title="Download Invoice (PDF)"
                                >
                                  <Download size={14} />
                                </button>
                              </>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ) : (
            <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
              {invoices.slice(0, 3).map((inv) => (
                <div key={inv.id} className="rounded-xl border border-border bg-card p-6 shadow-sm hover:shadow-md transition-all">
                  <div className="flex items-start justify-between mb-4">
                    <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center text-primary">
                      <FileText size={20} />
                    </div>
                    {activeTab === 'invoices' ? (
                      <div className="flex gap-2">
                        <span className={cn(
                          "inline-flex items-center rounded-full px-2.5 py-0.5 text-[10px] font-medium",
                          inv.engineerStatus === 'Paid' ? "bg-green-500/10 text-green-500" :
                          inv.engineerStatus === 'Overdue' ? "bg-red-500/10 text-red-500" :
                          "bg-yellow-500/10 text-yellow-500"
                        )}>
                          Eng: {inv.engineerStatus}
                        </span>
                        <span className={cn(
                          "inline-flex items-center rounded-full px-2.5 py-0.5 text-[10px] font-medium",
                          inv.clientStatus === 'Paid' ? "bg-green-500/10 text-green-500" :
                          inv.clientStatus === 'Overdue' ? "bg-red-500/10 text-red-500" :
                          "bg-yellow-500/10 text-yellow-500"
                        )}>
                          Cli: {inv.clientStatus}
                        </span>
                      </div>
                    ) : (
                      <span className={cn(
                        "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",
                        inv.status === 'Paid' ? "bg-green-500/10 text-green-500" :
                        inv.status === 'Overdue' ? "bg-red-500/10 text-red-500" :
                        "bg-yellow-500/10 text-yellow-500"
                      )}>
                        {activeTab === 'client_invoices' ? 'Cli: ' : 'Eng: '}{inv.status}
                      </span>
                    )}
                  </div>
                  {activeTab !== 'client_invoices' && (
                    <h3 className="font-bold mb-1">{inv.assignedOrder}</h3>
                  )}
                  {activeTab !== 'engineer_invoices' && (
                    <>
                      <p className="text-xs text-muted-foreground mb-1 uppercase font-bold">Requested Order</p>
                      <p className="text-sm text-primary font-medium mb-1">{inv.requestedOrder}</p>
                    </>
                  )}
                  <p className="text-xs text-muted-foreground mb-1">{inv.id}</p>
                  <p className="text-xs font-medium text-primary mb-4">Issued: {inv.issuedMonth ? (inv.issuedMonth.includes('-') ? new Date(parseInt(inv.issuedMonth.split('-')[0]), parseInt(inv.issuedMonth.split('-')[1]) - 1).toLocaleString('default', { month: 'long', year: 'numeric' }) : inv.issuedMonth) : '-'}</p>
                  <div className="flex items-center justify-between pt-4 border-t border-border">
                    {activeTab === 'invoices' ? (
                      <div className="flex gap-4">
                        <div>
                          <p className="text-[10px] text-muted-foreground uppercase font-bold">Engineer</p>
                          <p className="font-bold text-sm">{inv.amount}</p>
                        </div>
                        <div>
                          <p className="text-[10px] text-emerald-600 uppercase font-bold">Client</p>
                          <p className="font-bold text-sm text-emerald-600">{inv.clientAmount}</p>
                        </div>
                      </div>
                    ) : (
                      <div>
                        <p className="text-xs text-muted-foreground">{activeTab === 'client_invoices' ? 'Client Amount' : 'Engineer Amount'}</p>
                        <p className="font-bold text-lg">
                          {activeTab === 'client_invoices' ? inv.clientAmount : inv.amount}
                        </p>
                      </div>
                    )}
                    <div className="text-right">
                      <p className="text-xs text-muted-foreground">Completed Date</p>
                      <p className="text-sm font-medium">{inv.completedDate || '-'}</p>
                    </div>
                  </div>
                  <div className="mt-4 flex gap-2">
                    <button 
                      onClick={() => handleEditInvoice(inv)}
                      className="flex-1 py-2 text-xs font-medium rounded-lg border border-border hover:bg-accent transition-colors flex items-center justify-center gap-2"
                    >
                      <Edit size={14} />
                      Edit
                    </button>
                    {activeTab === 'invoices' ? (
                      <div className="flex-[3] flex gap-2">
                        <button 
                          onClick={() => handleExportRowPDF(inv)}
                          className="flex-1 py-2 text-xs font-medium rounded-lg border border-border hover:bg-accent transition-colors flex items-center justify-center gap-1 text-orange-500"
                          title="PDF Report"
                        >
                          <FileText size={14} />
                        </button>
                        <button 
                          onClick={() => handleDownloadInvoice(inv, false)}
                          className="flex-1 py-2 text-xs font-medium rounded-lg border border-border hover:bg-accent transition-colors flex items-center justify-center gap-1 text-blue-500"
                          title="Engineer PDF"
                        >
                          <Download size={14} />
                        </button>
                        <button 
                          onClick={() => handleDownloadInvoice(inv, true)}
                          className="flex-1 py-2 text-xs font-medium rounded-lg border border-border hover:bg-accent transition-colors flex items-center justify-center gap-1 text-emerald-600"
                          title="Client PDF"
                        >
                          <Download size={14} />
                        </button>
                      </div>
                    ) : (
                      <div className="flex-[3] flex gap-2">
                        <button 
                          onClick={() => handleExportRowPDF(inv)}
                          className="flex-1 py-2 text-xs font-medium rounded-lg border border-border hover:bg-accent transition-colors flex items-center justify-center gap-1 text-orange-500"
                        >
                          <FileText size={14} />
                          PDF
                        </button>
                        <button 
                          onClick={() => handleDownloadInvoice(inv)}
                          className="flex-[2] py-2 text-xs font-medium rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors flex items-center justify-center gap-2 shadow-sm"
                        >
                          <Download size={14} />
                          PDF
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Commission Invoice Modal */}
      {isCommissionModalOpen && (
        <div className="fixed inset-0 z-[110] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-2xl rounded-xl border border-border bg-card p-6 shadow-xl animate-in fade-in zoom-in duration-200 overflow-y-auto max-h-[90vh]">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="text-xl font-bold text-primary">Commission Invoice Template</h2>
                <p className="text-sm text-muted-foreground">Preview and edit invoice details</p>
              </div>
              <button 
                onClick={() => setIsCommissionModalOpen(false)}
                className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
                id="close-commission-modal"
              >
                <X size={20} />
              </button>
            </div>

            <div className="space-y-6">
              {/* Header Info */}
              <div className="grid grid-cols-2 gap-4 border-b border-border pb-4">
                <div className="space-y-2">
                  <label className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">Invoice ID</label>
                  <input
                    type="text"
                    value={commissionFormData.invoiceId}
                    onChange={(e) => setCommissionFormData({ ...commissionFormData, invoiceId: e.target.value })}
                    className="w-full bg-muted/30 border border-border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/20 outline-none"
                  />
                </div>
                <div className="space-y-2 text-right">
                  <label className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">Date</label>
                  <input
                    type="date"
                    value={commissionFormData.date}
                    onChange={(e) => setCommissionFormData({ ...commissionFormData, date: e.target.value })}
                    className="w-full bg-muted/30 border border-border rounded-lg px-3 py-2 text-sm text-right focus:ring-2 focus:ring-primary/20 outline-none"
                  />
                </div>
              </div>

              {/* From / Bill To */}
              <div className="grid grid-cols-2 gap-8">
                <div className="space-y-4">
                  <h4 className="text-xs font-bold text-primary uppercase tracking-widest border-l-2 border-primary pl-2 font-mono">From (Our Details)</h4>
                  <div className="space-y-3">
                    <input
                      type="text"
                      placeholder="Company Name"
                      value={commissionFormData.fromName}
                      onChange={(e) => setCommissionFormData({ ...commissionFormData, fromName: e.target.value })}
                      className="w-full border border-border rounded-lg px-3 py-2 text-sm font-bold bg-background focus:ring-2 focus:ring-primary/20 outline-none"
                    />
                    <input
                      type="email"
                      placeholder="Email"
                      value={commissionFormData.fromEmail}
                      onChange={(e) => setCommissionFormData({ ...commissionFormData, fromEmail: e.target.value })}
                      className="w-full border border-border rounded-lg px-3 py-2 text-xs bg-background focus:ring-2 focus:ring-primary/20 outline-none"
                    />
                    <textarea
                      placeholder="Address"
                      rows={2}
                      value={commissionFormData.fromAddress}
                      onChange={(e) => setCommissionFormData({ ...commissionFormData, fromAddress: e.target.value })}
                      className="w-full border border-border rounded-lg px-3 py-2 text-xs bg-background focus:ring-2 focus:ring-primary/20 outline-none"
                    />
                  </div>
                </div>

                <div className="space-y-4">
                  <h4 className="text-xs font-bold text-orange-500 uppercase tracking-widest border-l-2 border-orange-500 pl-2 font-mono">Bill To (Vendor Details)</h4>
                  <div className="space-y-3">
                    <input
                      type="text"
                      placeholder="Vendor Name"
                      value={commissionFormData.billToName}
                      onChange={(e) => setCommissionFormData({ ...commissionFormData, billToName: e.target.value })}
                      className="w-full border border-border rounded-lg px-3 py-2 text-sm font-bold bg-background focus:ring-2 focus:ring-orange-500/20 outline-none"
                    />
                    <input
                      type="email"
                      placeholder="Email (Optional)"
                      value={commissionFormData.billToEmail}
                      onChange={(e) => setCommissionFormData({ ...commissionFormData, billToEmail: e.target.value })}
                      className="w-full border border-border rounded-lg px-3 py-2 text-xs bg-background focus:ring-2 focus:ring-orange-500/20 outline-none"
                    />
                    <textarea
                      placeholder="Vendor Address"
                      rows={2}
                      value={commissionFormData.billToAddress}
                      onChange={(e) => setCommissionFormData({ ...commissionFormData, billToAddress: e.target.value })}
                      className="w-full border border-border rounded-lg px-3 py-2 text-xs bg-background focus:ring-2 focus:ring-orange-500/20 outline-none"
                    />
                  </div>
                </div>
              </div>

              {/* Items Table */}
              <div className="rounded-xl border border-border bg-muted/20 overflow-hidden">
                <table className="w-full text-left text-xs">
                  <thead className="bg-muted/50 border-b border-border">
                    <tr>
                      <th className="px-4 py-3 font-semibold w-1/2">Description</th>
                      <th className="px-4 py-3 font-semibold text-right">Amount</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    <tr className="bg-background">
                      <td className="px-4 py-3">
                        <input
                          type="text"
                          value={commissionFormData.description}
                          onChange={(e) => setCommissionFormData({ ...commissionFormData, description: e.target.value })}
                          className="w-full bg-transparent border-none focus:ring-0 p-0 font-medium"
                        />
                        <p className="text-[10px] text-muted-foreground mt-1">Ref: {commissionFormData.projectRef}</p>
                      </td>
                      <td className="px-4 py-3 text-right font-bold text-sm">
                        {commissionFormData.currency}{commissionFormData.amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                      </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 Commission</span>
                    <span className="font-bold text-lg text-primary">
                      {commissionFormData.currency}{commissionFormData.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={() => setIsCommissionModalOpen(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('COMMISSION INVOICE', 20, 28);
                    
                    doc.setFontSize(10);
                    doc.setTextColor(200, 200, 200);
                    doc.text(`Invoice ID: ${commissionFormData.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(commissionFormData.fromName, 20, fromY);
                    doc.setFont('helvetica', 'normal');
                    fromY += 5;
                    doc.text(commissionFormData.fromEmail, 20, fromY);
                    fromY += 5;
                    if (commissionFormData.fromPhone) {
                      doc.text(commissionFormData.fromPhone, 20, fromY);
                      fromY += 5;
                    }
                    if (commissionFormData.fromAddress) {
                      const splitFrom = doc.splitTextToSize(commissionFormData.fromAddress, 80);
                      doc.text(splitFrom, 20, fromY);
                    }
                    
                    // Bill To details
                    let toY = 68;
                    doc.setFont('helvetica', 'bold');
                    doc.text(commissionFormData.billToName, 110, toY);
                    doc.setFont('helvetica', 'normal');
                    toY += 5;
                    if (commissionFormData.billToEmail) {
                      doc.text(commissionFormData.billToEmail, 110, toY);
                      toY += 5;
                    }
                    if (commissionFormData.billToPhone) {
                      doc.text(commissionFormData.billToPhone, 110, toY);
                      toY += 5;
                    }
                    if (commissionFormData.billToAddress) {
                      const splitTo = doc.splitTextToSize(commissionFormData.billToAddress, 80);
                      doc.text(splitTo, 110, toY);
                    }

                    // Table
                    autoTable(doc, {
                      head: [['Description', 'Ref', 'Amount']],
                      body: [[
                        commissionFormData.description,
                        commissionFormData.projectRef,
                        `${commissionFormData.currency}${commissionFormData.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 COMMISSION:', 110, finalY);
                    doc.text(`${commissionFormData.currency}${commissionFormData.amount.toLocaleString()}`, 190, finalY, { align: 'right' });
                    
                    doc.save(`${commissionFormData.invoiceId}.pdf`);
                    toast.success('Commission Invoice generated');
                    setIsCommissionModalOpen(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>
  );
}

function FinanceStatCard({ title, value, icon: Icon, trend, trendType, description }: { title: string, value: string, icon: any, trend: string, trendType: 'up' | 'down' | 'neutral', description: string }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
      <div className="flex items-center justify-between mb-2">
        <div className="p-2 rounded-lg bg-accent text-muted-foreground">
          <Icon size={18} />
        </div>
        <div className={cn(
          "flex items-center gap-1 text-xs font-medium",
          trendType === 'up' ? "text-green-500" : trendType === 'down' ? "text-red-500" : "text-muted-foreground"
        )}>
          {trendType === 'up' && <ArrowUpRight size={14} />}
          {trendType === 'down' && <ArrowDownRight size={14} />}
          {trend}
        </div>
      </div>
      <div>
        <p className="text-sm text-muted-foreground">{title}</p>
        <p className="text-2xl font-bold">{value}</p>
        <p className="text-xs text-muted-foreground mt-1">{description}</p>
      </div>
    </div>
  );
}
