import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  TrendingUp, 
  Users, 
  Briefcase, 
  CheckSquare, 
  DollarSign, 
  Receipt, 
  BarChart3,
  Plus,
  ArrowRight,
  CheckCircle2,
  Clock,
  AlertCircle,
  MoreHorizontal,
  Search,
  Filter,
  UserPlus,
  Wrench,
  ChevronRight,
  Target,
  Calendar,
  X,
  Download,
  FileText,
  CreditCard,
  ArrowUpRight,
  ArrowDownRight,
  Edit,
  Trash2
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp, Project, Client, Engineer, Task, Expense } from '@/context/AppContext';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell
} from 'recharts';

type OperationStep = 'leads' | 'clients' | 'projects' | 'execution' | 'finance';

export function Operations() {
  const navigate = useNavigate();
  const { 
    projects, 
    clients, 
    engineers, 
    tasks, 
    expenses,
    addProject,
    updateProject,
    addClient,
    updateClient,
    addTask,
    updateTask,
    addExpense,
    deleteProject,
    deleteClient,
    deleteTask,
    deleteExpense,
    currencies
  } = useApp();

  const [activeStep, setActiveStep] = useState<OperationStep>('leads');
  const [searchQuery, setSearchQuery] = useState('');
  const [isLeadModalOpen, setIsLeadModalOpen] = useState(false);
  const [isClientModalOpen, setIsClientModalOpen] = useState(false);
  const [isProjectModalOpen, setIsProjectModalOpen] = useState(false);
  const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);
  const [isExpenseModalOpen, setIsExpenseModalOpen] = useState(false);
  const [isInvoiceModalOpen, setIsInvoiceModalOpen] = useState(false);
  const [isReportModalOpen, setIsReportModalOpen] = useState(false);
  const [isClientDetailsModalOpen, setIsClientDetailsModalOpen] = useState(false);
  const [isEditClientModalOpen, setIsEditClientModalOpen] = useState(false);
  const [isDeleteClientModalOpen, setIsDeleteClientModalOpen] = useState(false);
  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [clientToDelete, setClientToDelete] = useState<Client | null>(null);
  const [leadFormData, setLeadFormData] = useState({
    name: '',
    client: '',
    value: '',
    currency: 'USD',
    deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    status: 'Planning',
    assignedTo: 'Unassigned'
  });
  const [clientFormData, setClientFormData] = useState({
    name: '',
    industry: '',
    contactPerson: '',
    email: '',
    phone: '',
    website: ''
  });
  const [projectFormData, setProjectFormData] = useState({
    name: '',
    client: '',
    budget: '',
    deadline: new Date(Date.now() + 60 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
  });
  const [taskFormData, setTaskFormData] = useState({
    title: '',
    projectId: '',
    assignee: '',
    dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
  });
  const [expenseFormData, setExpenseFormData] = useState({
    description: '',
    category: 'Operations',
    amount: '',
    date: new Date().toISOString().split('T')[0],
    status: 'Pending',
    paymentMethod: 'Corporate Card'
  });
  const [invoiceFormData, setInvoiceFormData] = useState({
    projectId: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Stats for the top bar
  const stats = useMemo(() => {
    const totalLeads = projects.filter(p => p.status === 'Planning' || p.status === 'Pending').length;
    const activeProjects = projects.filter(p => p.status === 'Active' || p.status === 'In Progress' || p.status === 'Work In Progress').length;
    const totalRevenue = projects.reduce((acc, p) => acc + (p.clientTotalAmount || 0), 0);
    const totalExpenses = expenses.filter(e => e.status === 'Approved').reduce((acc, e) => acc + e.amount, 0);
    const profit = totalRevenue - totalExpenses;
    
    return { totalLeads, activeProjects, totalRevenue, totalExpenses, profit };
  }, [projects, expenses]);

  const downloadFullReport = () => {
    try {
      const headers = ['Category', 'ID', 'Name/Title', 'Client/Project', 'Status', 'Amount/Value', 'Date/Deadline'];
      const rows: string[][] = [];

      // Summary
      rows.push(['SUMMARY', '', 'Total Revenue', '', '', `$${stats.totalRevenue}`, '']);
      rows.push(['SUMMARY', '', 'Total Expenses', '', '', `$${stats.totalExpenses}`, '']);
      rows.push(['SUMMARY', '', 'Net Profit', '', '', `$${stats.profit}`, '']);
      rows.push(['', '', '', '', '', '', '']);

      // Projects
      projects.forEach(p => {
        rows.push(['PROJECT', p.id, p.name, p.client, p.status, `$${p.clientTotalAmount || 0}`, p.deadline]);
      });
      rows.push(['', '', '', '', '', '', '']);

      // Clients
      clients.forEach(c => {
        rows.push(['CLIENT', c.id, c.name, '', c.status, `$${c.revenue}`, '']);
      });
      rows.push(['', '', '', '', '', '', '']);

      // Tasks
      tasks.forEach(t => {
        rows.push(['TASK', t.id, t.title, t.project, t.status, '', t.dueDate]);
      });
      rows.push(['', '', '', '', '', '', '']);

      // Expenses
      expenses.forEach(e => {
        rows.push(['EXPENSE', e.id, e.description, e.category, e.status, `$${e.amount}`, e.date]);
      });

      const csvContent = [
        headers.join(','),
        ...rows.map(row => row.map(cell => `"${cell}"`).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', `operations_full_report_${new Date().toISOString().split('T')[0]}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      toast.success('Report downloaded successfully');
    } catch (error) {
      toast.error('Failed to generate report');
      console.error(error);
    }
  };

  const workflowSteps = useMemo(() => [
    { id: 'leads', label: 'Lead', icon: Target, value: projects.filter(p => p.status === 'Planning' || p.status === 'Pending').length, color: 'text-blue-500', bg: 'bg-blue-500/10' },
    { id: 'clients', label: 'Client', icon: Users, value: clients.length, color: 'text-purple-500', bg: 'bg-purple-500/10' },
    { id: 'projects', label: 'Project', icon: Briefcase, value: projects.filter(p => p.status === 'Active' || p.status === 'In Progress' || p.status === 'Work In Progress').length, color: 'text-orange-500', bg: 'bg-orange-500/10' },
    { id: 'tasks', label: 'Tasks', icon: CheckSquare, value: tasks.length, color: 'text-green-500', bg: 'bg-green-500/10' },
    { id: 'timesheets', label: 'Timesheets', icon: Clock, value: tasks.filter(t => t.status === 'Completed').length, color: 'text-cyan-500', bg: 'bg-cyan-500/10' },
    { id: 'invoices', label: 'Invoice (+Tax)', icon: FileText, value: projects.filter(p => p.clientInvoiceStatus).length, color: 'text-yellow-500', bg: 'bg-yellow-500/10' },
    { id: 'payments', label: 'Payment', icon: CreditCard, value: projects.filter(p => p.clientInvoiceStatus === 'Paid').length, color: 'text-emerald-500', bg: 'bg-emerald-500/10' },
    { id: 'expenses', label: 'Expenses', icon: Receipt, value: expenses.filter(e => e.status === 'Approved').length, color: 'text-red-500', bg: 'bg-red-500/10' },
    { id: 'profit', label: 'Profit', icon: TrendingUp, value: `$${stats.profit.toLocaleString()}`, color: 'text-indigo-500', bg: 'bg-indigo-500/10' },
  ], [projects, clients, tasks, expenses, stats.profit]);

  const steps = [
    { id: 'leads', label: 'Sales & Leads', icon: Target, color: 'text-blue-500', bg: 'bg-blue-500/10' },
    { id: 'clients', label: 'Clients', icon: Users, color: 'text-purple-500', bg: 'bg-purple-500/10' },
    { id: 'projects', label: 'Projects', icon: Briefcase, color: 'text-orange-500', bg: 'bg-orange-500/10' },
    { id: 'execution', label: 'Execution', icon: CheckSquare, color: 'text-green-500', bg: 'bg-green-500/10' },
    { id: 'finance', label: 'Finance', icon: DollarSign, color: 'text-emerald-500', bg: 'bg-emerald-500/10' },
  ];

  return (
    <div className="space-y-6 pb-12">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Operations Control Center</h1>
          <p className="text-muted-foreground">Manage the entire business lifecycle from lead to profit.</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex flex-col items-end">
            <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Total Profit</span>
            <span className={cn(
              "text-xl font-bold",
              stats.profit >= 0 ? "text-green-500" : "text-red-500"
            )}>
              ${stats.profit.toLocaleString()}
            </span>
          </div>
          <div className="h-10 w-px bg-border mx-2" />
          <button 
            onClick={() => setIsReportModalOpen(true)}
            className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors shadow-sm"
          >
            <BarChart3 size={18} />
            Full Report
          </button>
        </div>
      </div>

      {/* Business Workflow Visualization */}
      <div className="rounded-2xl border border-border bg-card p-6 shadow-sm overflow-hidden">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-lg font-bold flex items-center gap-2">
            <TrendingUp className="text-primary" size={20} />
            Business Lifecycle Workflow
          </h2>
          <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground bg-muted px-2 py-0.5 rounded">Real-time Pipeline</span>
        </div>
        
        <div className="relative">
          {/* Connecting Line */}
          <div className="absolute top-1/2 left-0 right-0 h-0.5 bg-muted -translate-y-1/2 hidden lg:block" />
          
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-9 gap-4 relative z-10">
            {workflowSteps.map((step, index) => {
              const Icon = step.icon;
              return (
                <motion.div 
                  key={step.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.05 }}
                  className="flex flex-col items-center group"
                >
                  <div className={cn(
                    "w-12 h-12 rounded-full flex items-center justify-center mb-3 transition-all duration-300 group-hover:scale-110 shadow-sm",
                    step.bg,
                    step.color
                  )}>
                    <Icon size={20} />
                  </div>
                  <div className="text-center">
                    <p className="text-[10px] font-bold uppercase tracking-tighter text-muted-foreground mb-0.5">{step.label}</p>
                    <p className="text-sm font-bold">{step.value}</p>
                  </div>
                  {index < workflowSteps.length - 1 && (
                    <div className="lg:hidden flex justify-center my-2 text-muted-foreground/30">
                      <ChevronRight size={16} className="rotate-90" />
                    </div>
                  )}
                </motion.div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Workflow Stepper */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-2 p-1 bg-muted/30 rounded-xl border border-border">
        {steps.map((step) => {
          const Icon = step.icon;
          const isActive = activeStep === step.id;
          return (
            <button
              key={step.id}
              onClick={() => setActiveStep(step.id as OperationStep)}
              className={cn(
                "flex flex-col items-center gap-1 py-3 px-2 rounded-lg transition-all relative overflow-hidden",
                isActive ? "bg-card shadow-sm text-primary" : "text-muted-foreground hover:bg-muted/50"
              )}
            >
              <div className={cn(
                "p-2 rounded-lg mb-1",
                isActive ? step.bg : "bg-transparent"
              )}>
                <Icon size={20} className={isActive ? step.color : "text-muted-foreground"} />
              </div>
              <span className="text-xs font-bold uppercase tracking-tighter">{step.label}</span>
              {isActive && (
                <motion.div 
                  layoutId="activeStep"
                  className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary"
                />
              )}
            </button>
          );
        })}
      </div>

      {/* Main Content Area */}
      <div className="min-h-[600px]">
        <AnimatePresence mode="wait">
          <motion.div
            key={activeStep}
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.2 }}
          >
            {activeStep === 'leads' && (
              <LeadsSection 
                onAddLead={() => setIsLeadModalOpen(true)} 
              />
            )}
            {activeStep === 'clients' && (
              <ClientsSection 
                onAddClient={() => setIsClientModalOpen(true)} 
                onViewDetails={(client) => {
                  setSelectedClient(client);
                  setIsClientDetailsModalOpen(true);
                }}
                onEditClient={(client) => {
                  setSelectedClient(client);
                  setClientFormData({
                    name: client.name,
                    industry: client.industry,
                    contactPerson: client.contactPerson,
                    email: client.email,
                    phone: client.phone,
                    website: client.website || ''
                  });
                  setIsEditClientModalOpen(true);
                }}
                onDeleteClient={(client) => {
                  setClientToDelete(client);
                  setIsDeleteClientModalOpen(true);
                }}
              />
            )}
            {activeStep === 'projects' && <ProjectsSection onAddProject={() => setIsProjectModalOpen(true)} />}
            {activeStep === 'execution' && <ExecutionSection onAddTask={() => setIsTaskModalOpen(true)} />}
            {activeStep === 'finance' && (
              <FinanceSection 
                onAddExpense={() => setIsExpenseModalOpen(true)} 
                onGenerateInvoice={() => setIsInvoiceModalOpen(true)} 
              />
            )}
          </motion.div>
        </AnimatePresence>
      </div>

      {/* Lead Modal */}
      {isLeadModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">Add New Lead</h2>
              <button onClick={() => setIsLeadModalOpen(false)} className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={async (e) => {
              e.preventDefault();
              if (isSubmitting) return;
              setIsSubmitting(true);
              try {
                const newLead: Project = {
                  id: `LEAD-${Math.random().toString(36).substr(2, 5).toUpperCase()}`,
                  name: leadFormData.name,
                  client: leadFormData.client,
                  status: leadFormData.status as any,
                  team: 0,
                  deadline: leadFormData.deadline,
                  currency: leadFormData.currency,
                  clientTotalAmount: parseFloat(leadFormData.value) || 0,
                  assignedTo: leadFormData.assignedTo
                };
                await addProject(newLead);
                toast.success('Lead added to pipeline');
                setIsLeadModalOpen(false);
                setLeadFormData({
                  name: '',
                  client: '',
                  value: '',
                  currency: 'USD',
                  deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
                  status: 'Planning',
                  assignedTo: 'Unassigned'
                });
              } catch (error) {
                toast.error('Failed to add lead');
              } finally {
                setIsSubmitting(false);
              }
            }} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Deal Name</label>
                <input
                  required
                  type="text"
                  value={leadFormData.name || ''}
                  onChange={(e) => setLeadFormData({ ...leadFormData, name: e.target.value })}
                  placeholder="e.g. Website Redesign"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Company</label>
                <input
                  required
                  type="text"
                  value={leadFormData.client || ''}
                  onChange={(e) => setLeadFormData({ ...leadFormData, client: e.target.value })}
                  placeholder="e.g. Acme Corp"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Deal Value</label>
                  <div className="flex gap-2">
                    <select
                      value={leadFormData.currency || 'USD'}
                      onChange={(e) => setLeadFormData({ ...leadFormData, currency: e.target.value })}
                      className="w-20 rounded-lg border border-border bg-background px-2 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    >
                      {currencies.map(curr => (
                        <option key={curr.code} value={curr.code}>{curr.code}</option>
                      ))}
                    </select>
                    <input
                      required
                      type="number"
                      value={leadFormData.value || ''}
                      onChange={(e) => setLeadFormData({ ...leadFormData, value: e.target.value })}
                      placeholder="5000"
                      className="flex-1 rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Stage</label>
                  <select
                    value={leadFormData.status}
                    onChange={(e) => setLeadFormData({ ...leadFormData, status: e.target.value })}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                  >
                    <option value="Planning">Lead</option>
                    <option value="Pending">Qualified</option>
                    <option value="In Progress">Proposal</option>
                    <option value="Active">Negotiation</option>
                  </select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Expected Close</label>
                  <input
                    required
                    type="date"
                    value={leadFormData.deadline || ''}
                    onChange={(e) => setLeadFormData({ ...leadFormData, deadline: e.target.value })}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Owner</label>
                  <input
                    type="text"
                    value={leadFormData.assignedTo || ''}
                    onChange={(e) => setLeadFormData({ ...leadFormData, assignedTo: e.target.value })}
                    placeholder="Owner name"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </div>
              <div className="flex justify-end gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setIsLeadModalOpen(false)}
                  className="rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center gap-2"
                >
                  {isSubmitting && <div className="h-3 w-3 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />}
                  Save Lead
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Client Modal */}
      {isClientModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">Add New Client</h2>
              <button onClick={() => setIsClientModalOpen(false)} className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={async (e) => {
              e.preventDefault();
              if (isSubmitting) return;
              setIsSubmitting(true);
              try {
                const newClient: Client = {
                  id: `CL-${Math.random().toString(36).substr(2, 5).toUpperCase()}`,
                  name: clientFormData.name,
                  industry: clientFormData.industry || 'Technology',
                  contactPerson: clientFormData.contactPerson,
                  email: clientFormData.email,
                  phone: clientFormData.phone,
                  status: 'Active',
                  projects: 0,
                  revenue: 0,
                  website: clientFormData.website
                };
                await addClient(newClient);
                toast.success('Client added successfully');
                setIsClientModalOpen(false);
                setClientFormData({
                  name: '',
                  industry: '',
                  contactPerson: '',
                  email: '',
                  phone: '',
                  website: ''
                });
              } catch (error) {
                toast.error('Failed to add client');
              } finally {
                setIsSubmitting(false);
              }
            }} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Company Name</label>
                <input
                  required
                  type="text"
                  value={clientFormData.name || ''}
                  onChange={(e) => setClientFormData({ ...clientFormData, name: e.target.value })}
                  placeholder="e.g. Acme Corp"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Industry</label>
                  <input
                    type="text"
                    value={clientFormData.industry || ''}
                    onChange={(e) => setClientFormData({ ...clientFormData, industry: e.target.value })}
                    placeholder="e.g. Software"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Contact Person</label>
                  <input
                    required
                    type="text"
                    value={clientFormData.contactPerson || ''}
                    onChange={(e) => setClientFormData({ ...clientFormData, contactPerson: e.target.value })}
                    placeholder="e.g. Jane Smith"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Email</label>
                  <input
                    required
                    type="email"
                    value={clientFormData.email || ''}
                    onChange={(e) => setClientFormData({ ...clientFormData, email: e.target.value })}
                    placeholder="jane@acme.com"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Phone</label>
                  <input
                    type="text"
                    value={clientFormData.phone || ''}
                    onChange={(e) => setClientFormData({ ...clientFormData, phone: e.target.value })}
                    placeholder="+1 (555) 000-0000"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Website</label>
                <input
                  type="url"
                  value={clientFormData.website || ''}
                  onChange={(e) => setClientFormData({ ...clientFormData, website: e.target.value })}
                  placeholder="https://acme.com"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="flex justify-end gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setIsClientModalOpen(false)}
                  className="rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center gap-2"
                >
                  {isSubmitting && <div className="h-3 w-3 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />}
                  Save Client
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Project Modal */}
      {isProjectModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">Create New Project</h2>
              <button onClick={() => setIsProjectModalOpen(false)} className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={async (e) => {
              e.preventDefault();
              if (isSubmitting) return;
              setIsSubmitting(true);
              try {
                const newProject: Project = {
                  id: `PRJ-${Math.random().toString(36).substr(2, 5).toUpperCase()}`,
                  name: projectFormData.name,
                  client: projectFormData.client,
                  status: 'Active',
                  team: 0,
                  deadline: projectFormData.deadline,
                  clientTotalAmount: parseFloat(projectFormData.budget) || 0,
                  issueDate: new Date().toISOString().split('T')[0],
                  issuedMonth: new Date().toISOString().substring(0, 7)
                };
                await addProject(newProject);
                toast.success('Project created successfully');
                setIsProjectModalOpen(false);
                setProjectFormData({
                  name: '',
                  client: '',
                  budget: '',
                  deadline: new Date(Date.now() + 60 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
                });
              } catch (error) {
                toast.error('Failed to create project');
              } finally {
                setIsSubmitting(false);
              }
            }} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Project Name</label>
                <input
                  required
                  type="text"
                  value={projectFormData.name || ''}
                  onChange={(e) => setProjectFormData({ ...projectFormData, name: e.target.value })}
                  placeholder="e.g. Website Redesign"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Client</label>
                <select
                  required
                  value={projectFormData.client || ''}
                  onChange={(e) => setProjectFormData({ ...projectFormData, client: e.target.value })}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                >
                  <option value="">Select a client</option>
                  {clients.map(c => (
                    <option key={c.id} value={c.name}>{c.name}</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Budget ($)</label>
                  <input
                    required
                    type="number"
                    value={projectFormData.budget || ''}
                    onChange={(e) => setProjectFormData({ ...projectFormData, budget: e.target.value })}
                    placeholder="5000"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Deadline</label>
                  <input
                    required
                    type="date"
                    value={projectFormData.deadline || ''}
                    onChange={(e) => setProjectFormData({ ...projectFormData, deadline: e.target.value })}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </div>
              <div className="flex justify-end gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setIsProjectModalOpen(false)}
                  className="rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center gap-2"
                >
                   {isSubmitting && <div className="h-3 w-3 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />}
                  Create Project
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Task Modal */}
      {isTaskModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">Add New Task</h2>
              <button onClick={() => setIsTaskModalOpen(false)} className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={async (e) => {
              e.preventDefault();
              if (isSubmitting) return;
              setIsSubmitting(true);
              try {
                const project = projects.find(p => p.id === taskFormData.projectId);
                const newTask: Task = {
                  id: `TSK-${Math.random().toString(36).substr(2, 5).toUpperCase()}`,
                  title: taskFormData.title,
                  project: project?.name || 'Unknown Project',
                  projectId: taskFormData.projectId,
                  assignDate: new Date().toISOString().split('T')[0],
                  status: 'To Do',
                  dueDate: taskFormData.dueDate,
                  assignee: taskFormData.assignee
                };
                await addTask(newTask);
                toast.success('Task added successfully');
                setIsTaskModalOpen(false);
                setTaskFormData({
                  title: '',
                  projectId: '',
                  assignee: '',
                  dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
                });
              } catch (error) {
                toast.error('Failed to add task');
              } finally {
                setIsSubmitting(false);
              }
            }} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Task Title</label>
                <input
                  required
                  type="text"
                  value={taskFormData.title || ''}
                  onChange={(e) => setTaskFormData({ ...taskFormData, title: e.target.value })}
                  placeholder="e.g. Design Homepage"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Project</label>
                <select
                  required
                  value={taskFormData.projectId || ''}
                  onChange={(e) => setTaskFormData({ ...taskFormData, projectId: e.target.value })}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                >
                  <option value="">Select a project</option>
                  {projects.filter(p => p.status === 'Active' || p.status === 'In Progress').map(p => (
                    <option key={p.id} value={p.id}>{p.name}</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Assignee</label>
                  <select
                    required
                    value={taskFormData.assignee || ''}
                    onChange={(e) => setTaskFormData({ ...taskFormData, assignee: e.target.value })}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="">Select engineer</option>
                    {engineers.map(eng => (
                      <option key={eng.id} value={eng.name}>{eng.name}</option>
                    ))}
                  </select>
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Due Date</label>
                  <input
                    required
                    type="date"
                    value={taskFormData.dueDate || ''}
                    onChange={(e) => setTaskFormData({ ...taskFormData, dueDate: e.target.value })}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </div>
              <div className="flex justify-end gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setIsTaskModalOpen(false)}
                  className="rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center gap-2"
                >
                  {isSubmitting && <div className="h-3 w-3 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />}
                  Save Task
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Expense Modal */}
      {isExpenseModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">Record New Expense</h2>
              <button onClick={() => setIsExpenseModalOpen(false)} className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={async (e) => {
              e.preventDefault();
              if (isSubmitting) return;
              setIsSubmitting(true);
              try {
                const expense: Expense = {
                  id: `EXP-${Math.floor(Math.random() * 10000).toString().padStart(3, '0')}`,
                  description: expenseFormData.description,
                  category: expenseFormData.category,
                  amount: parseFloat(expenseFormData.amount) || 0,
                  date: expenseFormData.date,
                  status: expenseFormData.status as any,
                  paymentMethod: expenseFormData.paymentMethod
                };
                await addExpense(expense);
                toast.success('Expense recorded successfully');
                setIsExpenseModalOpen(false);
                setExpenseFormData({
                  description: '',
                  category: 'Operations',
                  amount: '',
                  date: new Date().toISOString().split('T')[0],
                  status: 'Pending',
                  paymentMethod: 'Corporate Card'
                });
              } catch (error) {
                toast.error('Failed to record expense');
              } finally {
                setIsSubmitting(false);
              }
            }} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Description</label>
                <input
                  required
                  type="text"
                  value={expenseFormData.description}
                  onChange={(e) => setExpenseFormData({ ...expenseFormData, description: e.target.value })}
                  placeholder="e.g. Office Supplies"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Category</label>
                  <select
                    value={expenseFormData.category}
                    onChange={(e) => setExpenseFormData({ ...expenseFormData, category: e.target.value })}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="Operations">Operations</option>
                    <option value="Technology">Technology</option>
                    <option value="Travel">Travel</option>
                    <option value="Marketing">Marketing</option>
                    <option value="Engineer bills">Engineer bills</option>
                  </select>
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Amount ($)</label>
                  <input
                    required
                    type="number"
                    step="0.01"
                    value={expenseFormData.amount}
                    onChange={(e) => setExpenseFormData({ ...expenseFormData, amount: e.target.value })}
                    placeholder="0.00"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Date</label>
                  <input
                    type="date"
                    value={expenseFormData.date}
                    onChange={(e) => setExpenseFormData({ ...expenseFormData, date: e.target.value })}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Payment Method</label>
                  <select
                    value={expenseFormData.paymentMethod}
                    onChange={(e) => setExpenseFormData({ ...expenseFormData, paymentMethod: e.target.value })}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="Corporate Card">Corporate Card</option>
                    <option value="Bank Transfer">Bank Transfer</option>
                    <option value="Cash">Cash</option>
                  </select>
                </div>
              </div>
              <div className="flex justify-end gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setIsExpenseModalOpen(false)}
                  className="rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center gap-2"
                >
                  {isSubmitting && <div className="h-3 w-3 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />}
                  Save Expense
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Invoice Modal */}
      {isInvoiceModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">Generate Invoice</h2>
              <button onClick={() => setIsInvoiceModalOpen(false)} className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={async (e) => {
              e.preventDefault();
              try {
                const project = projects.find(p => p.id === invoiceFormData.projectId);
                if (project) {
                  await updateProject(project.id, { 
                    clientInvoiceStatus: 'Unpaid',
                    issueDate: new Date().toISOString().split('T')[0]
                  });
                  toast.success(`Invoice generated for ${project.client}`);
                  setIsInvoiceModalOpen(false);
                  setInvoiceFormData({ projectId: '' });
                }
              } catch (error) {
                toast.error('Failed to generate invoice');
              }
            }} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Select Project to Invoice</label>
                <select
                  required
                  value={invoiceFormData.projectId}
                  onChange={(e) => setInvoiceFormData({ ...invoiceFormData, projectId: e.target.value })}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                >
                  <option value="">Select a project</option>
                  {projects.filter(p => !p.clientInvoiceStatus && (p.status === 'Active' || p.status === 'Completed')).map(p => (
                    <option key={p.id} value={p.id}>{p.client} - {p.name}</option>
                  ))}
                </select>
              </div>
              <div className="p-4 rounded-lg bg-muted/30 border border-border">
                <p className="text-xs text-muted-foreground">
                  Generating an invoice will mark the project as "Unpaid" and set today's date as the issue date.
                </p>
              </div>
              <div className="flex justify-end gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setIsInvoiceModalOpen(false)}
                  className="rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
                >
                  Generate Invoice
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Edit Client Modal */}
      {isEditClientModalOpen && selectedClient && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">Edit Client</h2>
              <button onClick={() => setIsEditClientModalOpen(false)} className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={async (e) => {
              e.preventDefault();
              try {
                await updateClient(selectedClient.id, clientFormData);
                toast.success('Client updated successfully');
                setIsEditClientModalOpen(false);
              } catch (error) {
                toast.error('Failed to update client');
              }
            }} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Company Name</label>
                <input
                  required
                  type="text"
                  value={clientFormData.name || ''}
                  onChange={(e) => setClientFormData({ ...clientFormData, name: e.target.value })}
                  placeholder="e.g. Acme Corp"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Industry</label>
                  <input
                    type="text"
                    value={clientFormData.industry || ''}
                    onChange={(e) => setClientFormData({ ...clientFormData, industry: e.target.value })}
                    placeholder="e.g. Software"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Contact Person</label>
                  <input
                    required
                    type="text"
                    value={clientFormData.contactPerson || ''}
                    onChange={(e) => setClientFormData({ ...clientFormData, contactPerson: e.target.value })}
                    placeholder="e.g. Jane Smith"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Email</label>
                  <input
                    required
                    type="email"
                    value={clientFormData.email || ''}
                    onChange={(e) => setClientFormData({ ...clientFormData, email: e.target.value })}
                    placeholder="jane@acme.com"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Phone</label>
                  <input
                    type="text"
                    value={clientFormData.phone || ''}
                    onChange={(e) => setClientFormData({ ...clientFormData, phone: e.target.value })}
                    placeholder="+1 (555) 000-0000"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Website</label>
                <input
                  type="url"
                  value={clientFormData.website || ''}
                  onChange={(e) => setClientFormData({ ...clientFormData, website: e.target.value })}
                  placeholder="https://acme.com"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="flex justify-end gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setIsEditClientModalOpen(false)}
                  className="rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
                >
                  Update Client
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Client Modal */}
      {isDeleteClientModalOpen && clientToDelete && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="flex items-center gap-3 text-red-500 mb-4">
              <AlertCircle size={24} />
              <h2 className="text-xl font-bold">Delete Client</h2>
            </div>
            <p className="text-muted-foreground mb-6">
              Are you sure you want to delete <span className="font-bold text-foreground">{clientToDelete.name}</span>? This action cannot be undone and will remove all associated data.
            </p>
            <div className="flex justify-end gap-3">
              <button
                onClick={() => setIsDeleteClientModalOpen(false)}
                className="rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={async () => {
                  try {
                    await deleteClient(clientToDelete.id);
                    toast.success('Client deleted successfully');
                    setIsDeleteClientModalOpen(false);
                  } catch (error) {
                    toast.error('Failed to delete client');
                  }
                }}
                className="rounded-lg bg-red-500 px-4 py-2 text-sm font-medium text-white hover:bg-red-600 transition-colors"
              >
                Delete Client
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Client Details Modal */}
      <AnimatePresence>
        {isClientDetailsModalOpen && selectedClient && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="w-full max-w-2xl rounded-2xl border border-border bg-card shadow-2xl overflow-hidden flex flex-col"
            >
              <div className="flex items-center justify-between p-6 border-b border-border bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-lg bg-purple-500/10 text-purple-500">
                    <Users size={24} />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold tracking-tight">{selectedClient.name}</h2>
                    <p className="text-sm text-muted-foreground">{selectedClient.industry} • ID: {selectedClient.id}</p>
                  </div>
                </div>
                <button 
                  onClick={() => setIsClientDetailsModalOpen(false)} 
                  className="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors"
                >
                  <X size={20} />
                </button>
              </div>

              <div className="p-6 space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-4">
                    <h3 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Contact Information</h3>
                    <div className="space-y-3">
                      <div className="flex items-center gap-3 text-sm">
                        <UserPlus size={16} className="text-muted-foreground" />
                        <span className="font-medium">{selectedClient.contactPerson}</span>
                      </div>
                      <div className="flex items-center gap-3 text-sm">
                        <Target size={16} className="text-muted-foreground" />
                        <a href={`mailto:${selectedClient.email}`} className="text-primary hover:underline">{selectedClient.email}</a>
                      </div>
                      <div className="flex items-center gap-3 text-sm">
                        <Clock size={16} className="text-muted-foreground" />
                        <span>{selectedClient.phone}</span>
                      </div>
                      {selectedClient.website && (
                        <div className="flex items-center gap-3 text-sm">
                          <TrendingUp size={16} className="text-muted-foreground" />
                          <a href={selectedClient.website} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">{selectedClient.website}</a>
                        </div>
                      )}
                    </div>
                  </div>

                  <div className="space-y-4">
                    <h3 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Business Overview</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="p-4 rounded-xl bg-muted/30 border border-border">
                        <p className="text-[10px] font-bold uppercase text-muted-foreground mb-1">Total Revenue</p>
                        <p className="text-lg font-bold text-green-500">${selectedClient.revenue.toLocaleString()}</p>
                      </div>
                      <div className="p-4 rounded-xl bg-muted/30 border border-border">
                        <p className="text-[10px] font-bold uppercase text-muted-foreground mb-1">Active Projects</p>
                        <p className="text-lg font-bold">{selectedClient.projects}</p>
                      </div>
                    </div>
                    <div className="p-4 rounded-xl bg-muted/30 border border-border">
                      <p className="text-[10px] font-bold uppercase text-muted-foreground mb-1">Account Status</p>
                      <span className={cn(
                        "inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider",
                        selectedClient.status === 'Active' ? "bg-green-500/10 text-green-500" : 
                        selectedClient.status === 'Onboarding' ? "bg-blue-500/10 text-blue-500" : "bg-muted text-muted-foreground"
                      )}>
                        {selectedClient.status}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="space-y-4">
                  <h3 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Associated Projects</h3>
                  <div className="space-y-2">
                    {projects.filter(p => p.client === selectedClient.name).map(p => (
                      <div key={p.id} className="flex items-center justify-between p-3 rounded-lg bg-muted/20 border border-border hover:bg-muted/30 transition-colors">
                        <div>
                          <p className="text-sm font-bold">{p.name}</p>
                          <p className="text-[10px] text-muted-foreground">{p.status} • Deadline: {p.deadline}</p>
                        </div>
                        <p className="text-sm font-bold">${(p.clientTotalAmount || 0).toLocaleString()}</p>
                      </div>
                    ))}
                    {projects.filter(p => p.client === selectedClient.name).length === 0 && (
                      <p className="text-sm text-muted-foreground italic text-center py-4">No projects found for this client.</p>
                    )}
                  </div>
                </div>
              </div>

              <div className="p-4 border-t border-border bg-muted/10 flex justify-end gap-3">
                <button 
                  onClick={() => setIsClientDetailsModalOpen(false)}
                  className="px-4 py-2 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors"
                >
                  Close
                </button>
                <button 
                  onClick={() => navigate(`/clients?search=${encodeURIComponent(selectedClient.name)}`)}
                  className="px-4 py-2 text-sm font-bold bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors"
                >
                  Full Client Profile
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Full Report Modal */}
      <AnimatePresence>
        {isReportModalOpen && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="w-full max-w-4xl max-h-[90vh] overflow-hidden rounded-2xl border border-border bg-card shadow-2xl flex flex-col"
            >
              <div className="flex items-center justify-between p-6 border-b border-border bg-muted/30">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-lg bg-primary/10 text-primary">
                    <BarChart3 size={24} />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold tracking-tight">Operations Full Report</h2>
                    <p className="text-sm text-muted-foreground">Comprehensive overview of business health and activity.</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <button 
                    onClick={downloadFullReport}
                    className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-bold text-primary-foreground hover:bg-primary/90 transition-all shadow-md active:scale-95"
                  >
                    <Download size={18} />
                    Export CSV
                  </button>
                  <button 
                    onClick={() => setIsReportModalOpen(false)} 
                    className="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors"
                  >
                    <X size={20} />
                  </button>
                </div>
              </div>

              <div className="flex-1 overflow-y-auto p-6 space-y-8">
                {/* Executive Summary */}
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                  <ReportStatCard label="Total Revenue" value={`$${stats.totalRevenue.toLocaleString()}`} icon={TrendingUp} color="text-blue-500" />
                  <ReportStatCard label="Total Expenses" value={`$${stats.totalExpenses.toLocaleString()}`} icon={Receipt} color="text-red-500" />
                  <ReportStatCard label="Net Profit" value={`$${stats.profit.toLocaleString()}`} icon={DollarSign} color="text-green-500" />
                  <ReportStatCard label="Active Projects" value={stats.activeProjects.toString()} icon={Briefcase} color="text-orange-500" />
                </div>

                {/* Detailed Sections */}
                <div className="space-y-6">
                  <ReportTableSection 
                    title="Recent Projects" 
                    icon={Briefcase}
                    headers={['Name', 'Client', 'Status', 'Value']}
                    data={projects.slice(0, 5).map(p => [p.name, p.client, p.status, `$${(p.clientTotalAmount || 0).toLocaleString()}`])}
                  />
                  
                  <ReportTableSection 
                    title="Key Clients" 
                    icon={Users}
                    headers={['Name', 'Industry', 'Status', 'Revenue']}
                    data={clients.slice(0, 5).map(c => [c.name, c.industry, c.status, `$${c.revenue.toLocaleString()}`])}
                  />

                  <ReportTableSection 
                    title="Critical Tasks" 
                    icon={CheckSquare}
                    headers={['Task', 'Project', 'Assignee', 'Due Date']}
                    data={tasks.slice(0, 5).map(t => [t.title, t.project, t.assignee, t.dueDate])}
                  />
                </div>
              </div>

              <div className="p-4 border-t border-border bg-muted/10 text-center">
                <p className="text-[10px] text-muted-foreground uppercase tracking-widest font-medium">
                  Report generated on {new Date().toLocaleString()} • Confidential
                </p>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
}

function ReportStatCard({ label, value, icon: Icon, color }: { label: string, value: string, icon: any, color: string }) {
  return (
    <div className="rounded-xl border border-border bg-background p-4 shadow-sm">
      <div className="flex items-center gap-3 mb-2">
        <div className={cn("p-2 rounded-lg bg-muted", color.replace('text-', 'bg-').replace('500', '500/10'))}>
          <Icon size={18} className={color} />
        </div>
        <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">{label}</span>
      </div>
      <p className="text-2xl font-bold">{value}</p>
    </div>
  );
}

function ReportTableSection({ title, icon: Icon, headers, data }: { title: string, icon: any, headers: string[], data: string[][] }) {
  return (
    <div className="space-y-3">
      <div className="flex items-center gap-2 px-1">
        <Icon size={18} className="text-primary" />
        <h3 className="text-sm font-bold uppercase tracking-wider">{title}</h3>
      </div>
      <div className="rounded-xl border border-border overflow-hidden">
        <table className="w-full text-left text-sm">
          <thead className="bg-muted/50 border-b border-border">
            <tr>
              {headers.map((h, i) => (
                <th key={i} className="px-4 py-3 font-semibold text-muted-foreground">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {data.map((row, i) => (
              <tr key={i} className="hover:bg-muted/30 transition-colors">
                {row.map((cell, j) => (
                  <td key={j} className="px-4 py-3">{cell}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function LeadsSection({ onAddLead }: { onAddLead: () => void }) {
  const { projects, addClient, updateProject, clients } = useApp();
  const leads = projects.filter(p => p.status === 'Planning' || p.status === 'Pending');

  const handleConvert = async (lead: Project) => {
    try {
      // 1. Check if client exists, if not create one
      const clientExists = clients.find(c => c.name.toLowerCase() === lead.client.toLowerCase());
      if (!clientExists) {
        const newClient: Client = {
          id: `CL-${Math.random().toString(36).substr(2, 5).toUpperCase()}`,
          name: lead.client,
          industry: 'Technology', // Default
          contactPerson: 'Pending',
          email: 'pending@company.com',
          phone: 'N/A',
          status: 'Onboarding',
          projects: 1,
          revenue: 0
        };
        await addClient(newClient);
      }

      // 2. Update project status to Active
      await updateProject(lead.id, { status: 'Active' });
      toast.success(`Lead converted! ${lead.client} is now a client and project is Active.`);
    } catch (error) {
      toast.error('Conversion failed');
    }
  };

  const getCurrencySymbol = (currency?: string) => {
    switch (currency) {
      case 'EUR': return '€';
      case 'GBP': return '£';
      case 'AED': return 'AED ';
      case 'SAR': return 'SAR ';
      default: return '$';
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold flex items-center gap-2">
          <Target className="text-blue-500" />
          Active Leads & Sales Pipeline
        </h2>
        <button 
          onClick={onAddLead}
          className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
        >
          <Plus size={18} />
          New Lead
        </button>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {leads.map(lead => (
          <div key={lead.id} className="rounded-xl border border-border bg-card p-5 shadow-sm hover:shadow-md transition-all">
            <div className="flex items-start justify-between mb-4">
              <div>
                <h3 className="font-bold">{lead.name}</h3>
                <p className="text-xs text-muted-foreground">{lead.client}</p>
              </div>
              <span className="px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-500 text-[10px] font-bold uppercase">
                {lead.status}
              </span>
            </div>
            <div className="space-y-2 mb-4">
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Expected Value</span>
                <span className="font-bold">{getCurrencySymbol(lead.currency)}{(lead.clientTotalAmount || 0).toLocaleString()}</span>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Close Date</span>
                <span>{lead.deadline}</span>
              </div>
            </div>
            <button 
              onClick={() => handleConvert(lead)}
              className="w-full flex items-center justify-center gap-2 py-2 rounded-lg bg-primary/10 text-primary text-sm font-bold hover:bg-primary/20 transition-colors"
            >
              Convert to Project
              <ArrowRight size={16} />
            </button>
          </div>
        ))}
        {leads.length === 0 && (
          <div className="col-span-full py-12 text-center border-2 border-dashed border-border rounded-xl">
            <Target className="mx-auto text-muted-foreground mb-2 opacity-20" size={48} />
            <p className="text-muted-foreground">No active leads in the pipeline.</p>
          </div>
        )}
      </div>
    </div>
  );
}

function ClientsSection({ onAddClient, onViewDetails, onEditClient, onDeleteClient }: { 
  onAddClient: () => void, 
  onViewDetails: (client: Client) => void,
  onEditClient: (client: Client) => void,
  onDeleteClient: (client: Client) => void
}) {
  const { clients, updateClient } = useApp();

  const handleToggleStatus = async (client: Client) => {
    try {
      const newStatus = client.status === 'Active' ? 'Inactive' : 'Active';
      await updateClient(client.id, { status: newStatus });
      toast.success(`Client ${client.name} is now ${newStatus}`);
    } catch (error) {
      toast.error('Failed to update client status');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold flex items-center gap-2">
          <Users className="text-purple-500" />
          Client Relationships
        </h2>
        <button 
          onClick={onAddClient}
          className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
        >
          <Plus size={18} />
          Add Client
        </button>
      </div>

      <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
        <table className="w-full text-left text-sm">
          <thead className="bg-muted/50 border-b border-border">
            <tr>
              <th className="px-6 py-4 font-semibold">Client</th>
              <th className="px-6 py-4 font-semibold">Industry</th>
              <th className="px-6 py-4 font-semibold">Status</th>
              <th className="px-6 py-4 font-semibold">Revenue</th>
              <th className="px-6 py-4 font-semibold text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {clients.map(client => (
              <tr key={client.id} className="hover:bg-accent/30 transition-colors">
                <td className="px-6 py-4 font-medium">{client.name}</td>
                <td className="px-6 py-4 text-muted-foreground">{client.industry}</td>
                <td className="px-6 py-4">
                  <button 
                    onClick={() => handleToggleStatus(client)}
                    className={cn(
                      "px-2 py-0.5 rounded-full text-[10px] font-bold uppercase transition-colors hover:opacity-80",
                      client.status === 'Active' ? "bg-green-500/10 text-green-500" : "bg-muted text-muted-foreground"
                    )}
                  >
                    {client.status}
                  </button>
                </td>
                <td className="px-6 py-4 font-bold">${client.revenue.toLocaleString()}</td>
                <td className="px-6 py-4 text-right">
                  <div className="flex items-center justify-end gap-2">
                    <button 
                      onClick={() => onViewDetails(client)}
                      className="p-1.5 rounded-md hover:bg-accent text-primary transition-colors"
                      title="View Details"
                    >
                      <Search size={16} />
                    </button>
                    <button 
                      onClick={() => onEditClient(client)}
                      className="p-1.5 rounded-md hover:bg-accent text-blue-500 transition-colors"
                      title="Edit Client"
                    >
                      <Edit size={16} />
                    </button>
                    <button 
                      onClick={() => onDeleteClient(client)}
                      className="p-1.5 rounded-md hover:bg-accent text-red-500 transition-colors"
                      title="Delete Client"
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ProjectsSection({ onAddProject }: { onAddProject: () => void }) {
  const navigate = useNavigate();
  const { projects, engineers, updateProject, deleteProject } = useApp();
  const [openAssignId, setOpenAssignId] = useState<string | null>(null);
  const activeProjects = projects.filter(p => !p.status || p.status === 'Planning' || p.status === 'Scheduled' || p.status === 'In Progress' || p.status === 'Work In Progress' || p.status === 'Active');

  const handleAssign = async (projectId: string, engineerName: string) => {
    try {
      const engineer = engineers.find(e => e.name === engineerName);
      await updateProject(projectId, { 
        assignedTo: engineerName,
        assignedRole: engineer?.role || 'Lead Engineer'
      });
      toast.success(`Assigned ${engineerName} to project`);
    } catch (error) {
      toast.error('Assignment failed');
    }
  };

  const handleUnassign = async (projectId: string) => {
    try {
      await updateProject(projectId, { 
        assignedTo: '',
        assignedRole: ''
      });
      toast.success('Engineer unassigned successfully');
    } catch (error) {
      toast.error('Failed to unassign engineer');
    }
  };

  const handleDeleteProject = async (projectId: string) => {
    if (window.confirm('Are you sure you want to delete this project? This action cannot be undone.')) {
      try {
        await deleteProject(projectId);
        toast.success('Project deleted successfully');
      } catch (error) {
        toast.error('Failed to delete project');
      }
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold flex items-center gap-2">
          <Briefcase className="text-orange-500" />
          Project Management & Assignments
        </h2>
        <button 
          onClick={onAddProject}
          className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
        >
          <Plus size={18} />
          New Project
        </button>
      </div>

      <div className="grid gap-6">
        {activeProjects.map(project => (
          <div key={project.id} className="rounded-xl border border-border bg-card p-6 shadow-sm">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
              <div>
                <div className="flex items-center gap-3 mb-1">
                  <h3 className="text-lg font-bold">{project.name}</h3>
                  <div className="flex items-center gap-2">
                    <button 
                      onClick={() => window.location.href = '/projects'}
                      className="text-[10px] text-primary hover:underline font-bold uppercase tracking-wider"
                    >
                      View
                    </button>
                    <button 
                      onClick={() => handleDeleteProject(project.id)}
                      className="text-[10px] text-red-500 hover:underline font-bold uppercase tracking-wider"
                    >
                      Delete
                    </button>
                  </div>
                </div>
                <p className="text-sm text-muted-foreground">Client: {project.client} • ID: {project.id}</p>
              </div>
              <div className="flex items-center gap-4">
                <div className="text-right">
                  <p className="text-xs text-muted-foreground uppercase font-bold">Deadline</p>
                  <p className="font-medium">{project.deadline}</p>
                </div>
                <div className="h-8 w-px bg-border" />
                <div className="text-right">
                  <p className="text-xs text-muted-foreground uppercase font-bold">Budget</p>
                  <p className="font-bold text-primary">${(project.clientTotalAmount || 0).toLocaleString()}</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-8">
              <div className="space-y-4">
                <h4 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Team Assignment</h4>
                <div className="flex items-center gap-4 p-4 rounded-lg bg-muted/30 border border-border">
                  <div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                    <Wrench size={24} />
                  </div>
                  <div className="flex-1">
                    <p className="text-sm font-bold">{project.assignedTo || 'No Engineer Assigned'}</p>
                    <p className="text-xs text-muted-foreground">{project.assignedRole || 'Assign a lead engineer to start'}</p>
                  </div>
                  <div className="flex items-center gap-2">
                    {project.assignedTo && (
                      <button 
                        onClick={() => handleUnassign(project.id)}
                        className="p-1.5 rounded-md hover:bg-red-50 text-red-500 transition-colors"
                        title="Remove Assignment"
                      >
                        <X size={16} />
                      </button>
                    )}
                    <div className="relative">
                      <button 
                        onClick={() => setOpenAssignId(openAssignId === project.id ? null : project.id)}
                        className={cn(
                          "px-3 py-1.5 rounded-md border text-xs font-bold transition-all shadow-sm flex items-center gap-1.5",
                          openAssignId === project.id 
                            ? "bg-primary text-primary-foreground border-primary" 
                            : "bg-card border-border hover:bg-accent"
                        )}
                      >
                        Assign
                        <ChevronRight size={14} className={cn("transition-transform", openAssignId === project.id && "rotate-90")} />
                      </button>
                    {openAssignId === project.id && (
                      <div className="absolute right-0 top-full mt-2 z-50 w-56 rounded-xl border border-border bg-card p-1 shadow-xl animate-in fade-in slide-in-from-top-2">
                        <div className="px-3 py-2 border-b border-border mb-1">
                          <p className="text-[10px] font-bold text-muted-foreground uppercase tracking-widest">Available Engineers</p>
                        </div>
                        <div className="max-h-64 overflow-y-auto">
                          {engineers.filter(e => e.status === 'Available').map(eng => (
                            <button
                              key={eng.id}
                              onClick={() => {
                                handleAssign(project.id, eng.name);
                                setOpenAssignId(null);
                              }}
                              className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-xs hover:bg-accent transition-colors group/eng"
                            >
                              <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center text-[10px] font-bold text-primary group-hover/eng:bg-primary group-hover/eng:text-primary-foreground transition-colors">
                                {eng.name.charAt(0)}
                              </div>
                              <div className="flex-1">
                                <p className="font-bold">{eng.name}</p>
                                <p className="text-[10px] text-muted-foreground">{eng.role}</p>
                              </div>
                            </button>
                          ))}
                          {engineers.filter(e => e.status === 'Available').length === 0 && (
                            <div className="p-4 text-center">
                              <p className="text-[10px] text-muted-foreground italic mb-2">No available engineers</p>
                              <button 
                                onClick={() => navigate('/engineers?create=true')}
                                className="text-[10px] text-primary font-bold hover:underline"
                              >
                                Add New Engineer
                              </button>
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <h4 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Project Health</h4>
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-xs">
                    <span>Progress</span>
                    <span className="font-bold">65%</span>
                  </div>
                  <div className="h-2 w-full bg-muted rounded-full overflow-hidden">
                    <div className="h-full bg-orange-500 w-[65%]" />
                  </div>
                  <div className="flex items-center justify-between mt-2">
                    <span className="text-[10px] text-muted-foreground flex items-center gap-1">
                      <Clock size={10} />
                      12 days remaining
                    </span>
                    <span className="text-[10px] text-green-500 font-bold">On Track</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      ))}
        {activeProjects.length === 0 && (
          <div className="py-12 text-center border-2 border-dashed border-border rounded-xl">
            <Briefcase className="mx-auto text-muted-foreground mb-2 opacity-20" size={48} />
            <p className="text-muted-foreground">No active projects currently being managed.</p>
          </div>
        )}
      </div>
    </div>
  );
}

function ExecutionSection({ onAddTask }: { onAddTask: () => void }) {
  const { tasks, updateTask } = useApp();

  const handleLogTime = async (task: Task) => {
    try {
      await updateTask(task.id, { status: 'Completed', completedDate: new Date().toISOString().split('T')[0] });
      toast.success(`Time logged for ${task.title}. Task marked as Completed.`);
    } catch (error) {
      toast.error('Failed to log time');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold flex items-center gap-2">
          <CheckSquare className="text-green-500" />
          Task Execution & Timesheets
        </h2>
        <button 
          onClick={onAddTask}
          className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
        >
          <Plus size={18} />
          Add Task
        </button>
      </div>

      <div className="grid md:grid-cols-3 gap-6">
        {['To Do', 'In Progress', 'Completed'].map(status => (
          <div key={status} className="space-y-4">
            <div className="flex items-center justify-between px-2">
              <h3 className="text-sm font-bold uppercase tracking-widest text-muted-foreground">{status}</h3>
              <span className="text-xs font-bold bg-muted px-2 py-0.5 rounded-full">
                {tasks.filter(t => t.status === status).length}
              </span>
            </div>
            <div className="space-y-3">
              {tasks.filter(t => t.status === status).map(task => (
                <div key={task.id} className="p-4 rounded-xl border border-border bg-card shadow-sm hover:shadow-md transition-all group/task">
                  <div className="flex items-start justify-between mb-1">
                    <h4 className="font-bold text-sm">{task.title}</h4>
                    {status !== 'Completed' && (
                      <button 
                        onClick={() => handleLogTime(task)}
                        className="opacity-0 group-hover/task:opacity-100 p-1 rounded-md bg-primary/10 text-primary hover:bg-primary/20 transition-all"
                        title="Log Time & Complete"
                      >
                        <Clock size={14} />
                      </button>
                    )}
                  </div>
                  <div className="flex items-center justify-between mb-3">
                    <p className="text-[10px] text-muted-foreground">{task.project}</p>
                    <button 
                      onClick={() => window.location.href = '/tasks'}
                      className="opacity-0 group-hover/task:opacity-100 text-[8px] text-primary hover:underline font-bold uppercase"
                    >
                      Details
                    </button>
                  </div>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-1 text-[10px] text-muted-foreground">
                      <Calendar size={10} />
                      {task.dueDate}
                    </div>
                    <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center text-[10px] font-bold text-primary">
                      {task.assignee.charAt(0)}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function FinanceSection({ onAddExpense, onGenerateInvoice }: { onAddExpense: () => void, onGenerateInvoice: () => void }) {
  const { projects, expenses, updateProject } = useApp();
  
  const handleGenerateInvoice = async (project: Project) => {
    try {
      await updateProject(project.id, { 
        clientInvoiceStatus: 'Unpaid',
        issueDate: new Date().toISOString().split('T')[0]
      });
      toast.success(`Invoice generated for ${project.client}`);
    } catch (error) {
      toast.error('Failed to generate invoice');
    }
  };

  const handleReceivePayment = async (project: Project) => {
    try {
      await updateProject(project.id, { clientInvoiceStatus: 'Paid' });
      toast.success(`Payment received from ${project.client}`);
    } catch (error) {
      toast.error('Failed to record payment');
    }
  };

  const financialData = useMemo(() => {
    const revenue = projects.reduce((acc, p) => acc + (p.clientTotalAmount || 0), 0);
    const cost = expenses.filter(e => e.status === 'Approved').reduce((acc, e) => acc + e.amount, 0);
    const profit = revenue - cost;
    const margin = revenue > 0 ? (profit / revenue) * 100 : 0;

    return { revenue, cost, profit, margin };
  }, [projects, expenses]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold flex items-center gap-2">
          <DollarSign className="text-emerald-500" />
          Financial Control & Billing
        </h2>
        <div className="flex items-center gap-2">
          <button 
            onClick={onAddExpense}
            className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
          >
            <Receipt size={18} />
            Add Expense
          </button>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <FinanceStatCard title="Total Revenue" value={financialData.revenue} color="text-emerald-500" />
        <FinanceStatCard title="Total Expenses" value={financialData.cost} color="text-red-500" />
        <FinanceStatCard title="Net Profit" value={financialData.profit} color="text-primary" />
        <FinanceStatCard title="Profit Margin" value={`${financialData.margin.toFixed(1)}%`} color="text-blue-500" isCurrency={false} />
      </div>

      <div className="grid md:grid-cols-2 gap-6">
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <h3 className="font-bold mb-4">Recent Invoices</h3>
          <div className="space-y-4">
            {projects.filter(p => p.status === 'Active' || p.status === 'Completed').slice(0, 5).map(p => (
              <div key={p.id} className="flex items-center justify-between p-3 rounded-lg bg-muted/20 border border-border">
                <div>
                  <p className="text-sm font-bold">{p.client}</p>
                  <p className="text-[10px] text-muted-foreground">{p.name}</p>
                </div>
                <div className="flex items-center gap-3">
                  <div className="text-right">
                    <p className="text-sm font-bold">${(p.clientTotalAmount || 0).toLocaleString()}</p>
                    <span className={cn(
                      "text-[10px] font-bold uppercase",
                      p.clientInvoiceStatus === 'Paid' ? "text-green-500" : 
                      p.clientInvoiceStatus === 'Unpaid' ? "text-orange-500" : "text-muted-foreground"
                    )}>{p.clientInvoiceStatus || 'Not Invoiced'}</span>
                  </div>
                  <div className="flex flex-col gap-1">
                    {p.clientInvoiceStatus === 'Unpaid' && (
                      <button 
                        onClick={() => handleReceivePayment(p)}
                        className="p-1 rounded bg-green-500/10 text-green-500 hover:bg-green-500/20 transition-colors"
                        title="Mark as Paid"
                      >
                        <CheckCircle2 size={14} />
                      </button>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <h3 className="font-bold mb-4">Recent Expenses</h3>
          <div className="space-y-4">
            {expenses.slice(0, 5).map(e => (
              <div key={e.id} className="flex items-center justify-between p-3 rounded-lg bg-muted/20 border border-border">
                <div>
                  <p className="text-sm font-bold">{e.description}</p>
                  <p className="text-[10px] text-muted-foreground">{e.category} • {e.date}</p>
                </div>
                <div className="text-right">
                  <p className="text-sm font-bold text-red-500">-${e.amount.toLocaleString()}</p>
                  <span className="text-[10px] font-bold uppercase text-muted-foreground">{e.status}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function FinanceStatCard({ title, value, color, isCurrency = true }: { title: string, value: any, color: string, isCurrency?: boolean }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
      <p className="text-xs font-bold text-muted-foreground uppercase tracking-wider mb-1">{title}</p>
      <p className={cn("text-xl font-bold", color)}>
        {isCurrency ? `$${value.toLocaleString()}` : value}
      </p>
    </div>
  );
}

function RecruitmentStatCard({ title, value, icon: Icon, trend, trendColor = "text-muted-foreground", onClick }: { title: string, value: string, icon: any, trend: string, trendColor?: string, onClick?: () => void }) {
  return (
    <div 
      onClick={onClick}
      className={cn(
        "rounded-xl border border-border bg-card p-4 shadow-sm transition-all",
        onClick && "cursor-pointer hover:border-primary/50 hover:shadow-md"
      )}
    >
      <div className="flex items-center justify-between mb-2">
        <div className="p-2 rounded-lg bg-accent text-muted-foreground">
          <Icon size={18} />
        </div>
      </div>
      <div>
        <p className="text-sm text-muted-foreground">{title}</p>
        <p className="text-2xl font-bold">{value}</p>
        <p className={cn("text-xs mt-1", trendColor)}>{trend}</p>
      </div>
    </div>
  );
}
