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

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

export function Tasks() {
  const { projects: allProjects, updateProject, deleteProject, tasks: allTasks, addTask, updateTask, deleteTask, clients, engineers, currencies } = useApp();
  const { profile, hasPermission } = useAuth();

  const canViewAll = useMemo(() => {
    if (!profile) return false;
    return hasPermission('tasks.view_all') || 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 tasks = useMemo(() => {
    if (canViewAll) return allTasks;
    return allTasks.filter(t => t.assignee === profile?.name || t.assignee === profile?.email);
  }, [allTasks, canViewAll, profile]);
  
  const getSymbol = (code?: string) => {
    if (!code) return '$';
    const c = currencies.find(curr => curr.code === code);
    return c ? c.symbol : '$';
  };
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    const create = searchParams.get('create');
    if (create === 'true') {
      setIsTaskModalOpen(true);
      const newParams = new URLSearchParams(searchParams);
      newParams.delete('create');
      setSearchParams(newParams, { replace: true });
    }
  }, [searchParams, setSearchParams]);
  const [activeTab, setActiveTab] = useState<'timesheets' | 'tasks'>('timesheets');
  const [modalTab, setModalTab] = useState<'general' | 'contacts' | 'financials' | 'execution'>('general');
  const [showAllProjects, setShowAllProjects] = useState(false);
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [isTaskFilterOpen, setIsTaskFilterOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [statusFilter, setStatusFilter] = useState<string>('All');
  const [taskStatusFilter, setTaskStatusFilter] = useState<string>('All');
  const [clientFilter, setClientFilter] = useState<string>('All');
  const [taskProjectFilter, setTaskProjectFilter] = useState<string>('All');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingProjectId, setEditingProjectId] = useState<string | null>(null);
  const [newProject, setNewProject] = useState<Partial<Project>>({
    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: '',
    files: []
  });

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [projectToDelete, setProjectToDelete] = useState<Project | null>(null);

  const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);
  const [editingTaskId, setEditingTaskId] = useState<string | null>(null);
  const [newTask, setNewTask] = useState<Partial<Task>>({
    title: '',
    projectId: '',
    status: 'To Do',
    dueDate: new Date().toISOString().split('T')[0],
    assignee: '',
    timeLogged: '',
    approvalStatus: 'Pending'
  });

  const handleDeleteProjectClick = (project: Project) => {
    setProjectToDelete(project);
    setIsDeleteModalOpen(true);
  };

  const confirmDelete = async () => {
    if (projectToDelete && !isSubmitting) {
      setIsSubmitting(true);
      try {
        await deleteProject(projectToDelete.id);
        toast.success(`Project and associated data deleted successfully`);
        setIsDeleteModalOpen(false);
        setProjectToDelete(null);
      } catch (error) {
        console.error('Delete project error:', error);
      } finally {
        setIsSubmitting(false);
      }
    }
  };

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

  const handleUpdateProject = async (e: React.FormEvent) => {
    e.preventDefault();
    if (editingProjectId && !isSubmitting) {
      setIsSubmitting(true);
      try {
        await updateProject(editingProjectId, newProject);
        toast.success('Project data updated successfully');
        setIsModalOpen(false);
        setEditingProjectId(null);
      } catch (error) {
        console.error('Update project error:', error);
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  const handleSaveTask = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;
    if (!newTask.title || !newTask.projectId) {
      toast.error('Please fill in all required fields');
      return;
    }

    setIsSubmitting(true);
    try {
      if (editingTaskId) {
        await updateTask(editingTaskId, newTask);
        toast.success('Task updated successfully');
      } else {
        await addTask({
          ...newTask,
          id: `TASK-${Date.now()}`
        } as Task);
        toast.success('Task created successfully');
      }
      setIsTaskModalOpen(false);
      setEditingTaskId(null);
      setNewTask({
        title: '',
        projectId: '',
        status: 'To Do',
        dueDate: new Date().toISOString().split('T')[0],
        approvalStatus: 'Pending',
        timeLogged: ''
      });
    } catch (error) {
      console.error('Task save error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleExportCSV = () => {
    const allTasks = projects.flatMap(p => p.tasks || []);
    if (allTasks.length === 0) {
      toast.error('No tasks to export');
      return;
    }

    const headers = ['ID', 'Title', 'Project', 'Status', 'Due Date', 'Assignee', 'Time Logged'];
    const csvRows = [
      headers.join(','),
      ...allTasks.map(t => [
        `"${t.id}"`,
        `"${t.title}"`,
        `"${projects.find(p => p.id === t.projectId)?.name || t.projectId}"`,
        `"${t.status}"`,
        `"${t.dueDate}"`,
        `"${t.assignee || ''}"`,
        `"${t.timeLogged || ''}"`
      ].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', `tasks_export_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success('Tasks 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 newTasks: 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 projectName = clean(matches[2]);
          const project = projects.find(p => p.name === projectName || p.id === projectName);
          
          if (!project) continue;

          const task = {
            id: clean(matches[0]),
            title: clean(matches[1]),
            projectId: project.id,
            status: clean(matches[3]) as any,
            dueDate: clean(matches[4]),
            assignee: clean(matches[5]),
            timeLogged: clean(matches[6]) || '',
            approvalStatus: 'Pending'
          };
          newTasks.push(task);
        }

        if (newTasks.length === 0) {
          toast.error('No valid tasks found (ensure project names match)');
          return;
        }

        let importedCount = 0;
        for (const task of newTasks) {
          const project = projects.find(p => p.id === task.projectId);
          if (project) {
            const existingTasks = project.tasks || [];
            if (!existingTasks.some(t => t.id === task.id)) {
              await updateProject(project.id, {
                tasks: [...existingTasks, task]
              });
              importedCount++;
            }
          }
        }
        
        if (importedCount === 0) {
          toast.info('All tasks in CSV already exist');
        } else {
          toast.success(`Successfully imported ${importedCount} new tasks`);
        }
      } 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 handleEditTask = (task: Task) => {
    const project = projects.find(p => p.id === task.projectId);
    setEditingTaskId(task.id);
    setNewTask({ 
      ...task,
      timeLogged: project?.totalTime || task.timeLogged
    });
    setIsTaskModalOpen(true);
  };

  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))
    }));
  }, [
    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 getProjectForTask = (projectId?: string) => {
    return projects.find(p => p.id === projectId);
  };

  const calculateTotalAmount = (project: Project) => {
    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(project.totalTime);
    const hourlyTotal = (project.hourlyRate || 0) * hours;
    
    return hourlyTotal + (project.travelCost || 0) + (project.materialCost || 0) + 
           (project.halfDayRate || 0) + (project.fullDayRate || 0) + (project.monthlyRate || 0);
  };

  const calculateClientTotalAmount = (project: Project) => {
    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(project.totalTime);
    const hourlyTotal = (project.clientHourlyRate || 0) * hours;
    
    return hourlyTotal + (project.clientTravelCost || 0) + (project.clientMaterialCost || 0) + 
           (project.clientHalfDayRate || 0) + (project.clientFullDayRate || 0) + (project.clientMonthlyRate || 0);
  };

  const formatCurrency = (amount: number, currency?: string) => {
    const symbol = currency === 'Euro' ? '€' : currency === 'GBP' ? '£' : '$';
    return `${symbol}${amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  };

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

  const filteredProjects = projects.filter(prj => {
    const matchesSearch = prj.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      prj.client.toLowerCase().includes(searchQuery.toLowerCase()) ||
      prj.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (prj.assignedTo && prj.assignedTo.toLowerCase().includes(searchQuery.toLowerCase()));
    
    const matchesStatus = statusFilter === 'All' || prj.status === statusFilter;
    const matchesClient = clientFilter === 'All' || prj.client === clientFilter;

    if (showAllProjects) return matchesSearch && matchesStatus && matchesClient;
    
    const inactiveStatuses = ['Completed', 'Rejected', 'Cancelled'];
    return matchesSearch && matchesStatus && matchesClient && !inactiveStatuses.includes(prj.status);
  });

  const filteredTasks = tasks.filter(task => {
    const project = projects.find(p => p.id === task.projectId);
    const matchesSearch = task.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (project && project.name.toLowerCase().includes(searchQuery.toLowerCase())) ||
      (task.assignee && task.assignee.toLowerCase().includes(searchQuery.toLowerCase()));
    
    const matchesStatus = taskStatusFilter === 'All' || task.status === taskStatusFilter;
    const matchesProject = taskProjectFilter === 'All' || task.projectId === taskProjectFilter;

    return matchesSearch && matchesStatus && matchesProject;
  });

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

  return (
    <div className="space-y-6">
      {/* Edit Project Modal (Local to Tasks) */}
      <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">
                    <Edit2 size={24} />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold tracking-tight">Edit Project Data</h2>
                    <p className="text-sm text-muted-foreground">Update details for project associated with this task.</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={() => setModalTab(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",
                      modalTab === 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={handleUpdateProject} className="flex-1 overflow-y-auto p-8 space-y-8">
                <AnimatePresence mode="wait">
                  <motion.div
                    key={modalTab}
                    initial={{ opacity: 0, x: 10 }}
                    animate={{ opacity: 1, x: 0 }}
                    exit={{ opacity: 0, x: -10 }}
                    transition={{ duration: 0.2 }}
                    className="space-y-8"
                  >
                    {modalTab === '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) => {
                                  const newStatus = e.target.value;
                                  const updates: any = { status: newStatus };
                                  if (['Completed', 'Accepted', 'Rejected'].includes(newStatus) && !newProject.completedDate) {
                                    updates.completedDate = new Date().toISOString().split('T')[0];
                                  }
                                  setNewProject({...newProject, ...updates});
                                }}
                                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>
                                <option value="Accepted">Accepted</option>
                                <option value="Rejected">Rejected</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">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 className="space-y-2">
                                <label className="text-sm font-semibold">Completed Date</label>
                                <div className="space-y-1">
                                  <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"
                                  />
                                  {newProject.completedDate && (
                                    <p className="text-[10px] text-primary font-medium px-1">
                                      {formatDate(newProject.completedDate)}
                                    </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>
                    )}

                    {modalTab === '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>
                    )}

                    {modalTab === '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-transparent text-xs font-bold focus:outline-none cursor-pointer"
                            >
                              {!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-6 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-xl font-bold text-blue-500">
                                    {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>
                    )}

                    {modalTab === '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",
                          modalTab === 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"
                  >
                    Discard
                  </button>
                  <button 
                    onClick={handleUpdateProject}
                    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"
                  >
                    Save Changes
                  </button>
                </div>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Task Modal */}
      {isTaskModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-2xl border border-border bg-card shadow-2xl animate-in fade-in zoom-in duration-200 overflow-hidden">
            <div className="bg-primary/5 border-b border-border p-6 flex items-center justify-between">
              <h2 className="text-xl font-bold">{editingTaskId ? 'Edit Task' : 'Add New Task'}</h2>
              <button 
                onClick={() => {
                  setIsTaskModalOpen(false);
                  setEditingTaskId(null);
                }}
                className="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleSaveTask} className="p-6 space-y-4">
              <div className="space-y-2">
                <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Task Title *</label>
                <input 
                  type="text" 
                  placeholder="e.g. Design UI Mockups"
                  value={newTask.title || ''}
                  onChange={(e) => setNewTask({...newTask, title: e.target.value})}
                  className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all"
                  required
                />
              </div>

              <div className="space-y-2">
                <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Project *</label>
                <div className="relative">
                  <select 
                    value={newTask.projectId || ''}
                    onChange={(e) => {
                      const pId = e.target.value;
                      const project = projects.find(p => p.id === pId);
                      setNewTask({
                        ...newTask, 
                        projectId: pId,
                        timeLogged: project?.totalTime || newTask.timeLogged
                      });
                    }}
                    className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all appearance-none cursor-pointer"
                    required
                  >
                    <option value="" disabled>Select a project</option>
                    {projects.map(p => (
                      <option key={p.id} value={p.id}>{p.name}</option>
                    ))}
                  </select>
                  <ChevronRight className="absolute right-4 top-1/2 -translate-y-1/2 rotate-90 text-muted-foreground pointer-events-none" size={14} />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Due Date *</label>
                  <input 
                    type="date" 
                    value={newTask.dueDate || ''}
                    onChange={(e) => setNewTask({...newTask, dueDate: e.target.value})}
                    className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Status</label>
                  <div className="relative">
                    <select 
                      value={newTask.status || 'To Do'}
                      onChange={(e) => setNewTask({...newTask, status: e.target.value as any})}
                      className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all appearance-none cursor-pointer"
                    >
                      <option value="To Do">To Do</option>
                      <option value="In Progress">In Progress</option>
                      <option value="Completed">Completed</option>
                    </select>
                    <ChevronRight className="absolute right-4 top-1/2 -translate-y-1/2 rotate-90 text-muted-foreground pointer-events-none" size={14} />
                  </div>
                </div>
              </div>

              <div className="space-y-2">
                <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Assignee</label>
                <div className="relative">
                  <User className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground" size={14} />
                  <select 
                    value={newTask.assignee || ''}
                    onChange={(e) => setNewTask({...newTask, assignee: e.target.value})}
                    className="h-11 w-full rounded-xl border border-border bg-muted/20 pl-11 pr-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all appearance-none cursor-pointer"
                  >
                    <option value="">Unassigned</option>
                    {engineers.map(eng => (
                      <option key={eng.id} value={eng.name}>{eng.name}</option>
                    ))}
                  </select>
                  <ChevronRight className="absolute right-4 top-1/2 -translate-y-1/2 rotate-90 text-muted-foreground pointer-events-none" size={14} />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Time Logged</label>
                  <div className="relative">
                    <Clock className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground" size={14} />
                    <input 
                      type="text" 
                      placeholder="e.g. 4h 30m"
                      value={newTask.timeLogged || ''}
                      onChange={(e) => setNewTask({...newTask, timeLogged: e.target.value})}
                      className="h-11 w-full rounded-xl border border-border bg-muted/20 pl-11 pr-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all"
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Approval</label>
                  <div className="relative">
                    <select 
                      value={newTask.approvalStatus || 'Pending'}
                      onChange={(e) => setNewTask({...newTask, approvalStatus: e.target.value as any})}
                      className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all appearance-none cursor-pointer"
                    >
                      <option value="Pending">Pending</option>
                      <option value="Approved">Approved</option>
                      <option value="Rejected">Rejected</option>
                    </select>
                    <ChevronRight className="absolute right-4 top-1/2 -translate-y-1/2 rotate-90 text-muted-foreground pointer-events-none" size={14} />
                  </div>
                </div>
              </div>

              <div className="pt-4 flex items-center gap-3">
                <button 
                  type="button"
                  onClick={() => {
                    setIsTaskModalOpen(false);
                    setEditingTaskId(null);
                  }}
                  className="flex-1 h-11 text-sm font-bold border border-border rounded-xl hover:bg-accent transition-all"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  className="flex-1 h-11 bg-primary text-sm font-bold text-primary-foreground rounded-xl hover:bg-primary/90 transition-all shadow-sm"
                >
                  {editingTaskId ? 'Update Task' : 'Create Task'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

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

      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Tasks & Timesheets</h1>
          <p className="text-muted-foreground">Monitor and manage all active and upcoming projects.</p>
        </div>
        <div className="flex items-center gap-3">
          <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>
          <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>
        </div>
      </div>

      <div className="flex items-center gap-1 p-1 bg-muted/50 rounded-xl w-fit">
        <button
          onClick={() => setActiveTab('timesheets')}
          className={cn(
            "px-6 py-2 text-sm font-bold rounded-lg transition-all",
            activeTab === 'timesheets' 
              ? "bg-background text-primary shadow-sm" 
              : "text-muted-foreground hover:text-foreground"
          )}
        >
          Project Timesheets
        </button>
        <button
          onClick={() => setActiveTab('tasks')}
          className={cn(
            "px-6 py-2 text-sm font-bold rounded-lg transition-all",
            activeTab === 'tasks' 
              ? "bg-background text-primary shadow-sm" 
              : "text-muted-foreground hover:text-foreground"
          )}
        >
          Project Tasks
        </button>
      </div>

      <div className="space-y-4">
        {activeTab === 'timesheets' ? (
          <>
            {/* Filters */}
            <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="relative">
                <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 hover:bg-accent transition-colors",
                    (statusFilter !== 'All' || clientFilter !== 'All') && "border-primary text-primary"
                  )}
                >
                  <Filter size={18} />
                  Filters
                  {(statusFilter !== 'All' || clientFilter !== 'All') && (
                    <span className="ml-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground">
                      {[statusFilter, clientFilter].filter(f => f !== 'All').length}
                    </span>
                  )}
                  <ChevronDown size={14} className={cn("ml-1 transition-transform", isFilterOpen && "rotate-180")} />
                </button>

                {isFilterOpen && (
                  <>
                    <div 
                      className="fixed inset-0 z-[40]" 
                      onClick={() => setIsFilterOpen(false)}
                    />
                    <div className="absolute right-0 mt-2 w-64 rounded-xl border border-border bg-card p-4 shadow-xl z-[50] animate-in fade-in slide-in-from-top-2 duration-200">
                      <div className="space-y-4">
                        <div className="space-y-2">
                          <label className="text-xs font-bold 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="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 className="space-y-2">
                          <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Client</label>
                          <select 
                            value={clientFilter}
                            onChange={(e) => setClientFilter(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>
                            {Array.from(new Set(projects.map(p => p.client))).sort().map(client => (
                              <option key={client} value={client}>{client}</option>
                            ))}
                          </select>
                        </div>

                        {(statusFilter !== 'All' || clientFilter !== 'All') && (
                          <button 
                            onClick={() => {
                              setStatusFilter('All');
                              setClientFilter('All');
                            }}
                            className="w-full rounded-lg bg-muted py-2 text-xs font-medium hover:bg-muted/80 transition-colors"
                          >
                            Clear All Filters
                          </button>
                        )}
                      </div>
                    </div>
                  </>
                )}
              </div>
            </div>

            {/* Timesheet List */}
            <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 === 'Active' || project.status === 'Work 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">
                            <button 
                              onClick={() => handleEditProject(project)}
                              className="p-1 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                              title="Edit Project"
                            >
                              <Edit2 size={16} />
                            </button>
                            <button 
                              onClick={() => handleDeleteProjectClick(project)}
                              className="p-1 hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
                              title="Delete Project"
                            >
                              <Trash2 size={16} />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                    {filteredProjects.length === 0 && (
                      <tr>
                        <td colSpan={12} className="py-12 text-center text-muted-foreground">
                          No projects found matching your search.
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </>
        ) : (
          <div className="space-y-6">
            <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 tasks by title, project or assignee..."
                  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="relative">
                <button 
                  onClick={() => setIsTaskFilterOpen(!isTaskFilterOpen)}
                  className={cn(
                    "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",
                    (taskStatusFilter !== 'All' || taskProjectFilter !== 'All') && "border-primary text-primary"
                  )}
                >
                  <Filter size={18} />
                  Filters
                  {(taskStatusFilter !== 'All' || taskProjectFilter !== 'All') && (
                    <span className="ml-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground">
                      {[taskStatusFilter, taskProjectFilter].filter(f => f !== 'All').length}
                    </span>
                  )}
                  <ChevronDown size={14} className={cn("ml-1 transition-transform", isTaskFilterOpen && "rotate-180")} />
                </button>

                {isTaskFilterOpen && (
                  <>
                    <div 
                      className="fixed inset-0 z-[40]" 
                      onClick={() => setIsTaskFilterOpen(false)}
                    />
                    <div className="absolute right-0 mt-2 w-64 rounded-xl border border-border bg-card p-4 shadow-xl z-[50] animate-in fade-in slide-in-from-top-2 duration-200">
                      <div className="space-y-4">
                        <div className="space-y-2">
                          <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Status</label>
                          <select 
                            value={taskStatusFilter}
                            onChange={(e) => setTaskStatusFilter(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="To Do">To Do</option>
                            <option value="In Progress">In Progress</option>
                            <option value="Completed">Completed</option>
                          </select>
                        </div>

                        <div className="space-y-2">
                          <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Project</label>
                          <select 
                            value={taskProjectFilter}
                            onChange={(e) => setTaskProjectFilter(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 Projects</option>
                            {projects.map(project => (
                              <option key={project.id} value={project.id}>{project.name}</option>
                            ))}
                          </select>
                        </div>

                        {(taskStatusFilter !== 'All' || taskProjectFilter !== 'All') && (
                          <button 
                            onClick={() => {
                              setTaskStatusFilter('All');
                              setTaskProjectFilter('All');
                            }}
                            className="w-full rounded-lg bg-muted py-2 text-xs font-medium hover:bg-muted/80 transition-colors"
                          >
                            Clear All Filters
                          </button>
                        )}
                      </div>
                    </div>
                  </>
                )}
              </div>

              <button 
                onClick={() => setIsTaskModalOpen(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 ml-auto"
              >
                <Plus size={18} />
                Add Task
              </button>
            </div>

            <div className="grid gap-4">
              {filteredTasks.length > 0 ? (
                filteredTasks.map(task => {
                  const project = getProjectForTask(task.projectId);
                  return (
                    <div key={task.id} className="flex items-center justify-between p-4 rounded-xl border border-border bg-card hover:border-primary/50 transition-all group">
                      <div className="flex items-center gap-4">
                        <div className={cn(
                          "h-10 w-10 rounded-full flex items-center justify-center",
                          task.status === 'Completed' ? "bg-green-500/10 text-green-500" :
                          task.status === 'In Progress' ? "bg-blue-500/10 text-blue-500" :
                          "bg-yellow-500/10 text-yellow-500"
                        )}>
                          {task.status === 'Completed' ? <CheckCircle2 size={20} /> : <Timer size={20} />}
                        </div>
                        <div>
                          <h3 className="font-bold group-hover:text-primary transition-colors">{task.title}</h3>
                          <div className="flex items-center gap-3 text-xs text-muted-foreground mt-1">
                            <span className="flex items-center gap-1">
                              <Building2 size={12} />
                              {project?.name || 'Unknown Project'}
                            </span>
                            <span className="flex items-center gap-1">
                              <Clock size={12} />
                              Due: {task.dueDate}
                            </span>
                            {task.assignee && (
                              <span className="flex items-center gap-1">
                                <User size={12} />
                                {task.assignee}
                              </span>
                            )}
                            {task.timeLogged && (
                              <span className="flex items-center gap-1 text-primary font-bold">
                                <Clock size={12} />
                                {task.timeLogged}
                              </span>
                            )}
                            {task.approvalStatus && (
                              <span className={cn(
                                "flex items-center gap-1 font-bold px-1.5 py-0.5 rounded text-[10px] uppercase tracking-wider",
                                task.approvalStatus === 'Approved' ? "bg-emerald-500/10 text-emerald-500" :
                                task.approvalStatus === 'Rejected' ? "bg-rose-500/10 text-rose-500" :
                                "bg-yellow-500/10 text-yellow-500"
                              )}>
                                {task.approvalStatus}
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <button 
                          onClick={() => handleEditTask(task)}
                          className="p-1.5 hover:bg-accent text-muted-foreground transition-colors rounded-md"
                        >
                          <Edit2 size={16} />
                        </button>
                        <select 
                          value={task.status}
                          onChange={(e) => updateTask(task.id, { status: e.target.value as any })}
                          className="text-xs font-medium bg-muted border-none rounded-md px-2 py-1 focus:ring-1 focus:ring-primary/20 cursor-pointer"
                        >
                          <option value="To Do">To Do</option>
                          <option value="In Progress">In Progress</option>
                          <option value="Completed">Completed</option>
                        </select>
                        <button 
                          onClick={() => deleteTask(task.id)}
                          className="p-1.5 hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors rounded-md"
                        >
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </div>
                  );
                })
              ) : (
                <div className="py-12 text-center text-muted-foreground border-2 border-dashed border-border rounded-xl">
                  No tasks found. Start by adding a task to a project.
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
