import React, { useState, useEffect, useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Briefcase, 
  Plus, 
  Search, 
  Filter,
  Clock, 
  Users, 
  CheckCircle2,
  X,
  Calendar,
  Building2,
  User,
  UserCheck,
  Ticket,
  Mail,
  Phone,
  DollarSign,
  Hash,
  FileText,
  Trash2,
  ChevronDown,
  Check,
  Timer,
  Upload,
  Download,
  File,
  Paperclip
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

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

export function ProjectList() {
  const { projects: allProjects, addProject, updateProject, deleteProject, clients, engineers, tasks, companySettings, currencies } = useApp();
  const { profile, hasPermission } = useAuth();
  
  const canViewAll = useMemo(() => {
    if (!profile) return false;
    return hasPermission('projects.view_all') || profile.uid === 'admin-123';
  }, [profile, hasPermission]);

  const projects = useMemo(() => {
    if (canViewAll) return allProjects;
    return allProjects.filter(p => 
      p.assignedTo === profile?.name || 
      p.assignedEmail === profile?.email ||
      p.assignedRole === profile?.role
    );
  }, [allProjects, canViewAll, profile]);
  
  const getSymbol = (code?: string) => {
    if (!code) return '$';
    const c = currencies.find(curr => curr.code === code);
    return c ? c.symbol : '$';
  };
  
  const stats = useMemo(() => {
    const total = projects.length;
    const active = projects.filter(p => ['Active', 'Work In Progress', 'Scheduled'].includes(p.status)).length;
    const completed = projects.filter(p => p.status === 'Completed').length;
    const totalValue = projects.reduce((sum, p) => sum + (p.clientTotalAmount || 0), 0);
    
    return { total, active, completed, totalValue };
  }, [projects]);

  const [searchParams, setSearchParams] = useSearchParams();
  const initialSearch = searchParams.get('search') || '';
  const initialStatus = searchParams.get('status') || 'All';
  const [searchQuery, setSearchQuery] = useState(initialSearch);
  const [statusFilter, setStatusFilter] = useState(initialStatus);

  useEffect(() => {
    const search = searchParams.get('search');
    const status = searchParams.get('status');
    const create = searchParams.get('create');

    if (search) setSearchQuery(search);
    if (status) setStatusFilter(status);
    if (create === 'true') {
      setIsModalOpen(true);
      // Clear the param so it doesn't reopen on refresh/navigation
      const newParams = new URLSearchParams(searchParams);
      newParams.delete('create');
      setSearchParams(newParams, { replace: true });
    }
  }, [searchParams, setSearchParams]);

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

  const [showAllProjects, setShowAllProjects] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [activeTab, setActiveTab] = useState<'general' | 'contacts' | 'financials' | 'execution'>('general');
  const [editingProjectId, setEditingProjectId] = useState<string | null>(null);
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [filterClient, setFilterClient] = useState('All');
  const [filterEngineer, setFilterEngineer] = useState('All');
  const [newProject, setNewProject] = useState<Partial<Project>>({
    name: '',
    client: '',
    deadline: '',
    team: 1,
    status: 'Planning',
    description: '',
    currency: 'USD',
    ticketId: '',
    personName: '',
    email: '',
    contactNumber: '',
    assignedEmail: '',
    assignedContactNumber: '',
    hourlyRate: 0,
    halfDayRate: 0,
    fullDayRate: 0,
    monthlyRate: 0,
    travelCost: 0,
    materialCost: 0,
    totalAmount: 0,
    clientHourlyRate: 0,
    clientHalfDayRate: 0,
    clientFullDayRate: 0,
    clientMonthlyRate: 0,
    clientTravelCost: 0,
    clientMaterialCost: 0,
    clientTotalAmount: 0,
    taxRate: 20,
    taxAmount: 0,
    assignedTo: '',
    assignedRole: '',
    timeIn: '',
    timeOut: '',
    totalTime: '',
    totalDays: 0,
    completedDate: '',
    engineerInvoiceStatus: 'Unpaid',
    clientInvoiceStatus: 'Unpaid',
    files: []
  });

  const filterRef = React.useRef<HTMLDivElement>(null);

  const handleCreateProject = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;
    if (!newProject.name || !newProject.client || !newProject.deadline) {
      toast.error('Please fill in all required fields');
      return;
    }

    setIsSubmitting(true);
    try {
      if (editingProjectId) {
        await updateProject(editingProjectId, newProject);
        toast.success('Project updated successfully');
      } else {
        const newId = `PRJ-${Math.random().toString(36).substr(2, 5).toUpperCase()}`;
        const projectToAdd = {
          id: newId,
          name: newProject.name || '',
          client: newProject.client || '',
          deadline: newProject.deadline || '',
          team: newProject.team || 1,
          status: newProject.status || 'Planning',
          ...newProject
        } as Project;
        await addProject(projectToAdd);
        toast.success('Project created successfully', {
          description: `${projectToAdd.name} has been added to your portfolio.`
        });
      }

      setIsModalOpen(false);
      setEditingProjectId(null);
      setNewProject({
        name: '',
        client: '',
        deadline: '',
        team: 1,
        status: 'Planning',
        description: '',
        currency: 'USD',
        ticketId: '',
        personName: '',
        email: '',
        contactNumber: '',
        hourlyRate: 0,
        halfDayRate: 0,
        fullDayRate: 0,
        monthlyRate: 0,
        travelCost: 0,
        materialCost: 0,
        totalAmount: 0,
        clientHourlyRate: 0,
        clientHalfDayRate: 0,
        clientFullDayRate: 0,
        clientMonthlyRate: 0,
        clientTravelCost: 0,
        clientMaterialCost: 0,
        clientTotalAmount: 0,
        assignedTo: '',
        assignedRole: '',
        assignedEmail: '',
        assignedContactNumber: '',
        timeIn: '',
        timeOut: '',
        totalTime: '',
        completedDate: '',
        engineerInvoiceStatus: 'Unpaid',
        clientInvoiceStatus: 'Unpaid'
      });
    } catch (error) {
      console.error('Project save error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleEditProject = (project: Project) => {
    setEditingProjectId(project.id);
    setNewProject({ ...project });
    setIsModalOpen(true);
  };

  const handleDeleteProject = async (id: string) => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      await deleteProject(id);
      toast.success('Project deleted successfully');
    } catch (error) {
      console.error('Delete project error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleUpdateStatus = async (id: string, newStatus: string) => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    const updates: Partial<Project> = { status: newStatus };
    if (['Completed', 'Accepted', 'Rejected'].includes(newStatus)) {
      updates.completedDate = new Date().toISOString().split('T')[0];
    }
    try {
      await updateProject(id, updates);
      setActiveDropdown(null);
      toast.success(`Project ${newStatus.toLowerCase()} successfully`);
    } catch (error) {
      console.error('Status update error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    if (newProject.timeIn && newProject.timeOut) {
      const [h1, m1] = newProject.timeIn.split(':').map(Number);
      const [h2, m2] = newProject.timeOut.split(':').map(Number);
      
      let diffMinutes = (h2 * 60 + m2) - (h1 * 60 + m1);
      if (diffMinutes < 0) diffMinutes += 24 * 60; // Handle overnight
      
      const multiplier = newProject.totalDays && newProject.totalDays > 0 ? newProject.totalDays : 1;
      const totalMinutes = diffMinutes * multiplier;
      
      const hours = Math.floor(totalMinutes / 60);
      const mins = totalMinutes % 60;
      
      setNewProject(prev => ({
        ...prev,
        totalTime: `${hours}h ${mins}m`
      }));
    }
  }, [newProject.timeIn, newProject.timeOut, newProject.totalDays]);

  useEffect(() => {
    const parseTotalTime = (timeStr?: string) => {
      if (!timeStr) return 0;
      const hoursMatch = timeStr.match(/(\d+)h/);
      const minsMatch = timeStr.match(/(\d+)m/);
      const hours = hoursMatch ? parseInt(hoursMatch[1]) : 0;
      const mins = minsMatch ? parseInt(minsMatch[1]) : 0;
      return hours + mins / 60;
    };

    const hours = parseTotalTime(newProject.totalTime);
    const hourlyTotal = (newProject.hourlyRate || 0) * hours;
    const clientHourlyTotal = (newProject.clientHourlyRate || 0) * hours;
    
    const calculated = hourlyTotal + (newProject.travelCost || 0) + (newProject.materialCost || 0) + 
           (newProject.halfDayRate || 0) + (newProject.fullDayRate || 0) + (newProject.monthlyRate || 0);

    const clientCalculated = clientHourlyTotal + (newProject.clientTravelCost || 0) + (newProject.clientMaterialCost || 0) + 
           (newProject.clientHalfDayRate || 0) + (newProject.clientFullDayRate || 0) + (newProject.clientMonthlyRate || 0);
    
    setNewProject(prev => ({
      ...prev,
      totalAmount: parseFloat(calculated.toFixed(2)),
      clientTotalAmount: parseFloat(clientCalculated.toFixed(2)),
      taxAmount: 0
    }));
  }, [
    newProject.hourlyRate, 
    newProject.totalTime, 
    newProject.travelCost, 
    newProject.materialCost, 
    newProject.halfDayRate, 
    newProject.fullDayRate, 
    newProject.monthlyRate,
    newProject.clientHourlyRate,
    newProject.clientTravelCost,
    newProject.clientMaterialCost,
    newProject.clientHalfDayRate,
    newProject.clientFullDayRate,
    newProject.clientMonthlyRate
  ]);

  const filteredProjects = projects.filter(prj => {
    const matchesSearch = prj.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      prj.client.toLowerCase().includes(searchQuery.toLowerCase()) ||
      prj.id.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesStatus = statusFilter === 'All' || prj.status === statusFilter;
    const matchesClient = filterClient === 'All' || prj.client === filterClient;
    const matchesEngineer = filterEngineer === 'All' || prj.assignedTo === filterEngineer;
    
    const isBaseMatch = matchesSearch && matchesStatus && matchesClient && matchesEngineer;
    
    if (showAllProjects) return isBaseMatch;
    
    // Default view: hide Completed, Rejected, Cancelled unless explicitly filtered
    const inactiveStatuses = ['Completed', 'Rejected', 'Cancelled'];
    const isExplicitlyInactive = inactiveStatuses.includes(statusFilter);
    
    if (isExplicitlyInactive) {
      return isBaseMatch;
    }

    return isBaseMatch && !inactiveStatuses.includes(prj.status);
  });

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const fileList = e.target.files;
    if (!fileList) return;

    const uploadPromises = Array.from(fileList).map(async (file: File) => {
      const formData = new FormData();
      formData.append('file', file);
      
      try {
        const response = await fetch('/api/upload', {
          method: 'POST',
          body: formData,
        });
        
        if (!response.ok) throw new Error('Upload failed');
        return await response.json();
      } catch (error) {
        console.error('Upload error:', error);
        toast.error(`Failed to upload ${file.name}`);
        return null;
      }
    });

    const uploadedFiles = (await Promise.all(uploadPromises)).filter(f => f !== null);

    if (uploadedFiles.length > 0) {
      setNewProject(prev => ({
        ...prev,
        files: [...(prev.files || []), ...uploadedFiles]
      }));
      toast.success(`${uploadedFiles.length} file(s) uploaded successfully`);
    }
  };

  const removeFile = (index: number) => {
    setNewProject(prev => ({
      ...prev,
      files: (prev.files || []).filter((_, i) => i !== index)
    }));
  };

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

    const headers = ['ID', 'Name', 'Client', 'Deadline', 'Status', 'Total Amount', 'Assigned To'];
    const csvRows = [
      headers.join(','),
      ...filteredProjects.map(p => [
        `"${p.id}"`,
        `"${p.name}"`,
        `"${p.client}"`,
        `"${p.deadline}"`,
        `"${p.status}"`,
        p.totalAmount.toFixed(2),
        `"${p.assignedTo || ''}"`
      ].join(','))
    ];

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

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

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

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

          const clean = (val: string) => val.replace(/^"|"$/g, '').trim();
          
          const project = {
            id: clean(matches[0]),
            name: clean(matches[1]),
            client: clean(matches[2]),
            deadline: clean(matches[3]),
            status: clean(matches[4]) as any,
            totalAmount: parseFloat(clean(matches[5])) || 0,
            assignedTo: clean(matches[6]) || '',
            issueDate: new Date().toISOString().split('T')[0],
            team: 1
          };
          newProjects.push(project);
        }

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

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

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

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Projects</h1>
          <p className="text-muted-foreground">Monitor and manage all active and upcoming projects.</p>
        </div>
        <div className="flex items-center gap-3">
          {hasPermission('projects.create') && (
            <div className="relative">
              <input 
                type="file" 
                accept=".csv"
                className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                onChange={handleImportCSV}
              />
              <button className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors">
                <Upload size={18} />
                Import CSV
              </button>
            </div>
          )}
          {hasPermission('projects.export') && (
            <button 
              onClick={handleExportCSV}
              className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
            >
              <Download size={18} />
              Export CSV
            </button>
          )}
          {hasPermission('projects.create') && (
            <button 
              onClick={() => {
                setEditingProjectId(null);
                setNewProject({
                  name: '',
                  client: '',
                  deadline: '',
                  issueDate: new Date().toISOString().split('T')[0],
                  team: 1,
                  status: 'Planning',
                  description: '',
                  currency: 'USD',
                  ticketId: '',
                  personName: '',
                  email: '',
                  contactNumber: '',
                  hourlyRate: 0,
                  halfDayRate: 0,
                  fullDayRate: 0,
                  monthlyRate: 0,
                  travelCost: 0,
                  materialCost: 0,
                  totalAmount: 0,
                  clientHourlyRate: 0,
                  clientHalfDayRate: 0,
                  clientFullDayRate: 0,
                  clientMonthlyRate: 0,
                  clientTravelCost: 0,
                  clientMaterialCost: 0,
                  clientTotalAmount: 0,
                  taxRate: companySettings.vatTaxRate || 20,
                  taxAmount: 0,
                  assignedTo: '',
                  assignedRole: '',
                  assignedEmail: '',
                  assignedContactNumber: '',
                  timeIn: '',
                  timeOut: '',
                  totalTime: '',
                  completedDate: '',
                  engineerInvoiceStatus: 'Unpaid',
                  clientInvoiceStatus: 'Unpaid'
                });
                setIsModalOpen(true);
              }}
              className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors shadow-sm"
            >
              <Plus size={18} />
              Create Project
            </button>
          )}
        </div>
    </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <KPICard 
          title="Total Projects" 
          value={stats.total} 
          icon={Briefcase} 
          colorClass="bg-blue-500/10 text-blue-500" 
        />
        <KPICard 
          title="Active Projects" 
          value={stats.active} 
          icon={Clock} 
          colorClass="bg-orange-500/10 text-orange-500" 
        />
        <KPICard 
          title="Completed" 
          value={stats.completed} 
          icon={CheckCircle2} 
          colorClass="bg-emerald-500/10 text-emerald-500" 
        />
        <KPICard 
          title="Total Value" 
          value={`$${stats.totalValue.toLocaleString()}`} 
          icon={DollarSign} 
          colorClass="bg-primary/10 text-primary" 
        />
      </div>

      {/* Create Project Modal */}
      <AnimatePresence>
        {isModalOpen && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4 overflow-y-auto">
            <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 rounded-2xl border border-border bg-card shadow-2xl overflow-hidden flex flex-col max-h-[90vh]"
            >
              {/* Modal Header */}
              <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">
                    <Briefcase size={24} />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold tracking-tight">
                      {editingProjectId ? 'Edit Project' : 'Create New Project'}
                    </h2>
                    <p className="text-sm text-muted-foreground">
                      {editingProjectId ? `Updating project ${editingProjectId}` : 'Define the scope and details of your new venture'}
                    </p>
                  </div>
                </div>
                <button 
                  onClick={() => {
                    setIsModalOpen(false);
                    setEditingProjectId(null);
                  }}
                  className="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors"
                >
                  <X size={20} />
                </button>
              </div>

              {/* Tab Navigation */}
              <div className="flex items-center gap-1 p-2 bg-muted/20 border-b border-border overflow-x-auto no-scrollbar">
                {[
                  { id: 'general', label: 'General Info', icon: FileText },
                  { id: 'contacts', label: 'Contacts', icon: Users },
                  { id: 'financials', label: 'Financials', icon: DollarSign },
                  { id: 'execution', label: 'Execution', icon: Timer },
                ].map((tab) => (
                  <button
                    key={tab.id}
                    onClick={() => setActiveTab(tab.id as any)}
                    className={cn(
                      "flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all whitespace-nowrap",
                      activeTab === tab.id 
                        ? "bg-background text-primary shadow-sm border border-border" 
                        : "text-muted-foreground hover:bg-muted/50 hover:text-foreground"
                    )}
                  >
                    <tab.icon size={16} />
                    {tab.label}
                  </button>
                ))}
              </div>

              <form onSubmit={handleCreateProject} className="flex-1 overflow-y-auto p-8 space-y-8">
                <AnimatePresence mode="wait">
                  <motion.div
                    key={activeTab}
                    initial={{ opacity: 0, x: 10 }}
                    animate={{ opacity: 1, x: 0 }}
                    exit={{ opacity: 0, x: -10 }}
                    transition={{ duration: 0.2 }}
                    className="space-y-8"
                  >
                    {activeTab === 'general' && (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <div className="space-y-6">
                          <h3 className="text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2">
                            <span className="h-1 w-4 bg-primary rounded-full" />
                            Core Identity
                          </h3>
                          <div className="space-y-4">
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Project Name *</label>
                              <input 
                                type="text" 
                                placeholder="e.g. Cloud Migration Alpha"
                                value={newProject.name || ''}
                                onChange={(e) => setNewProject({...newProject, name: e.target.value})}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all"
                                required
                              />
                            </div>
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Company / Client *</label>
                              <select 
                                value={newProject.client || ''}
                                onChange={(e) => {
                                  const clientName = e.target.value;
                                  const selectedClient = clients.find(c => c.name === clientName);
                                  if (selectedClient) {
                                    setNewProject({
                                      ...newProject, 
                                      client: clientName,
                                      personName: selectedClient.contactPerson,
                                      email: selectedClient.email,
                                      contactNumber: selectedClient.phone
                                    });
                                  } else {
                                    setNewProject({...newProject, client: clientName});
                                  }
                                }}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                                required
                              >
                                <option value="" disabled>Select a client</option>
                                {clients.map(client => (
                                  <option key={client.id} value={client.name}>{client.name}</option>
                                ))}
                                <option value="Other">Other / New Client</option>
                              </select>
                            </div>
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Project Status</label>
                              <select 
                                value={newProject.status || 'Planning'}
                                onChange={(e) => setNewProject({...newProject, status: e.target.value})}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                              >
                                <option value="Planning">Planning</option>
                                <option value="Active">Active</option>
                                <option value="Work In Progress">Work In Progress</option>
                                <option value="Pending">Pending</option>
                                <option value="Scheduled">Scheduled</option>
                                <option value="Completed">Completed</option>
                                <option value="Cancelled">Cancelled</option>
                              </select>
                            </div>
                          </div>
                        </div>

                        <div className="space-y-6">
                          <h3 className="text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2">
                            <span className="h-1 w-4 bg-primary rounded-full" />
                            Timeline
                          </h3>
                          <div className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                              <div className="space-y-2">
                                <label className="text-sm font-semibold">Issue Date</label>
                                <div className="space-y-1">
                                  <input 
                                    type="date" 
                                    value={newProject.issueDate || ''}
                                    onChange={(e) => setNewProject({...newProject, issueDate: e.target.value})}
                                    className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                                  />
                                  {newProject.issueDate && (
                                    <p className="text-[10px] text-primary font-medium px-1">
                                      {formatDate(newProject.issueDate)}
                                    </p>
                                  )}
                                </div>
                              </div>
                              <div className="space-y-2">
                                <label className="text-sm font-semibold">Deadline *</label>
                                <div className="space-y-1">
                                  <input 
                                    type="date" 
                                    value={newProject.deadline || ''}
                                    onChange={(e) => setNewProject({...newProject, deadline: e.target.value})}
                                    className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                                    required
                                  />
                                  {newProject.deadline && (
                                    <p className="text-[10px] text-primary font-medium px-1">
                                      {formatDate(newProject.deadline)}
                                    </p>
                                  )}
                                </div>
                              </div>
                            </div>
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Ticket / Reference ID</label>
                              <div className="relative">
                                <Hash className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
                                <input 
                                  type="text" 
                                  placeholder="e.g. TIC-12345"
                                  value={newProject.ticketId || ''}
                                  onChange={(e) => setNewProject({...newProject, ticketId: e.target.value})}
                                  className="h-11 w-full rounded-xl border border-border bg-background pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                                />
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    )}

                    {activeTab === 'contacts' && (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-12">
                        <div className="space-y-6">
                          <h3 className="text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2">
                            <span className="h-1 w-4 bg-blue-500 rounded-full" />
                            Client Contact
                          </h3>
                          <div className="space-y-4">
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Select Client (Auto-fill)</label>
                              <select 
                                value={newProject.client || ''}
                                onChange={(e) => {
                                  const clientName = e.target.value;
                                  const selectedClient = clients.find(c => c.name === clientName);
                                  if (selectedClient) {
                                    setNewProject({
                                      ...newProject, 
                                      client: clientName,
                                      personName: selectedClient.contactPerson,
                                      email: selectedClient.email,
                                      contactNumber: selectedClient.phone
                                    });
                                  } else {
                                    setNewProject({...newProject, client: clientName});
                                  }
                                }}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                              >
                                <option value="" disabled>Choose a client</option>
                                {clients.map(client => (
                                  <option key={client.id} value={client.name}>{client.name}</option>
                                ))}
                                <option value="Other">Other / New Client</option>
                              </select>
                            </div>
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Point of Contact</label>
                              <input 
                                type="text" 
                                placeholder="Full Name"
                                value={newProject.personName || ''}
                                onChange={(e) => setNewProject({...newProject, personName: e.target.value})}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                              />
                            </div>
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Email Address</label>
                              <input 
                                type="email" 
                                placeholder="client@example.com"
                                value={newProject.email || ''}
                                onChange={(e) => setNewProject({...newProject, email: e.target.value})}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                              />
                            </div>
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Phone Number</label>
                              <input 
                                type="tel" 
                                placeholder="+1 (555) 000-0000"
                                value={newProject.contactNumber || ''}
                                onChange={(e) => setNewProject({...newProject, contactNumber: e.target.value})}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                              />
                            </div>
                          </div>
                        </div>

                        <div className="space-y-6">
                          <h3 className="text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2">
                            <span className="h-1 w-4 bg-emerald-500 rounded-full" />
                            Assigned Member
                          </h3>
                          <div className="space-y-4">
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Select Engineer</label>
                              <select 
                                value={newProject.assignedTo || ''}
                                onChange={(e) => {
                                  const selectedEng = engineers.find(eng => eng.name === e.target.value);
                                  setNewProject({
                                    ...newProject, 
                                    assignedTo: e.target.value,
                                    assignedRole: selectedEng?.role || newProject.assignedRole,
                                    assignedEmail: selectedEng?.email || newProject.assignedEmail,
                                    assignedContactNumber: selectedEng?.phone || newProject.assignedContactNumber
                                  });
                                }}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                              >
                                <option value="">Unassigned</option>
                                {engineers.map(eng => (
                                  <option key={eng.id} value={eng.name}>{eng.name} ({eng.role})</option>
                                ))}
                              </select>
                            </div>
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Internal Role</label>
                              <input 
                                type="text" 
                                placeholder="e.g. Lead Engineer"
                                value={newProject.assignedRole || ''}
                                onChange={(e) => setNewProject({...newProject, assignedRole: e.target.value})}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                              />
                            </div>
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Internal Email</label>
                              <input 
                                type="email" 
                                placeholder="alex@company.com"
                                value={newProject.assignedEmail || ''}
                                onChange={(e) => setNewProject({...newProject, assignedEmail: e.target.value})}
                                className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                    )}

                    {activeTab === 'financials' && (
                      <div className="space-y-8">
                        <div className="flex items-center justify-between">
                          <h3 className="text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2">
                            <span className="h-1 w-4 bg-primary rounded-full" />
                            Rate Configuration
                          </h3>
                          <div className="flex items-center gap-3 px-3 py-1.5 rounded-lg bg-muted/50 border border-border">
                            <span className="text-xs font-bold text-muted-foreground">Currency:</span>
                            <select 
                              value={newProject.currency || 'USD'}
                              onChange={(e) => setNewProject({...newProject, currency: e.target.value})}
                              className="bg-card/50 border border-border/50 rounded px-1.5 py-0.5 text-xs font-bold focus:outline-none cursor-pointer text-foreground [&>option]:bg-card [&>option]:text-foreground"
                            >
                              {!currencies.some(c => c.code === 'USD') && <option value="USD">USD</option>}
                              {!currencies.some(c => c.code === 'EUR') && <option value="EUR">EUR</option>}
                              {!currencies.some(c => c.code === 'GBP') && <option value="GBP">GBP</option>}
                              {!currencies.some(c => c.code === 'CAD') && <option value="CAD">CAD</option>}
                              {currencies.map(curr => (
                                <option key={curr.code} value={curr.code}>{curr.code}</option>
                              ))}
                            </select>
                          </div>
                        </div>

                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
                          {/* Client Side Rates */}
                          <div className="space-y-6">
                            <div className="p-4 rounded-2xl bg-blue-500/5 border border-blue-500/10">
                              <h4 className="text-xs font-bold uppercase tracking-wider text-blue-500 mb-4 flex items-center gap-2">
                                <Building2 size={14} />
                                Client Billing Rates
                              </h4>
                              <div className="grid grid-cols-2 gap-4">
                                {[
                                  { id: 'clientHourlyRate', label: 'Hourly' },
                                  { id: 'clientHalfDayRate', label: 'Half-Day' },
                                  { id: 'clientFullDayRate', label: 'Full-Day' },
                                  { id: 'clientMonthlyRate', label: 'Monthly' },
                                  { id: 'clientTravelCost', label: 'Travel' },
                                  { id: 'clientMaterialCost', label: 'Materials' },
                                ].map((rate) => (
                                  <div key={rate.id} className="space-y-1.5">
                                    <label className="text-[10px] font-bold uppercase text-muted-foreground">{rate.label}</label>
                                    <div className="relative">
                                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs">
                                        {getSymbol(newProject.currency)}
                                      </span>
                                      <input 
                                        type="number" 
                                        value={(newProject as any)[rate.id] || 0}
                                        onChange={(e) => setNewProject({...newProject, [rate.id]: parseFloat(e.target.value) || 0})}
                                        className="h-10 w-full rounded-xl border border-border bg-background pl-8 pr-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                                      />
                                    </div>
                                  </div>
                                ))}
                              </div>
                                  <div className="mt-4 pt-4 border-t border-blue-500/10">
                                    <div className="flex items-center justify-between">
                                      <span className="text-sm font-bold text-blue-500">Total Client Value</span>
                                      <span className="text-2xl font-black text-blue-600">
                                        {getSymbol(newProject.currency)}
                                        {newProject.clientTotalAmount?.toLocaleString()}
                                      </span>
                                    </div>
                                  </div>
                            </div>
                          </div>

                          {/* Engineer Side Rates */}
                          <div className="space-y-6">
                            <div className="p-4 rounded-2xl bg-emerald-500/5 border border-emerald-500/10">
                              <h4 className="text-xs font-bold uppercase tracking-wider text-emerald-500 mb-4 flex items-center gap-2">
                                <UserCheck size={14} />
                                Engineer Payout Rates
                              </h4>
                              <div className="grid grid-cols-2 gap-4">
                                {[
                                  { id: 'hourlyRate', label: 'Hourly' },
                                  { id: 'halfDayRate', label: 'Half-Day' },
                                  { id: 'fullDayRate', label: 'Full-Day' },
                                  { id: 'monthlyRate', label: 'Monthly' },
                                  { id: 'travelCost', label: 'Travel' },
                                  { id: 'materialCost', label: 'Materials' },
                                ].map((rate) => (
                                  <div key={rate.id} className="space-y-1.5">
                                    <label className="text-[10px] font-bold uppercase text-muted-foreground">{rate.label}</label>
                                    <div className="relative">
                                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs">
                                        {getSymbol(newProject.currency)}
                                      </span>
                                      <input 
                                        type="number" 
                                        value={(newProject as any)[rate.id] || 0}
                                        onChange={(e) => setNewProject({...newProject, [rate.id]: parseFloat(e.target.value) || 0})}
                                        className="h-10 w-full rounded-xl border border-border bg-background pl-8 pr-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                                      />
                                    </div>
                                  </div>
                                ))}
                              </div>
                              <div className="mt-6 pt-4 border-t border-emerald-500/10">
                                <div className="flex items-center justify-between">
                                  <span className="text-sm font-bold text-emerald-500">Total Engineer Cost</span>
                                  <span className="text-xl font-bold text-emerald-500">
                                    {getSymbol(newProject.currency)}
                                    {newProject.totalAmount?.toLocaleString()}
                                  </span>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    )}

                    {activeTab === 'execution' && (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-12">
                        <div className="space-y-6">
                          <h3 className="text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2">
                            <span className="h-1 w-4 bg-orange-500 rounded-full" />
                            Work Schedule
                          </h3>
                          <div className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                              <div className="space-y-2">
                                <label className="text-sm font-semibold">Time In</label>
                                <input 
                                  type="time" 
                                  value={newProject.timeIn || ''}
                                  onChange={(e) => setNewProject({...newProject, timeIn: e.target.value})}
                                  className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                                />
                              </div>
                              <div className="space-y-2">
                                <label className="text-sm font-semibold">Time Out</label>
                                <input 
                                  type="time" 
                                  value={newProject.timeOut || ''}
                                  onChange={(e) => setNewProject({...newProject, timeOut: e.target.value})}
                                  className="h-11 w-full rounded-xl border border-border bg-background px-4 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-semibold">Total Time</label>
                                <input 
                                  type="text" 
                                  placeholder="e.g. 8h 30m"
                                  value={newProject.totalTime || ''}
                                  readOnly
                                  className="h-11 w-full rounded-xl border border-border bg-muted/50 px-4 text-sm font-bold text-primary cursor-not-allowed"
                                />
                              </div>
                              <div className="space-y-2">
                                <label className="text-sm font-semibold">Team Size</label>
                                <input 
                                  type="number" 
                                  min="1"
                                  value={newProject.team || 1}
                                  onChange={(e) => setNewProject({...newProject, team: parseInt(e.target.value) || 1})}
                                  className="h-11 w-full rounded-xl border border-border bg-background px-4 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-semibold">Total Days (for Monthly Assignment)</label>
                                <input 
                                  type="number" 
                                  min="0"
                                  placeholder="e.g. 22"
                                  value={newProject.totalDays || ''}
                                  onChange={(e) => setNewProject({...newProject, totalDays: parseInt(e.target.value) || 0})}
                                  className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                                />
                              </div>
                              <div className="space-y-2">
                                <label className="text-sm font-semibold">Completed Date</label>
                                <input 
                                  type="date" 
                                  value={newProject.completedDate || ''}
                                  onChange={(e) => setNewProject({...newProject, completedDate: e.target.value})}
                                  className="h-11 w-full rounded-xl border border-border bg-background px-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                                />
                              </div>
                            </div>
                          </div>
                        </div>

                        <div className="space-y-6">
                          <h3 className="text-sm font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2">
                            <span className="h-1 w-4 bg-primary rounded-full" />
                            Project Scope & Attachments
                          </h3>
                          <div className="space-y-4">
                            <div className="space-y-2">
                              <label className="text-sm font-semibold">Description & Requirements</label>
                              <textarea 
                                placeholder="Outline the key deliverables and constraints..."
                                value={newProject.description || ''}
                                onChange={(e) => setNewProject({...newProject, description: e.target.value})}
                                className="min-h-[120px] w-full rounded-xl border border-border bg-background px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 resize-none"
                              />
                            </div>
                            
                            <div className="space-y-3">
                              <div className="flex items-center justify-between">
                                <label className="text-sm font-semibold flex items-center gap-2">
                                  <Paperclip size={16} className="text-primary" />
                                  Attachments
                                </label>
                                <label className="cursor-pointer flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary/10 text-primary text-xs font-bold hover:bg-primary/20 transition-all">
                                  <Upload size={14} />
                                  Upload File
                                  <input 
                                    type="file" 
                                    multiple 
                                    className="hidden" 
                                    onChange={handleFileUpload}
                                  />
                                </label>
                              </div>
                              
                              <div className="space-y-2 max-h-[150px] overflow-y-auto pr-2 custom-scrollbar">
                                {newProject.files && newProject.files.length > 0 ? (
                                  newProject.files.map((file, idx) => (
                                    <div key={idx} className="flex items-center justify-between p-2 rounded-lg bg-muted/30 border border-border group">
                                      <div className="flex items-center gap-3 overflow-hidden">
                                        <div className="p-1.5 rounded bg-background border border-border text-muted-foreground">
                                          <File size={14} />
                                        </div>
                                        <div className="flex flex-col overflow-hidden">
                                          <span className="text-xs font-medium truncate">{file.name}</span>
                                          <span className="text-[10px] text-muted-foreground">{file.size}</span>
                                        </div>
                                      </div>
                                      <button 
                                        type="button"
                                        onClick={() => removeFile(idx)}
                                        className="p-1 text-muted-foreground hover:text-destructive transition-colors opacity-0 group-hover:opacity-100"
                                      >
                                        <Trash2 size={14} />
                                      </button>
                                    </div>
                                  ))
                                ) : (
                                  <div className="flex flex-col items-center justify-center py-6 border-2 border-dashed border-border rounded-xl bg-muted/10">
                                    <Upload size={24} className="text-muted-foreground/30 mb-2" />
                                    <p className="text-xs text-muted-foreground">No files uploaded yet</p>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    )}
                  </motion.div>
                </AnimatePresence>
              </form>

              {/* Modal Footer */}
              <div className="p-6 border-t border-border bg-muted/30 flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div className="flex -space-x-2">
                    {['general', 'contacts', 'financials', 'execution'].map((tab, idx) => (
                      <div 
                        key={tab}
                        className={cn(
                          "h-2 w-8 rounded-full transition-all duration-300",
                          activeTab === tab ? "bg-primary w-12" : "bg-muted-foreground/20"
                        )}
                      />
                    ))}
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <button 
                    type="button"
                    onClick={() => {
                      setIsModalOpen(false);
                      setEditingProjectId(null);
                    }}
                    className="px-6 py-2.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
                  >
                    Cancel
                  </button>
                  <button 
                    onClick={handleCreateProject}
                    disabled={isSubmitting}
                    className="px-8 py-2.5 bg-primary text-primary-foreground rounded-xl text-sm font-bold hover:bg-primary/90 transition-all shadow-lg shadow-primary/20 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                  >
                    {isSubmitting ? (
                      <>
                        <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />
                        Processing...
                      </>
                    ) : (
                      editingProjectId ? 'Update Project' : 'Launch Project'
                    )}
                  </button>
                </div>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      <div className="flex flex-wrap items-center gap-4">
        <div className="relative flex-1 min-w-[300px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
          <input
            type="text"
            placeholder="Search projects by name, client or ID..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="h-10 w-full rounded-lg border border-border bg-card pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
          />
        </div>
        
        <div className="flex items-center gap-2 bg-card border border-border rounded-lg px-3 py-1.5 shadow-sm">
          <span className="text-xs font-medium text-muted-foreground">View All Projects</span>
          <button
            onClick={() => setShowAllProjects(!showAllProjects)}
            className={cn(
              "relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none",
              showAllProjects ? "bg-primary" : "bg-muted"
            )}
          >
            <span
              className={cn(
                "inline-block h-3.5 w-3.5 transform rounded-full bg-background shadow-sm transition-transform",
                showAllProjects ? "translate-x-5" : "translate-x-1"
              )}
            />
          </button>
        </div>

        <div className="relative" ref={filterRef}>
          <button 
            onClick={() => setIsFilterOpen(!isFilterOpen)}
            className={cn(
              "flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium transition-colors hover:bg-accent",
              (statusFilter !== 'All' || filterClient !== 'All' || filterEngineer !== 'All') && "border-primary text-primary"
            )}
          >
            <Filter size={18} />
            Filters
            {(statusFilter !== 'All' || filterClient !== 'All' || filterEngineer !== 'All') && (
              <span className="flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground">
                {[statusFilter, filterClient, filterEngineer].filter(f => f !== 'All').length}
              </span>
            )}
          </button>

          {isFilterOpen && (
            <div className="absolute right-0 mt-2 z-50 w-72 rounded-xl border border-border bg-card p-4 shadow-lg animate-in fade-in slide-in-from-top-2 duration-200">
              <div className="flex items-center justify-between mb-4">
                <h4 className="font-bold text-sm">Filter Projects</h4>
                <button 
                  onClick={() => {
                    setStatusFilter('All');
                    setFilterClient('All');
                    setFilterEngineer('All');
                  }}
                  className="text-[10px] font-bold uppercase tracking-wider text-primary hover:underline"
                >
                  Reset
                </button>
              </div>
              
              <div className="space-y-4">
                <div className="space-y-2">
                  <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Status</label>
                  <select 
                    value={statusFilter}
                    onChange={(e) => setStatusFilter(e.target.value)}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="All">All Statuses</option>
                    <option value="Planning">Planning</option>
                    <option value="Scheduled">Scheduled</option>
                    <option value="Work In Progress">Work In Progress</option>
                    <option value="Completed">Completed</option>
                    <option value="On Hold">On Hold</option>
                    <option value="Cancelled">Cancelled</option>
                    <option value="Rejected">Rejected</option>
                  </select>
                </div>

                <div className="space-y-2">
                  <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Client</label>
                  <select 
                    value={filterClient}
                    onChange={(e) => setFilterClient(e.target.value)}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="All">All Clients</option>
                    {clients.map(client => (
                      <option key={client.id} value={client.name}>{client.name}</option>
                    ))}
                  </select>
                </div>

                <div className="space-y-2">
                  <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Assigned To</label>
                  <select 
                    value={filterEngineer}
                    onChange={(e) => setFilterEngineer(e.target.value)}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="All">All Engineers</option>
                    {engineers.map(eng => (
                      <option key={eng.id} value={eng.name}>{eng.name}</option>
                    ))}
                  </select>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {showAllProjects ? (
        <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead className="bg-muted/50 border-b border-border">
                <tr>
                  <th className="px-4 py-3 font-medium">Project ID</th>
                  <th className="px-4 py-3 font-medium">Project Name</th>
                  <th className="px-4 py-3 font-medium">Client</th>
                  <th className="px-4 py-3 font-medium">Project Status</th>
                  <th className="px-4 py-3 font-medium text-center">Team</th>
                  <th className="px-4 py-3 font-medium">Assign</th>
                  <th className="px-4 py-3 font-medium">Role</th>
                  <th className="px-4 py-3 font-medium">Time</th>
                  <th className="px-4 py-3 font-medium">Deadline</th>
                  <th className="px-4 py-3 font-medium">Completed</th>
                  <th className="px-4 py-3 font-medium text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filteredProjects.map((project) => (
                  <tr key={project.id} className="hover:bg-accent/30 transition-colors group">
                    <td className="px-4 py-4 font-mono text-xs text-muted-foreground">{project.id}</td>
                    <td className="px-4 py-4">
                      <p className="font-medium group-hover:text-primary transition-colors">{project.name}</p>
                    </td>
                    <td className="px-4 py-4 text-muted-foreground">{project.client}</td>
                    <td className="px-4 py-4">
                      <span className={cn(
                        "rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider",
                        project.status === 'In Progress' ? "bg-blue-500/10 text-blue-500" :
                        project.status === 'Completed' ? "bg-green-500/10 text-green-500" :
                        project.status === 'Accepted' ? "bg-emerald-500/10 text-emerald-500" :
                        project.status === 'Rejected' ? "bg-rose-500/10 text-rose-500" :
                        "bg-yellow-500/10 text-yellow-500"
                      )}>
                        {project.status}
                      </span>
                    </td>
                    <td className="px-4 py-4 text-center text-muted-foreground">{project.team}</td>
                    <td className="px-4 py-4">
                      <div className="flex items-center gap-2">
                        <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold text-[10px]">
                          {project.assignedTo ? project.assignedTo.split(' ').map((n: string) => n[0]).join('') : '?'}
                        </div>
                        <span className="text-xs text-muted-foreground">{project.assignedTo || 'Unassigned'}</span>
                      </div>
                    </td>
                    <td className="px-4 py-4 text-xs text-muted-foreground">{project.assignedRole || '-'}</td>
                    <td className="px-4 py-4">
                      {project.totalTime ? (
                        <div className="flex flex-col">
                          <span className="text-xs font-bold text-primary">{project.totalTime}</span>
                          <span className="text-[10px] text-muted-foreground">{project.timeIn} - {project.timeOut}</span>
                        </div>
                      ) : (
                        <span className="text-xs text-muted-foreground italic">Not set</span>
                      )}
                    </td>
                    <td className="px-4 py-4 text-muted-foreground">{formatDate(project.deadline)}</td>
                    <td className="px-4 py-4 text-muted-foreground">{formatDate(project.completedDate)}</td>
                    <td className="px-4 py-4 text-right">
                      <div className="flex items-center justify-end gap-2">
                        {hasPermission('projects.edit') && (
                          <button 
                            onClick={() => handleEditProject(project)}
                            className="p-1 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                            title="Edit Project"
                          >
                            <FileText size={16} />
                          </button>
                        )}
                        {hasPermission('projects.delete') && (
                          <button 
                            disabled={isSubmitting}
                            onClick={() => handleDeleteProject(project.id)}
                            className="p-1 hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50"
                            title="Delete Project"
                          >
                            <Trash2 size={16} />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
                {filteredProjects.length === 0 && (
                  <tr>
                    <td colSpan={7} className="py-12 text-center text-muted-foreground">
                      No projects found matching your search.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      ) : (
        <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
          {filteredProjects.map((project) => (
            <div key={project.id} className="group rounded-xl border border-border bg-card p-6 shadow-sm transition-all hover:border-primary/50 hover:shadow-md">
            <div className="flex items-center justify-between mb-4">
              <span className={cn(
                "rounded-full px-2 py-1 text-[10px] font-bold uppercase tracking-wider",
                project.status === 'In Progress' ? "bg-blue-500/10 text-blue-500" :
                project.status === 'Completed' ? "bg-green-500/10 text-green-500" :
                project.status === 'Accepted' ? "bg-emerald-500/10 text-emerald-500" :
                project.status === 'Rejected' ? "bg-rose-500/10 text-rose-500" :
                "bg-yellow-500/10 text-yellow-500"
              )}>
                {project.status}
              </span>
              <div className="flex items-center gap-1">
                {hasPermission('projects.edit') && (
                  <div className="relative">
                    <button 
                      onClick={() => setActiveDropdown(activeDropdown === project.id ? null : project.id)}
                      className="flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium hover:bg-accent text-muted-foreground transition-colors"
                      title="Change Project Status"
                    >
                      Project Status
                      <ChevronDown size={14} className={cn("transition-transform", activeDropdown === project.id && "rotate-180")} />
                    </button>

                    {activeDropdown === project.id && (
                      <>
                        <div 
                          className="fixed inset-0 z-10" 
                          onClick={() => setActiveDropdown(null)} 
                        />
                        <div className="absolute right-0 top-full mt-1 w-32 rounded-lg border border-border bg-card p-1 shadow-lg z-20 animate-in fade-in zoom-in duration-200">
                          <button
                            disabled={isSubmitting}
                            onClick={() => handleUpdateStatus(project.id, 'Accepted')}
                            className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs hover:bg-emerald-500/10 hover:text-emerald-500 transition-colors disabled:opacity-50"
                          >
                            <Check size={14} />
                            Accept
                          </button>
                          <button
                            disabled={isSubmitting}
                            onClick={() => handleUpdateStatus(project.id, 'Rejected')}
                            className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs hover:bg-rose-500/10 hover:text-rose-500 transition-colors disabled:opacity-50"
                          >
                            <X size={14} />
                            Reject
                          </button>
                        </div>
                      </>
                    )}
                  </div>
                )}
                {hasPermission('projects.edit') && (
                  <button 
                    onClick={() => handleEditProject(project)}
                    className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
                    title="Edit Project"
                  >
                    <FileText size={16} />
                  </button>
                )}
                {hasPermission('projects.delete') && (
                  <button 
                    disabled={isSubmitting}
                    onClick={() => handleDeleteProject(project.id)}
                    className="rounded-md p-1 hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50"
                    title="Delete Project"
                  >
                    <Trash2 size={16} />
                  </button>
                )}
              </div>
            </div>

            <div className="flex items-start justify-between mb-1">
              <h3 className="text-lg font-bold group-hover:text-primary transition-colors leading-tight">{project.name}</h3>
              <span className="text-[10px] font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded shrink-0 ml-2">{project.id}</span>
            </div>
            <p className="text-sm text-muted-foreground mb-1">Client: {project.client}</p>
            
            <div className="flex items-center gap-2 mb-2">
              <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold text-[10px]">
                {project.assignedTo ? project.assignedTo.split(' ').map((n: string) => n[0]).join('') : '?'}
              </div>
              <div className="flex flex-col">
                <span className="text-xs text-muted-foreground">Assigned to: <span className="font-medium text-foreground">{project.assignedTo || 'Unassigned'}</span></span>
                {project.assignedRole && <span className="text-[10px] text-primary font-medium">{project.assignedRole}</span>}
              </div>
            </div>

            <div className="space-y-4">
              {/* Tasks Summary */}
              <div className="py-3 border-t border-border/50">
                <div className="flex items-center justify-between mb-2">
                  <h4 className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">Tasks</h4>
                  <span className="text-[10px] font-medium text-primary">
                    {tasks.filter(t => t.projectId === project.id && t.status === 'Completed').length}/{tasks.filter(t => t.projectId === project.id).length} Done
                  </span>
                </div>
                <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                  <div 
                    className="h-full bg-primary transition-all duration-500" 
                    style={{ 
                      width: `${tasks.filter(t => t.projectId === project.id).length > 0 
                        ? (tasks.filter(t => t.projectId === project.id && t.status === 'Completed').length / tasks.filter(t => t.projectId === project.id).length) * 100 
                        : 0}%` 
                    }}
                  />
                </div>
              </div>

              {(project.hourlyRate > 0 || project.halfDayRate > 0 || project.fullDayRate > 0 || project.monthlyRate > 0 || project.travelCost > 0 || project.materialCost > 0) && (
                <div className="grid grid-cols-2 gap-y-1.5 gap-x-4 py-3 border-t border-border/50">
                  {project.hourlyRate > 0 && (
                    <div className="flex items-center justify-between text-[10px]">
                      <span className="text-muted-foreground uppercase font-semibold">Hourly</span>
                      <span className="font-bold text-primary">
                        {getSymbol(project.currency)}{project.hourlyRate}
                      </span>
                    </div>
                  )}
                  {project.halfDayRate > 0 && (
                    <div className="flex items-center justify-between text-[10px]">
                      <span className="text-muted-foreground uppercase font-semibold">Half-Day</span>
                      <span className="font-bold text-primary">
                        {getSymbol(project.currency)}{project.halfDayRate}
                      </span>
                    </div>
                  )}
                  {project.fullDayRate > 0 && (
                    <div className="flex items-center justify-between text-[10px]">
                      <span className="text-muted-foreground uppercase font-semibold">Full-Day</span>
                      <span className="font-bold text-primary">
                        {getSymbol(project.currency)}{project.fullDayRate}
                      </span>
                    </div>
                  )}
                  {project.monthlyRate > 0 && (
                    <div className="flex items-center justify-between text-[10px]">
                      <span className="text-muted-foreground uppercase font-semibold">Monthly</span>
                      <span className="font-bold text-primary">
                        {getSymbol(project.currency)}{project.monthlyRate}
                      </span>
                    </div>
                  )}
                  {project.travelCost > 0 && (
                    <div className="flex items-center justify-between text-[10px]">
                      <span className="text-muted-foreground uppercase font-semibold">Travel</span>
                      <span className="font-bold text-primary">
                        {getSymbol(project.currency)}{project.travelCost}
                      </span>
                    </div>
                  )}
                  {project.materialCost > 0 && (
                    <div className="flex items-center justify-between text-[10px]">
                      <span className="text-muted-foreground uppercase font-semibold">Material</span>
                      <span className="font-bold text-primary">
                        {getSymbol(project.currency)}{project.materialCost}
                      </span>
                    </div>
                  )}
                  {project.totalAmount > 0 && (
                    <div className="flex items-center justify-between text-[10px] pt-1 border-t border-border/30 mt-1 col-span-2">
                      <span className="text-primary uppercase font-bold">Total Amount</span>
                      <span className="font-extrabold text-primary text-xs">
                        {getSymbol(project.currency)}{project.totalAmount.toLocaleString()}
                      </span>
                    </div>
                  )}
                </div>
              )}

              <div className="flex items-center justify-between pt-2 border-t border-border">
                <div className="flex items-center gap-4">
                  <div className="flex items-center gap-1 text-xs text-muted-foreground">
                    <Users size={14} />
                    {project.team}
                  </div>
                  <div className="flex items-center gap-1 text-xs text-muted-foreground">
                    <Calendar size={14} />
                    {formatDate(project.deadline)}
                  </div>
                  {project.completedDate && (
                    <div className="flex items-center gap-1 text-xs text-emerald-500 font-medium">
                      <CheckCircle2 size={14} />
                      {formatDate(project.completedDate)}
                    </div>
                  )}
                </div>
                {project.totalTime && (
                  <div className="flex items-center gap-1 text-xs font-bold text-primary">
                    <Timer size={14} />
                    {project.totalTime}
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
        {filteredProjects.length === 0 && (
          <div className="col-span-full py-12 text-center text-muted-foreground">
            No projects found matching your search.
          </div>
        )}
      </div>
    )}
    </div>
  );
}

function KPICard({ title, value, icon: Icon, colorClass }: { title: string, value: string | number, icon: any, colorClass: string }) {
  return (
    <motion.div 
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="rounded-xl border border-border bg-card p-6 shadow-sm hover:shadow-md transition-all"
    >
      <div className="flex items-center gap-4">
        <div className={cn("p-3 rounded-lg", colorClass)}>
          <Icon size={24} />
        </div>
        <div>
          <p className="text-sm font-medium text-muted-foreground">{title}</p>
          <h3 className="text-2xl font-bold tracking-tight">{value}</h3>
        </div>
      </div>
    </motion.div>
  );
}
