import React, { useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  TrendingUp, 
  Briefcase, 
  Users, 
  CheckSquare, 
  ArrowUpRight, 
  ArrowDownRight,
  Clock,
  Ticket,
  DollarSign,
  Eye,
  Download,
  X,
  FileText,
  Calendar,
  Database,
  Lock
} from 'lucide-react';
import { 
  AreaChart, 
  Area, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer,
  BarChart,
  Bar,
  Cell
} from 'recharts';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';
import { AnimatePresence, motion } from 'framer-motion';

const COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'];

export function Dashboard() {
  const { projects: allProjects, tasks: allTasks, expenses, engineers } = useApp();
  const { profile, hasPermission, logout } = useAuth();
  const navigate = useNavigate();

  const canViewAll = useMemo(() => {
    if (!profile) return false;
    return hasPermission('projects.view_all') || hasPermission('tasks.view_all') || profile.uid === 'admin-123';
  }, [profile, hasPermission]);

  const projects = useMemo(() => {
    if (canViewAll) return allProjects;
    return allProjects.filter(p => 
      p.assignedTo === profile?.name || 
      p.assignedEmail === profile?.email ||
      p.assignedRole === profile?.role
    );
  }, [allProjects, canViewAll, profile]);

  const tasks = useMemo(() => {
    if (canViewAll) return allTasks;
    return allTasks.filter(t => t.assignee === profile?.name || t.assignee === profile?.email);
  }, [allTasks, canViewAll, profile]);

  const handleLogout = () => {
    logout();
    navigate('/login');
  };
  const [isRevenueModalOpen, setIsRevenueModalOpen] = React.useState(false);
  const [isEngineerExpensesModalOpen, setIsEngineerExpensesModalOpen] = React.useState(false);
  const [isCompanyExpensesModalOpen, setIsCompanyExpensesModalOpen] = React.useState(false);
  const [isNetProfitModalOpen, setIsNetProfitModalOpen] = React.useState(false);
  const [isPendingClientPaymentModalOpen, setIsPendingClientPaymentModalOpen] = React.useState(false);
  const [isPendingEngineerPaymentModalOpen, setIsPendingEngineerPaymentModalOpen] = React.useState(false);
  const [isCompletedProjectsModalOpen, setIsCompletedProjectsModalOpen] = React.useState(false);
  const [isPendingProjectsModalOpen, setIsPendingProjectsModalOpen] = React.useState(false);
  const [isEmployeesModalOpen, setIsEmployeesModalOpen] = React.useState(false);
  const [isEngineersModalOpen, setIsEngineersModalOpen] = React.useState(false);

  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 formatDate = (dateStr?: string) => {
    if (!dateStr) return '-';
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr;
      return date.toLocaleDateString('en-GB', {
        day: 'numeric',
        month: 'long',
        year: 'numeric'
      });
    } catch (e) {
      return dateStr;
    }
  };

  const stats = useMemo(() => {
    let companyRevenue = 0;
    let engineerExpenses = 0;
    let pendingClientPayment = 0;
    let pendingEngineerPayment = 0;
    
    let prevCompanyRevenue = 0;
    let prevEngineerExpenses = 0;
    let prevCompanyExpenses = 0;
    
    const now = new Date();
    const currentMonthStr = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`;
    const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
    const prevMonthStr = `${prevMonthDate.getFullYear()}-${(prevMonthDate.getMonth() + 1).toString().padStart(2, '0')}`;

    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 });
    }

    const engineerPerformanceMap = new Map<string, number>();

    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));

      companyRevenue += clientAmount;
      engineerExpenses += internalAmount;

      const pMonth = p.issuedMonth || (p.issueDate ? p.issueDate.substring(0, 7) : '');
      if (pMonth === prevMonthStr) {
        prevCompanyRevenue += clientAmount;
        prevEngineerExpenses += internalAmount;
      }

      // Pending payments
      if (p.clientInvoiceStatus !== 'Paid') {
        pendingClientPayment += clientAmount;
      }
      if (p.engineerInvoiceStatus !== 'Paid') {
        pendingEngineerPayment += internalAmount;
      }

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

      if (p.assignedTo) {
        engineerPerformanceMap.set(p.assignedTo, (engineerPerformanceMap.get(p.assignedTo) || 0) + 1);
      }
    });

    const companyExpenses = expenses.reduce((sum, ex) => sum + (ex.amount || 0), 0);
    expenses.forEach(ex => {
      const exMonth = (ex.date || '').substring(0, 7);
      if (exMonth === prevMonthStr) {
        prevCompanyExpenses += (ex.amount || 0);
      }
    });

    const netProfit = companyRevenue - engineerExpenses - companyExpenses;
    const prevNetProfit = prevCompanyRevenue - prevEngineerExpenses - prevCompanyExpenses;

    const calculateChange = (current: number, previous: number) => {
      if (previous === 0) return current > 0 ? '+100%' : '0%';
      const change = ((current - previous) / previous) * 100;
      return `${change >= 0 ? '+' : ''}${change.toFixed(1)}%`;
    };

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

    const performanceData = Array.from(engineerPerformanceMap.entries())
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 5);

    const completedProjects = projects.filter(p => p.status === 'Completed').length;
    const pendingProjects = projects.filter(p => p.status !== 'Completed').length;
    
    const completedThisMonth = projects.filter(p => p.status === 'Completed' && (p.completedDate || '').substring(0, 7) === currentMonthStr).length;
    const pendingClientCount = projects.filter(p => p.clientInvoiceStatus !== 'Paid' && p.clientTotalAmount && p.clientTotalAmount > 0).length;
    const pendingEngineerCount = projects.filter(p => p.engineerInvoiceStatus !== 'Paid' && p.totalAmount && p.totalAmount > 0).length;

    // Unique employees from tasks and projects
    const employees = new Set<string>();
    projects.forEach(p => { if (p.assignedTo) employees.add(p.assignedTo); });
    tasks.forEach(t => { if (t.assignee) employees.add(t.assignee); });

    return {
      companyRevenue,
      engineerExpenses,
      companyExpenses,
      netProfit,
      pendingClientPayment,
      pendingEngineerPayment,
      completedProjects,
      pendingProjects,
      totalEmployees: employees.size,
      totalEngineers: engineers.length,
      revenueChartData,
      performanceData,
      completedThisMonth,
      pendingClientCount,
      pendingEngineerCount,
      changes: {
        revenue: calculateChange(companyRevenue, prevCompanyRevenue),
        engExpenses: calculateChange(engineerExpenses, prevEngineerExpenses),
        compExpenses: calculateChange(companyExpenses, prevCompanyExpenses),
        profit: calculateChange(netProfit, prevNetProfit)
      }
    };
  }, [projects, tasks, expenses, engineers]);

  const recentActivities = useMemo(() => {
    const activities: any[] = [];
    
    projects.slice(0, 3).forEach(p => {
      activities.push({
        id: `p-${p.id}`,
        action: `Project ${p.name} updated`,
        time: 'Recently',
        color: p.status === 'Completed' ? 'bg-green-500' : 'bg-blue-500'
      });
    });

    tasks.slice(0, 2).forEach(t => {
      activities.push({
        id: `t-${t.id}`,
        action: `Task ${t.title} assigned`,
        time: 'Recently',
        color: 'bg-purple-500'
      });
    });

    return activities.slice(0, 5);
  }, [projects, tasks]);

  const pendingApprovals = useMemo(() => {
    return projects
      .filter(p => p.status === 'Pending' || p.status === 'Planning')
      .slice(0, 3)
      .map(p => ({
        id: p.id,
        type: 'Project Approval',
        user: p.client || 'New Client',
        date: formatDate(p.issueDate)
      }));
  }, [projects]);

  const assignedTasks = useMemo(() => {
    return tasks
      .filter(t => t.status !== 'Completed')
      .slice(0, 3)
      .map(t => ({
        id: t.id,
        task: t.title,
        due: formatDate(t.dueDate),
        priority: t.status === 'In Progress' ? 'High' : 'Medium'
      }));
  }, [tasks]);

  const handleReview = (type: string, user: string) => {
    toast.info(`Reviewing ${type} for ${user}`, {
      description: 'Loading document details...',
    });
  };

  const formatCurrency = (val: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      notation: 'compact',
      maximumFractionDigits: 3
    }).format(val);
  };

  const formatCurrencyFull = (val: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      maximumFractionDigits: 2
    }).format(val);
  };

  const revenueDetails = useMemo(() => {
    return projects.map(p => {
      const hours = parseTotalTime(p.totalTime);
      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));
      
      return {
        id: p.id,
        name: p.name,
        client: p.client,
        amount: clientAmount,
        date: p.issueDate || p.deadline,
        status: p.clientInvoiceStatus || 'Unpaid'
      };
    }).filter(r => r.amount > 0).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [projects]);

  const engineerExpensesDetails = useMemo(() => {
    return projects.map(p => {
      const hours = parseTotalTime(p.totalTime);
      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));
      
      return {
        id: p.id,
        name: p.name,
        engineer: p.assignedTo || 'Unassigned',
        amount: internalAmount,
        date: p.issueDate || p.deadline,
        status: p.engineerInvoiceStatus || 'Unpaid'
      };
    }).filter(r => r.amount > 0).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [projects]);

  const companyExpensesDetails = useMemo(() => {
    return expenses.map(ex => ({
      id: ex.id,
      description: ex.description,
      category: ex.category,
      amount: ex.amount || 0,
      date: ex.date,
      status: ex.status || 'Pending'
    })).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [expenses]);

  const netProfitDetails = useMemo(() => {
    return projects.map(p => {
      const hours = parseTotalTime(p.totalTime);
      
      // 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));

      // 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));
      
      const profit = clientAmount - internalAmount;

      return {
        id: p.id,
        name: p.name,
        revenue: clientAmount,
        expense: internalAmount,
        profit: profit,
        date: p.issueDate || p.deadline,
        status: p.status
      };
    }).filter(r => r.revenue > 0 || r.expense > 0).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [projects]);

  const pendingClientPaymentDetails = useMemo(() => {
    return projects.map(p => {
      const hours = parseTotalTime(p.totalTime);
      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));
      
      return {
        id: p.id,
        name: p.name,
        client: p.client,
        amount: clientAmount,
        date: p.issueDate || p.deadline,
        status: p.clientInvoiceStatus || 'Unpaid'
      };
    }).filter(r => r.amount > 0 && r.status !== 'Paid').sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [projects]);

  const pendingEngineerPaymentDetails = useMemo(() => {
    return projects.map(p => {
      const hours = parseTotalTime(p.totalTime);
      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));
      
      return {
        id: p.id,
        name: p.name,
        engineer: p.assignedTo || 'Unassigned',
        amount: internalAmount,
        date: p.issueDate || p.deadline,
        status: p.engineerInvoiceStatus || 'Unpaid'
      };
    }).filter(r => r.amount > 0 && r.status !== 'Paid').sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [projects]);

  const completedProjectsDetails = useMemo(() => {
    return projects
      .filter(p => p.status === 'Completed')
      .map(p => ({
        id: p.id,
        name: p.name,
        client: p.client,
        engineer: p.assignedTo || 'Unassigned',
        date: p.deadline || p.issueDate,
        revenue: (p.clientTotalAmount || 0)
      }))
      .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [projects]);

  const pendingProjectsDetails = useMemo(() => {
    return projects
      .filter(p => p.status !== 'Completed')
      .map(p => ({
        id: p.id,
        name: p.name,
        client: p.client,
        engineer: p.assignedTo || 'Unassigned',
        date: p.deadline || p.issueDate,
        status: p.status
      }))
      .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [projects]);

  const employeesDetails = useMemo(() => {
    const empMap = new Map<string, { projects: number, tasks: number }>();
    
    projects.forEach(p => {
      if (p.assignedTo) {
        const current = empMap.get(p.assignedTo) || { projects: 0, tasks: 0 };
        empMap.set(p.assignedTo, { ...current, projects: current.projects + 1 });
      }
    });
    
    tasks.forEach(t => {
      if (t.assignee) {
        const current = empMap.get(t.assignee) || { projects: 0, tasks: 0 };
        empMap.set(t.assignee, { ...current, tasks: current.tasks + 1 });
      }
    });
    
    return Array.from(empMap.entries()).map(([name, counts]) => ({
      name,
      ...counts,
      total: counts.projects + counts.tasks
    })).sort((a, b) => b.total - a.total);
  }, [projects, tasks]);

  const engineersDetails = useMemo(() => {
    return engineers.map(eng => {
      const activeProjects = projects.filter(p => p.assignedTo === eng.name && p.status !== 'Completed').length;
      return {
        id: eng.id,
        name: eng.name,
        specialization: eng.specialization || 'General',
        activeProjects,
        email: eng.email || 'N/A'
      };
    }).sort((a, b) => b.activeProjects - a.activeProjects);
  }, [engineers, projects]);

  const handleDownloadRevenue = () => {
    const headers = ['Project ID', 'Project Name', 'Client', 'Amount', 'Date', 'Status'];
    const csvContent = [
      headers.join(','),
      ...revenueDetails.map(r => [
        r.id,
        `"${r.name}"`,
        `"${r.client}"`,
        r.amount.toFixed(2),
        r.date,
        r.status
      ].join(','))
    ].join('\n');

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

  const handleDownloadEngineerExpenses = () => {
    const headers = ['Project ID', 'Project Name', 'Engineer', 'Amount', 'Date', 'Status'];
    const csvContent = [
      headers.join(','),
      ...engineerExpensesDetails.map(e => [
        e.id,
        `"${e.name}"`,
        `"${e.engineer}"`,
        e.amount.toFixed(2),
        e.date,
        e.status
      ].join(','))
    ].join('\n');

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

  const handleDownloadCompanyExpenses = () => {
    const headers = ['Expense ID', 'Description', 'Category', 'Amount', 'Date', 'Status'];
    const csvContent = [
      headers.join(','),
      ...companyExpensesDetails.map(ex => [
        ex.id,
        `"${ex.description}"`,
        `"${ex.category}"`,
        ex.amount.toFixed(2),
        ex.date,
        ex.status
      ].join(','))
    ].join('\n');

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

  const handleDownloadNetProfit = () => {
    const headers = ['Project ID', 'Project Name', 'Revenue', 'Engineer Expense', 'Net Profit', 'Date', 'Status'];
    const csvContent = [
      headers.join(','),
      ...netProfitDetails.map(n => [
        n.id,
        `"${n.name}"`,
        n.revenue.toFixed(2),
        n.expense.toFixed(2),
        n.profit.toFixed(2),
        n.date,
        n.status
      ].join(','))
    ].join('\n');

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

  const handleDownloadPendingClientPayment = () => {
    const headers = ['Project ID', 'Project Name', 'Client', 'Amount', 'Date', 'Status'];
    const csvContent = [
      headers.join(','),
      ...pendingClientPaymentDetails.map(p => [
        p.id,
        `"${p.name}"`,
        `"${p.client}"`,
        p.amount.toFixed(2),
        p.date,
        p.status
      ].join(','))
    ].join('\n');

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

  const handleDownloadPendingEngineerPayment = () => {
    const headers = ['Project ID', 'Project Name', 'Engineer', 'Amount', 'Date', 'Status'];
    const csvContent = [
      headers.join(','),
      ...pendingEngineerPaymentDetails.map(p => [
        p.id,
        `"${p.name}"`,
        `"${p.engineer}"`,
        p.amount.toFixed(2),
        p.date,
        p.status
      ].join(','))
    ].join('\n');

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

  const handleDownloadCompletedProjects = () => {
    const headers = ['Project ID', 'Project Name', 'Client', 'Engineer', 'Completion Date', 'Revenue'];
    const csvContent = [
      headers.join(','),
      ...completedProjectsDetails.map(p => [
        p.id,
        `"${p.name}"`,
        `"${p.client}"`,
        `"${p.engineer}"`,
        p.date,
        p.revenue.toFixed(2)
      ].join(','))
    ].join('\n');

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

  const handleDownloadPendingProjects = () => {
    const headers = ['Project ID', 'Project Name', 'Client', 'Engineer', 'Deadline', 'Status'];
    const csvContent = [
      headers.join(','),
      ...pendingProjectsDetails.map(p => [
        p.id,
        `"${p.name}"`,
        `"${p.client}"`,
        `"${p.engineer}"`,
        p.date,
        p.status
      ].join(','))
    ].join('\n');

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

  const handleDownloadEmployees = () => {
    const headers = ['Employee Name', 'Active Projects', 'Active Tasks', 'Total Involvement'];
    const csvContent = [
      headers.join(','),
      ...employeesDetails.map(e => [
        `"${e.name}"`,
        e.projects,
        e.tasks,
        e.total
      ].join(','))
    ].join('\n');

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

  const handleDownloadEngineers = () => {
    const headers = ['Engineer ID', 'Name', 'Specialization', 'Active Projects', 'Email'];
    const csvContent = [
      headers.join(','),
      ...engineersDetails.map(e => [
        e.id,
        `"${e.name}"`,
        `"${e.specialization}"`,
        e.activeProjects,
        `"${e.email}"`
      ].join(','))
    ].join('\n');

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

  if (!hasPermission('dashboard.view')) {
    return (
      <div className="flex h-[80vh] flex-col items-center justify-center text-center p-6">
        <div className="h-20 w-20 rounded-full bg-muted flex items-center justify-center mb-6">
          <Lock size={40} className="text-muted-foreground" />
        </div>
        <h2 className="text-2xl font-bold tracking-tight mb-2">Access Restricted</h2>
        <p className="text-muted-foreground max-w-md mx-auto mb-8">
          You do not have permission to view the Dashboard. Please contact your system administrator to request access.
        </p>
        <div className="flex flex-col sm:flex-row gap-3 justify-center">
          <button 
            onClick={() => navigate('/profile')}
            className="px-6 py-2 bg-primary text-primary-foreground rounded-lg font-semibold hover:bg-primary/90 transition-all"
          >
            Go to My Profile
          </button>
          <button 
            onClick={handleLogout}
            className="px-6 py-2 border border-border bg-card hover:bg-accent rounded-lg font-semibold transition-all"
          >
            Logout
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="space-y-1">
          <h1 className="text-3xl font-bold tracking-tight">
            {canViewAll ? 'Management Dashboard' : 'Employee Dashboard'}
          </h1>
          <p className="text-sm text-muted-foreground">Welcome back, {profile?.name || 'User'}. Here's what's happening today.</p>
        </div>
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Clock size={16} />
          Last updated: Just now
        </div>
      </div>

      {/* KPI Widgets */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 xl:grid-cols-5">
        {hasPermission('finance.view') && (
          <KPICard 
            title="Company Revenue" 
            value={formatCurrency(stats.companyRevenue)} 
            change={stats.changes.revenue} 
            trend={stats.changes.revenue.startsWith('+') ? "up" : "down"} 
            icon={TrendingUp} 
            onClick={() => setIsRevenueModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsRevenueModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadRevenue(); } }
            ]}
          />
        )}
        {hasPermission('finance.view') && (
          <KPICard 
            title="Engineers Expenses" 
            value={formatCurrency(stats.engineerExpenses)} 
            change={stats.changes.engExpenses} 
            trend={stats.changes.engExpenses.startsWith('+') ? "up" : "down"} 
            icon={DollarSign} 
            onClick={() => setIsEngineerExpensesModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsEngineerExpensesModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadEngineerExpenses(); } }
            ]}
          />
        )}
        {hasPermission('finance.view') && (
          <KPICard 
            title="Company Expenses" 
            value={formatCurrency(stats.companyExpenses)} 
            change={stats.changes.compExpenses} 
            trend={stats.changes.compExpenses.startsWith('+') ? "up" : "down"} 
            icon={DollarSign} 
            onClick={() => setIsCompanyExpensesModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsCompanyExpensesModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadCompanyExpenses(); } }
            ]}
          />
        )}
        {hasPermission('finance.view') && (
          <KPICard 
            title="Net Profit" 
            value={formatCurrency(stats.netProfit)} 
            change={stats.changes.profit} 
            trend={stats.changes.profit.startsWith('+') ? "up" : "down"} 
            icon={TrendingUp} 
            onClick={() => setIsNetProfitModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsNetProfitModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadNetProfit(); } }
            ]}
          />
        )}
        {hasPermission('finance.view') && (
          <KPICard 
            title="Pending Client Pmt" 
            value={formatCurrency(stats.pendingClientPayment)} 
            change={`${stats.pendingClientCount} invoices`} 
            trend="down" 
            icon={Clock} 
            onClick={() => setIsPendingClientPaymentModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsPendingClientPaymentModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadPendingClientPayment(); } }
            ]}
          />
        )}
        {hasPermission('finance.view') && (
          <KPICard 
            title="Pending Engineer Pmt" 
            value={formatCurrency(stats.pendingEngineerPayment)} 
            change={`${stats.pendingEngineerCount} invoices`} 
            trend="down" 
            icon={Clock} 
            onClick={() => setIsPendingEngineerPaymentModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsPendingEngineerPaymentModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadPendingEngineerPayment(); } }
            ]}
          />
        )}
        {hasPermission('projects.view') && (
          <KPICard 
            title="Completed Projects" 
            value={stats.completedProjects.toString()} 
            change={`+${stats.completedThisMonth} this month`} 
            trend="up" 
            icon={CheckSquare} 
            onClick={() => setIsCompletedProjectsModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsCompletedProjectsModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadCompletedProjects(); } }
            ]}
          />
        )}
        {hasPermission('projects.view') && (
          <KPICard 
            title="Pending Projects" 
            value={stats.pendingProjects.toString()} 
            change={`${stats.pendingProjects} active`} 
            trend="up" 
            icon={Briefcase} 
            onClick={() => setIsPendingProjectsModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsPendingProjectsModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadPendingProjects(); } }
            ]}
          />
        )}
        {hasPermission('hr.view') && (
          <KPICard 
            title="Total Employees" 
            value={stats.totalEmployees.toString()} 
            change="Active team" 
            trend="up" 
            icon={Users} 
            onClick={() => setIsEmployeesModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsEmployeesModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadEmployees(); } }
            ]}
          />
        )}
        {hasPermission('hr.view') && (
          <KPICard 
            title="Total Engineers" 
            value={stats.totalEngineers.toString()} 
            change="Specialists" 
            trend="up" 
            icon={Users} 
            onClick={() => setIsEngineersModalOpen(true)}
            actions={[
              { icon: Eye, label: 'View', onClick: (e: any) => { e.stopPropagation(); setIsEngineersModalOpen(true); } },
              { icon: Download, label: 'Download', onClick: (e: any) => { e.stopPropagation(); handleDownloadEngineers(); } }
            ]}
          />
        )}
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
        {/* Revenue Chart */}
        {hasPermission('finance.view') && (
          <div className="col-span-4 rounded-xl border border-border bg-card p-6 shadow-sm">
            <div className="mb-4 flex items-center justify-between">
              <h3 className="font-semibold">Revenue Overview</h3>
              <select 
                onChange={(e) => toast.info(`Switching view to: ${e.target.value}`)}
                className="bg-transparent text-sm text-muted-foreground outline-none"
              >
                <option>Last 6 Months</option>
                <option>Last Year</option>
              </select>
            </div>
            <div className="h-[300px] w-full">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={stats.revenueChartData}>
                  <defs>
                    <linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3}/>
                      <stop offset="95%" stopColor="#3b82f6" stopOpacity={0}/>
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="rgba(255,255,255,0.1)" />
                  <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{fontSize: 12}} />
                  <YAxis axisLine={false} tickLine={false} tick={{fontSize: 12}} tickFormatter={(val) => formatCurrency(val)} />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#1e293b', border: 'none', borderRadius: '8px', color: '#fff' }}
                    itemStyle={{ color: '#fff' }}
                  />
                  <Area type="monotone" dataKey="value" stroke="#3b82f6" fillOpacity={1} fill="url(#colorValue)" />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>
        )}

        {/* Performance Snapshot */}
        {hasPermission('hr.view') && (
          <div className={cn(
            "rounded-xl border border-border bg-card p-6 shadow-sm",
            hasPermission('finance.view') ? "col-span-3" : "col-span-7"
          )}>
            <h3 className="mb-4 font-semibold">Engineer Project Distribution</h3>
            <div className="h-[300px] w-full">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={stats.performanceData} layout="vertical">
                  <XAxis type="number" hide />
                  <YAxis dataKey="name" type="category" axisLine={false} tickLine={false} tick={{fontSize: 12}} width={80} />
                  <Tooltip 
                    cursor={{fill: 'transparent'}}
                    contentStyle={{ backgroundColor: '#1e293b', border: 'none', borderRadius: '8px', color: '#fff' }}
                  />
                  <Bar dataKey="value" radius={[0, 4, 4, 0]}>
                    {stats.performanceData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>
        )}
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {/* Pending Approvals */}
        {hasPermission('projects.view') && (
          <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
            <h3 className="mb-4 font-semibold">Pending Project Approvals</h3>
            <div className="space-y-4">
              {pendingApprovals.length > 0 ? pendingApprovals.map((item) => (
                <div key={item.id} className="flex items-center justify-between border-b border-border pb-3 last:border-0 last:pb-0">
                  <div>
                    <p className="text-sm font-medium">{item.type}</p>
                    <p className="text-xs text-muted-foreground">{item.user} • {item.date}</p>
                  </div>
                  <button 
                    onClick={() => handleReview(item.type, item.user)}
                    className="text-xs font-medium text-primary hover:underline"
                  >
                    Review
                  </button>
                </div>
              )) : (
                <p className="text-sm text-muted-foreground">No pending approvals</p>
              )}
            </div>
          </div>
        )}

        {/* Activity Timeline */}
        {hasPermission('projects.view') && (
          <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
            <h3 className="mb-4 font-semibold">Recent Activity</h3>
            <div className="space-y-4">
              {recentActivities.length > 0 ? recentActivities.map((item) => (
                <div 
                  key={item.id} 
                  className="flex gap-3 cursor-pointer hover:bg-accent/50 p-1 rounded-lg transition-colors"
                  onClick={() => toast.info(`Viewing details for: ${item.action}`)}
                >
                  <div className={cn("mt-1.5 h-2 w-2 shrink-0 rounded-full", item.color)} />
                  <div>
                    <p className="text-sm font-medium">{item.action}</p>
                    <p className="text-xs text-muted-foreground">{item.time}</p>
                  </div>
                </div>
              )) : (
                <p className="text-sm text-muted-foreground">No recent activity</p>
              )}
            </div>
          </div>
        )}

        {/* Assigned Tasks */}
        {hasPermission('projects.view') && (
          <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
            <h3 className="mb-4 font-semibold">Upcoming Tasks</h3>
            <div className="space-y-4">
              {assignedTasks.length > 0 ? assignedTasks.map((item) => (
                <div 
                  key={item.id} 
                  className="flex items-center justify-between cursor-pointer hover:bg-accent/50 p-1 rounded-lg transition-colors"
                  onClick={() => toast.info(`Opening task: ${item.task}`)}
                >
                  <div className="flex items-center gap-3">
                    <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-accent">
                      <CheckSquare size={16} className="text-muted-foreground" />
                    </div>
                    <div>
                      <p className="text-sm font-medium">{item.task}</p>
                      <p className="text-xs text-muted-foreground">Due: {item.due}</p>
                    </div>
                  </div>
                  <span className={cn(
                    "rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider",
                    item.priority === 'High' ? "bg-red-500/10 text-red-500" : "bg-yellow-500/10 text-yellow-500"
                  )}>
                    {item.priority}
                  </span>
                </div>
              )) : (
                <p className="text-sm text-muted-foreground">No upcoming tasks</p>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Revenue Database Modal */}
      <AnimatePresence>
        {isRevenueModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <Database size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Revenue Database</h2>
                    <p className="text-xs text-muted-foreground">Detailed breakdown of all client revenue</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadRevenue}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsRevenueModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Project</th>
                        <th className="px-4 py-3">Client</th>
                        <th className="px-4 py-3">Date</th>
                        <th className="px-4 py-3">Status</th>
                        <th className="px-4 py-3 text-right">Amount</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {revenueDetails.length > 0 ? revenueDetails.map((rev) => (
                        <tr key={rev.id} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <FileText size={14} className="text-primary" />
                              <span className="font-medium">{rev.name}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-muted-foreground">{rev.client}</td>
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-1.5 text-xs">
                              <Calendar size={12} />
                              {rev.date}
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <span className={cn(
                              "px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",
                              rev.status === 'Paid' ? "bg-green-500/10 text-green-500" : "bg-yellow-500/10 text-yellow-500"
                            )}>
                              {rev.status}
                            </span>
                          </td>
                          <td className="px-4 py-4 text-right font-bold text-primary">
                            {formatCurrencyFull(rev.amount)}
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
                            No revenue data found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="text-sm">
                  <span className="text-muted-foreground">Total Revenue: </span>
                  <span className="font-bold text-lg text-primary">{formatCurrencyFull(stats.companyRevenue)}</span>
                </div>
                <button 
                  onClick={() => setIsRevenueModalOpen(false)}
                  className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                >
                  Close
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Engineer Expenses Database Modal */}
      <AnimatePresence>
        {isEngineerExpensesModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <Database size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Engineer Expenses Database</h2>
                    <p className="text-xs text-muted-foreground">Detailed breakdown of all engineer-related costs</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadEngineerExpenses}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsEngineerExpensesModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Project</th>
                        <th className="px-4 py-3">Engineer</th>
                        <th className="px-4 py-3">Date</th>
                        <th className="px-4 py-3">Status</th>
                        <th className="px-4 py-3 text-right">Amount</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {engineerExpensesDetails.length > 0 ? engineerExpensesDetails.map((exp) => (
                        <tr key={exp.id} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <FileText size={14} className="text-primary" />
                              <span className="font-medium">{exp.name}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-muted-foreground">{exp.engineer}</td>
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-1.5 text-xs">
                              <Calendar size={12} />
                              {formatDate(exp.date)}
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <span className={cn(
                              "px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",
                              exp.status === 'Paid' ? "bg-green-500/10 text-green-500" : "bg-yellow-500/10 text-yellow-500"
                            )}>
                              {exp.status}
                            </span>
                          </td>
                          <td className="px-4 py-4 text-right font-bold text-primary">
                            {formatCurrencyFull(exp.amount)}
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
                            No engineer expense data found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="text-sm">
                  <span className="text-muted-foreground">Total Engineer Expenses: </span>
                  <span className="font-bold text-lg text-primary">{formatCurrencyFull(stats.engineerExpenses)}</span>
                </div>
                <button 
                  onClick={() => setIsEngineerExpensesModalOpen(false)}
                  className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                >
                  Close
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Company Expenses Database Modal */}
      <AnimatePresence>
        {isCompanyExpensesModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <Database size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Company Expenses Database</h2>
                    <p className="text-xs text-muted-foreground">Detailed breakdown of all general company expenses</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadCompanyExpenses}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsCompanyExpensesModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Description</th>
                        <th className="px-4 py-3">Category</th>
                        <th className="px-4 py-3">Date</th>
                        <th className="px-4 py-3">Status</th>
                        <th className="px-4 py-3 text-right">Amount</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {companyExpensesDetails.length > 0 ? companyExpensesDetails.map((ex) => (
                        <tr key={ex.id} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <FileText size={14} className="text-primary" />
                              <span className="font-medium">{ex.description}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-muted-foreground">{ex.category}</td>
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-1.5 text-xs">
                              <Calendar size={12} />
                              {formatDate(ex.date)}
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <span className={cn(
                              "px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",
                              ex.status === 'Approved' ? "bg-green-500/10 text-green-500" : "bg-yellow-500/10 text-yellow-500"
                            )}>
                              {ex.status}
                            </span>
                          </td>
                          <td className="px-4 py-4 text-right font-bold text-primary">
                            {formatCurrencyFull(ex.amount)}
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
                            No company expense data found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="text-sm">
                  <span className="text-muted-foreground">Total Company Expenses: </span>
                  <span className="font-bold text-lg text-primary">{formatCurrencyFull(stats.companyExpenses)}</span>
                </div>
                <button 
                  onClick={() => setIsCompanyExpensesModalOpen(false)}
                  className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                >
                  Close
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Net Profit Database Modal */}
      <AnimatePresence>
        {isNetProfitModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-5xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <TrendingUp size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Net Profit Analysis</h2>
                    <p className="text-xs text-muted-foreground">Project-by-project breakdown of profit margins</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadNetProfit}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsNetProfitModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Project</th>
                        <th className="px-4 py-3 text-right">Revenue</th>
                        <th className="px-4 py-3 text-right">Eng. Cost</th>
                        <th className="px-4 py-3 text-right">Profit</th>
                        <th className="px-4 py-3">Date</th>
                        <th className="px-4 py-3">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {netProfitDetails.length > 0 ? netProfitDetails.map((n) => (
                        <tr key={n.id} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <FileText size={14} className="text-primary" />
                              <span className="font-medium">{n.name}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-right text-green-500 font-medium">
                            {formatCurrencyFull(n.revenue)}
                          </td>
                          <td className="px-4 py-4 text-right text-red-500 font-medium">
                            {formatCurrencyFull(n.expense)}
                          </td>
                          <td className={cn(
                            "px-4 py-4 text-right font-bold",
                            n.profit >= 0 ? "text-primary" : "text-red-600"
                          )}>
                            {formatCurrencyFull(n.profit)}
                          </td>
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-1.5 text-xs">
                              <Calendar size={12} />
                              {n.date}
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <span className={cn(
                              "px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",
                              n.status === 'Completed' ? "bg-green-500/10 text-green-500" : "bg-blue-500/10 text-blue-500"
                            )}>
                              {n.status}
                            </span>
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">
                            No profit data found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex flex-col gap-4">
                <div className="grid grid-cols-3 gap-4">
                  <div className="p-4 rounded-xl bg-card border border-border">
                    <p className="text-xs text-muted-foreground mb-1">Total Revenue</p>
                    <p className="text-xl font-bold text-green-500">{formatCurrencyFull(stats.companyRevenue)}</p>
                  </div>
                  <div className="p-4 rounded-xl bg-card border border-border">
                    <p className="text-xs text-muted-foreground mb-1">Total Expenses (Eng + Co)</p>
                    <p className="text-xl font-bold text-red-500">{formatCurrencyFull(stats.engineerExpenses + stats.companyExpenses)}</p>
                  </div>
                  <div className="p-4 rounded-xl bg-card border border-border">
                    <p className="text-xs text-muted-foreground mb-1">Net Profit</p>
                    <p className="text-xl font-bold text-primary">{formatCurrencyFull(stats.netProfit)}</p>
                  </div>
                </div>
                <div className="flex items-center justify-end">
                  <button 
                    onClick={() => setIsNetProfitModalOpen(false)}
                    className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                  >
                    Close
                  </button>
                </div>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Pending Client Payment Database Modal */}
      <AnimatePresence>
        {isPendingClientPaymentModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <Clock size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Pending Client Payments</h2>
                    <p className="text-xs text-muted-foreground">Detailed list of all unpaid client invoices</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadPendingClientPayment}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsPendingClientPaymentModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Project</th>
                        <th className="px-4 py-3">Client</th>
                        <th className="px-4 py-3 text-right">Amount</th>
                        <th className="px-4 py-3">Due Date</th>
                        <th className="px-4 py-3">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {pendingClientPaymentDetails.length > 0 ? pendingClientPaymentDetails.map((p) => (
                        <tr key={p.id} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <FileText size={14} className="text-primary" />
                              <span className="font-medium">{p.name}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-muted-foreground">{p.client}</td>
                          <td className="px-4 py-4 text-right font-bold text-primary">
                            {formatCurrencyFull(p.amount)}
                          </td>
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                              <Calendar size={12} />
                              {formatDate(p.date)}
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <span className={cn(
                              "px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-yellow-500/10 text-yellow-500"
                            )}>
                              {p.status}
                            </span>
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
                            No pending client payments found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="text-sm">
                  <span className="text-muted-foreground">Total Pending: </span>
                  <span className="font-bold text-lg text-primary">{formatCurrencyFull(stats.pendingClientPayment)}</span>
                </div>
                <button 
                  onClick={() => setIsPendingClientPaymentModalOpen(false)}
                  className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                >
                  Close
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Pending Engineer Payment Database Modal */}
      <AnimatePresence>
        {isPendingEngineerPaymentModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <Clock size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Pending Engineer Payments</h2>
                    <p className="text-xs text-muted-foreground">Detailed list of all unpaid engineer invoices</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadPendingEngineerPayment}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsPendingEngineerPaymentModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Project</th>
                        <th className="px-4 py-3">Engineer</th>
                        <th className="px-4 py-3 text-right">Amount</th>
                        <th className="px-4 py-3">Due Date</th>
                        <th className="px-4 py-3">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {pendingEngineerPaymentDetails.length > 0 ? pendingEngineerPaymentDetails.map((p) => (
                        <tr key={p.id} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <FileText size={14} className="text-primary" />
                              <span className="font-medium">{p.name}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-muted-foreground">{p.engineer}</td>
                          <td className="px-4 py-4 text-right font-bold text-primary">
                            {formatCurrencyFull(p.amount)}
                          </td>
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                              <Calendar size={12} />
                              {formatDate(p.date)}
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <span className={cn(
                              "px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-yellow-500/10 text-yellow-500"
                            )}>
                              {p.status}
                            </span>
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
                            No pending engineer payments found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="text-sm">
                  <span className="text-muted-foreground">Total Pending: </span>
                  <span className="font-bold text-lg text-primary">{formatCurrencyFull(stats.pendingEngineerPayment)}</span>
                </div>
                <button 
                  onClick={() => setIsPendingEngineerPaymentModalOpen(false)}
                  className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                >
                  Close
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Completed Projects Database Modal */}
      <AnimatePresence>
        {isCompletedProjectsModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <CheckSquare size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Completed Projects</h2>
                    <p className="text-xs text-muted-foreground">Historical record of all successfully delivered projects</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadCompletedProjects}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsCompletedProjectsModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Project</th>
                        <th className="px-4 py-3">Client</th>
                        <th className="px-4 py-3">Engineer</th>
                        <th className="px-4 py-3">Completion Date</th>
                        <th className="px-4 py-3 text-right">Revenue</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {completedProjectsDetails.length > 0 ? completedProjectsDetails.map((p) => (
                        <tr key={p.id} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <FileText size={14} className="text-primary" />
                              <span className="font-medium">{p.name}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-muted-foreground">{p.client}</td>
                          <td className="px-4 py-4 text-muted-foreground">{p.engineer}</td>
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                              <Calendar size={12} />
                              {formatDate(p.date)}
                            </div>
                          </td>
                          <td className="px-4 py-4 text-right font-bold text-primary">
                            {formatCurrencyFull(p.revenue)}
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
                            No completed projects found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="text-sm">
                  <span className="text-muted-foreground">Total Completed: </span>
                  <span className="font-bold text-lg text-primary">{stats.completedProjects} Projects</span>
                </div>
                <button 
                  onClick={() => setIsCompletedProjectsModalOpen(false)}
                  className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                >
                  Close
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Pending Projects Database Modal */}
      <AnimatePresence>
        {isPendingProjectsModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <Briefcase size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Pending Projects</h2>
                    <p className="text-xs text-muted-foreground">Overview of all active and upcoming projects</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadPendingProjects}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsPendingProjectsModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Project</th>
                        <th className="px-4 py-3">Client</th>
                        <th className="px-4 py-3">Engineer</th>
                        <th className="px-4 py-3">Deadline</th>
                        <th className="px-4 py-3">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {pendingProjectsDetails.length > 0 ? pendingProjectsDetails.map((p) => (
                        <tr key={p.id} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <FileText size={14} className="text-primary" />
                              <span className="font-medium">{p.name}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-muted-foreground">{p.client}</td>
                          <td className="px-4 py-4 text-muted-foreground">{p.engineer}</td>
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                              <Calendar size={12} />
                              {formatDate(p.date)}
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <span className={cn(
                              "px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",
                              p.status === 'In Progress' ? "bg-blue-500/10 text-blue-500" : "bg-yellow-500/10 text-yellow-500"
                            )}>
                              {p.status}
                            </span>
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
                            No pending projects found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="text-sm">
                  <span className="text-muted-foreground">Total Pending: </span>
                  <span className="font-bold text-lg text-primary">{stats.pendingProjects} Projects</span>
                </div>
                <button 
                  onClick={() => setIsPendingProjectsModalOpen(false)}
                  className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                >
                  Close
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Total Employees Database Modal */}
      <AnimatePresence>
        {isEmployeesModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <Users size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Employees Directory</h2>
                    <p className="text-xs text-muted-foreground">List of all active contributors across projects and tasks</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadEmployees}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsEmployeesModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Employee Name</th>
                        <th className="px-4 py-3 text-center">Active Projects</th>
                        <th className="px-4 py-3 text-center">Active Tasks</th>
                        <th className="px-4 py-3 text-right">Total Involvement</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {employeesDetails.length > 0 ? employeesDetails.map((e, idx) => (
                        <tr key={idx} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center text-primary text-xs font-bold">
                                {e.name.charAt(0)}
                              </div>
                              <span className="font-medium">{e.name}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-center text-muted-foreground">{e.projects}</td>
                          <td className="px-4 py-4 text-center text-muted-foreground">{e.tasks}</td>
                          <td className="px-4 py-4 text-right font-bold text-primary">
                            {e.total}
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={4} className="px-4 py-8 text-center text-muted-foreground">
                            No employee data found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="text-sm">
                  <span className="text-muted-foreground">Total Active Employees: </span>
                  <span className="font-bold text-lg text-primary">{stats.totalEmployees}</span>
                </div>
                <button 
                  onClick={() => setIsEmployeesModalOpen(false)}
                  className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                >
                  Close
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Total Engineers Database Modal */}
      <AnimatePresence>
        {isEngineersModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden"
            >
              <div className="p-6 border-b border-border flex items-center justify-between bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                    <Users size={20} />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold">Engineers Directory</h2>
                    <p className="text-xs text-muted-foreground">List of all registered engineers and their current workload</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={handleDownloadEngineers}
                    className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-all hover:scale-105 active:scale-95 cursor-pointer text-sm font-medium shadow-sm hover:shadow"
                  >
                    <Download size={16} />
                    Download CSV
                  </button>
                  <button 
                    onClick={() => setIsEngineersModalOpen(false)}
                    className="p-2 hover:bg-accent rounded-full transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <div className="rounded-xl border border-border overflow-hidden">
                  <table className="w-full text-left text-sm">
                    <thead className="bg-muted/50 text-muted-foreground font-medium">
                      <tr>
                        <th className="px-4 py-3">Engineer Name</th>
                        <th className="px-4 py-3">Specialization</th>
                        <th className="px-4 py-3">Email</th>
                        <th className="px-4 py-3 text-right">Active Projects</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {engineersDetails.length > 0 ? engineersDetails.map((e) => (
                        <tr key={e.id} className="hover:bg-accent/5 transition-colors">
                          <td className="px-4 py-4">
                            <div className="flex items-center gap-2">
                              <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center text-primary text-xs font-bold">
                                {e.name.charAt(0)}
                              </div>
                              <span className="font-medium">{e.name}</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 text-muted-foreground">{e.specialization}</td>
                          <td className="px-4 py-4 text-muted-foreground">{e.email}</td>
                          <td className="px-4 py-4 text-right font-bold text-primary">
                            {e.activeProjects}
                          </td>
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={4} className="px-4 py-8 text-center text-muted-foreground">
                            No engineer data found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="text-sm">
                  <span className="text-muted-foreground">Total Registered Engineers: </span>
                  <span className="font-bold text-lg text-primary">{stats.totalEngineers}</span>
                </div>
                <button 
                  onClick={() => setIsEngineersModalOpen(false)}
                  className="px-6 py-2 rounded-lg bg-accent hover:bg-accent/80 transition-colors text-sm font-medium"
                >
                  Close
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
}

function KPICard({ title, value, change, trend, icon: Icon, onClick, actions }: any) {
  return (
    <div 
      onClick={onClick}
      className="rounded-xl border border-border bg-card p-6 shadow-sm transition-all hover:shadow-md cursor-pointer group relative overflow-hidden"
    >
      <div className="flex items-center justify-between">
        <div className="rounded-lg bg-primary/10 p-2 text-primary group-hover:bg-primary group-hover:text-primary-foreground transition-colors">
          <Icon size={20} />
        </div>
        <div className={cn(
          "flex items-center gap-0.5 text-xs font-medium",
          trend === 'up' ? "text-green-500" : "text-red-500"
        )}>
          {trend === 'up' ? <ArrowUpRight size={14} /> : <ArrowDownRight size={14} />}
          {change}
        </div>
      </div>
      <div className="mt-4">
        <p className="text-sm font-medium text-muted-foreground">{title}</p>
        <h4 className="text-2xl font-bold">{value}</h4>
      </div>

      {actions && (
        <div className="mt-4 pt-4 border-t border-border flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
          {actions.map((action: any, idx: number) => (
            <button
              key={idx}
              onClick={action.onClick}
              className="flex items-center gap-1.5 px-2 py-1 rounded-md bg-accent hover:bg-accent/80 text-[10px] font-bold uppercase tracking-wider transition-all hover:scale-105 active:scale-95 cursor-pointer shadow-sm hover:shadow"
            >
              <action.icon size={12} />
              {action.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
