import React, { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { Users, UserPlus, Briefcase, Mail, Phone, MapPin, MoreVertical, Search, Filter, Edit, User, Trash2, ShieldCheck, X, CalendarCheck, ChevronDown, FileBarChart, Download } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp, Engineer } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';
import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';

export function EmployeeDirectory() {
  const { engineers, addEngineer, updateEngineer, deleteEngineer, projects } = useApp();
  const { hasPermission } = useAuth();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    const create = searchParams.get('create');
    if (create === 'true') {
      handleOpenAddModal();
      const newParams = new URLSearchParams(searchParams);
      newParams.delete('create');
      setSearchParams(newParams, { replace: true });
    }
  }, [searchParams, setSearchParams]);
  const [activeMenu, setActiveMenu] = useState<string | null>(null);
  const [menuPosition, setMenuPosition] = useState({ top: 0, left: 0 });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isProfileOpen, setIsProfileOpen] = useState(false);
  const [editingEmployee, setEditingEmployee] = useState<any>(null);
  const [viewingEmployee, setViewingEmployee] = useState<any>(null);
  const [formData, setFormData] = useState({ name: '', role: '', department: '', email: '', status: 'Active', type: 'Internal' as 'Internal' | 'External' });
  const [isAttendOpen, setIsAttendOpen] = useState(false);
  const [isReportOpen, setIsReportOpen] = useState(false);
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [filterDepartment, setFilterDepartment] = useState('All');
  const [filterStatus, setFilterStatus] = useState('All');
  const menuRef = useRef<HTMLDivElement>(null);
  const attendRef = useRef<HTMLDivElement>(null);
  const filterRef = useRef<HTMLDivElement>(null);

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

  const handleOpenAddModal = () => {
    setEditingEmployee(null);
    setFormData({ name: '', role: '', department: '', email: '', status: 'Active', type: 'Internal' });
    setIsModalOpen(true);
  };

  const handleOpenEditModal = (emp: any) => {
    setEditingEmployee(emp);
    setFormData({ 
      name: emp.name, 
      role: emp.role, 
      department: emp.department, 
      email: emp.email, 
      status: emp.status,
      type: emp.type || 'Internal'
    });
    setIsModalOpen(true);
    setActiveMenu(null);
  };

  const handleOpenProfile = (emp: any) => {
    setViewingEmployee(emp);
    setIsProfileOpen(true);
    setActiveMenu(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;
    
    setIsSubmitting(true);
    try {
      if (editingEmployee) {
        await updateEngineer(editingEmployee.id, formData as any);
        toast.success(formData.type === 'External' ? 'Moved to External Engineers' : 'Employee updated successfully');
        if (formData.type === 'External') {
          navigate('/engineers');
        }
      } else {
        const newId = `EMP${String(engineers.length + 1).padStart(3, '0')}`;
        await addEngineer({ 
          id: newId, 
          ...formData, 
          workedDays: 0,
          phone: '',
          experience: 'Junior'
        } as Engineer);
        
        if (formData.type === 'External') {
          toast.success('External staff added to Engineers page');
          navigate('/engineers');
        } else {
          toast.success('Employee added successfully');
        }
      }
      setIsModalOpen(false);
    } catch (error: any) {
      console.error('[Employees] Submit error:', error);
      // AppContext withSyncLock handled the error toast
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDeleteEmployee = async (id: string, name: string) => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      await deleteEngineer(id);
      toast.error('Employee deleted', {
        description: `${name} has been removed from the directory.`
      });
      setActiveMenu(null);
    } catch (error) {
      toast.error('Failed to delete employee');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleStatusChange = async (id: string, currentStatus: string) => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    const newStatus = currentStatus === 'Active' ? 'On Leave' : 'Active';
    try {
      await updateEngineer(id, { status: newStatus as any });
      toast.info(`Status updated to ${newStatus}`);
      setActiveMenu(null);
    } catch (error) {
      toast.error('Failed to update status');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDownloadEmployee = (emp: Engineer) => {
    try {
      const fieldMapping: { [key: string]: string } = {
        id: 'Employee ID',
        name: 'Full Name',
        role: 'Role/Designation',
        department: 'Department',
        email: 'Email Address',
        phone: 'Phone Number',
        status: 'Status',
        experience: 'Experience Level',
        type: 'Employment Type',
        workedDays: 'Worked Days',
        skills: 'Skills'
      };

      const keys = Object.keys(fieldMapping);
      const headers = keys.map(k => fieldMapping[k]).join(',');
      
      const values = keys.map(key => {
        const val = (emp as any)[key];
        let cell = '';
        
        if (Array.isArray(val)) {
          cell = val.join(' | ');
        } else if (val !== undefined && val !== null) {
          cell = String(val);
        }
        
        // Escape quotes and wrap in quotes if contains comma, newline or quotes
        if (cell.includes(',') || cell.includes('\n') || cell.includes('"')) {
          return `"${cell.replace(/"/g, '""')}"`;
        }
        return cell;
      }).join(',');
      
      const csvContent = `${headers}\n${values}`;
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const downloadAnchorNode = document.createElement('a');
      downloadAnchorNode.setAttribute("href", url);
      downloadAnchorNode.setAttribute("download", `${emp.name.replace(/\s+/g, '_')}_details.csv`);
      document.body.appendChild(downloadAnchorNode);
      downloadAnchorNode.click();
      downloadAnchorNode.remove();
      URL.revokeObjectURL(url);
      
      toast.success(`Downloading details for ${emp.name} as CSV`);
      setActiveMenu(null);
    } catch (error) {
      console.error('Download Error:', error);
      toast.error('Failed to download employee details');
    }
  };

  const handleExportPDF = () => {
    try {
      const doc = new jsPDF();
      
      // Add title
      doc.setFontSize(22);
      doc.setTextColor(30, 41, 59); // slate-800
      doc.text('Monthly Attendance Report', 14, 22);
      
      // Add date
      doc.setFontSize(10);
      doc.setTextColor(100, 116, 139); // slate-500
      doc.text(`Generated on: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`, 14, 30);
      
      // Add stats
      const totalEmployees = engineers.length;
      const totalDaysWorked = engineers.reduce((acc, emp) => acc + (emp.workedDays || 0), 0);
      const avgAttendance = totalEmployees > 0 ? (totalDaysWorked / totalEmployees).toFixed(1) : 0;
      
      doc.setFontSize(12);
      doc.setTextColor(51, 65, 85); // slate-700
      doc.text(`Total Employees: ${totalEmployees}`, 14, 42);
      doc.text(`Total Days Worked: ${totalDaysWorked}`, 14, 48);
      doc.text(`Avg. Attendance: ${avgAttendance} days`, 14, 54);
      
      // Add table
      const internalEmployees = engineers.filter(e => e.type === 'Internal');
      const tableData = internalEmployees
        .sort((a, b) => (b.workedDays || 0) - (a.workedDays || 0))
        .map(emp => [emp.name, emp.department, emp.workedDays || 0]);
      
      autoTable(doc, {
        startY: 65,
        head: [['Employee Name', 'Department', 'Days Worked']],
        body: tableData,
        theme: 'striped',
        headStyles: { 
          fillColor: [59, 130, 246], // blue-500
          textColor: [255, 255, 255],
          fontSize: 11,
          fontStyle: 'bold'
        },
        bodyStyles: {
          fontSize: 10,
          textColor: [71, 85, 105] // slate-600
        },
        alternateRowStyles: {
          fillColor: [248, 250, 252] // slate-50
        },
        margin: { top: 65 }
      });
      
      doc.save(`Attendance_Report_${new Date().toISOString().split('T')[0]}.pdf`);
      
      toast.success('Report exported successfully', {
        description: 'The monthly report has been downloaded as PDF.'
      });
      setIsReportOpen(false);
    } catch (error) {
      console.error('PDF Export Error:', error);
      toast.error('Failed to export PDF');
    }
  };

  const filteredEmployees = engineers.filter(emp => {
    const matchesSearch = 
      emp.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      emp.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
      emp.department.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesDepartment = filterDepartment === 'All' || emp.department === filterDepartment;
    const matchesStatus = filterStatus === 'All' || emp.status === filterStatus;
    const isInternal = emp.type === 'Internal';
    
    return matchesSearch && matchesDepartment && matchesStatus && isInternal;
  });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Employee Directory</h1>
          <p className="text-muted-foreground">Manage and view all employees across the organization.</p>
        </div>
        <div className="flex items-center gap-3">
          {hasPermission('hr.edit') && (
            <div className="relative" ref={attendRef}>
              <button 
                onClick={() => setIsAttendOpen(!isAttendOpen)}
                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"
              >
                <CalendarCheck size={18} />
                Attend
                <ChevronDown size={14} className={cn("transition-transform duration-200", isAttendOpen && "rotate-180")} />
              </button>

              {isAttendOpen && (
                <div className="absolute right-0 mt-2 z-50 w-56 max-h-64 overflow-y-auto rounded-xl border border-border bg-card p-1 shadow-lg animate-in fade-in slide-in-from-top-2 duration-200">
                  <div className="px-3 py-2 text-xs font-semibold text-muted-foreground border-b border-border mb-1">
                    Mark Attendance
                  </div>
                  {engineers.map((emp) => (
                    <button
                      key={emp.id}
                      disabled={isSubmitting}
                      onClick={async () => {
                        if (isSubmitting) return;
                        setIsSubmitting(true);
                        try {
                          await updateEngineer(emp.id, { workedDays: (emp.workedDays || 0) + 1 });
                          toast.success(`Attendance marked`, {
                            description: `Attendance recorded for ${emp.name} (${emp.id})`
                          });
                          setIsAttendOpen(false);
                        } catch (error) {
                          toast.error('Failed to mark attendance');
                        } finally {
                          setIsSubmitting(false);
                        }
                      }}
                      className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-left text-sm hover:bg-accent transition-colors disabled:opacity-50"
                    >
                      <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center text-[10px] font-bold text-primary">
                        {emp.name.charAt(0)}
                      </div>
                      <span className="truncate">{emp.name}</span>
                    </button>
                  ))}
                </div>
              )}
            </div>
          )}
          {hasPermission('hr.export') && (
            <button 
              onClick={() => setIsReportOpen(true)}
              className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
            >
              <FileBarChart size={18} />
              Monthly Report
            </button>
          )}
          {hasPermission('hr.create') && (
            <button 
              onClick={handleOpenAddModal}
              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"
            >
              <UserPlus size={18} />
              Add Employee
            </button>
          )}
        </div>
      </div>

      {/* Monthly Report Modal */}
      {isReportOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-2xl rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="mb-6 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <FileBarChart className="text-primary" size={24} />
                <h3 className="text-xl font-bold">Monthly Attendance Report</h3>
              </div>
              <button 
                onClick={() => setIsReportOpen(false)}
                className="rounded-md p-1 hover:bg-accent transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <div className="space-y-6">
              <div className="grid grid-cols-3 gap-4">
                <div className="rounded-lg border border-border bg-muted/30 p-4">
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Total Employees</p>
                  <p className="text-2xl font-bold">{engineers.filter(e => e.type === 'Internal').length}</p>
                </div>
                <div className="rounded-lg border border-border bg-muted/30 p-4">
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Total Days Worked</p>
                  <p className="text-2xl font-bold text-primary">
                    {engineers.filter(e => e.type === 'Internal').reduce((acc, emp) => acc + (emp.workedDays || 0), 0)}
                  </p>
                </div>
                <div className="rounded-lg border border-border bg-muted/30 p-4">
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Avg. Attendance</p>
                  <p className="text-2xl font-bold">
                    {engineers.filter(e => e.type === 'Internal').length > 0 
                      ? (engineers.filter(e => e.type === 'Internal').reduce((acc, emp) => acc + (emp.workedDays || 0), 0) / engineers.filter(e => e.type === 'Internal').length).toFixed(1) 
                      : 0}
                  </p>
                </div>
              </div>

              <div className="rounded-lg border border-border overflow-hidden">
                <table className="w-full text-left text-sm">
                  <thead className="bg-muted/50 border-b border-border">
                    <tr>
                      <th className="px-4 py-2 font-semibold">Employee</th>
                      <th className="px-4 py-2 font-semibold">Department</th>
                      <th className="px-4 py-2 font-semibold text-right">Days Worked</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {engineers
                      .filter(e => e.type === 'Internal')
                      .sort((a, b) => (b.workedDays || 0) - (a.workedDays || 0))
                      .map((emp) => (
                      <tr key={emp.id} className="hover:bg-accent/50 transition-colors">
                        <td className="px-4 py-3 font-medium">{emp.name}</td>
                        <td className="px-4 py-3 text-muted-foreground">{emp.department}</td>
                        <td className="px-4 py-3 text-right font-bold text-primary">{emp.workedDays || 0}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            <div className="mt-8 flex justify-end">
              <button 
                onClick={handleExportPDF}
                className="rounded-lg bg-primary px-6 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
              >
                Export PDF
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Profile Modal */}
      {isProfileOpen && viewingEmployee && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-lg rounded-xl border border-border bg-card p-8 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="mb-6 flex items-center justify-between">
              <h3 className="text-xl font-bold">Employee Profile</h3>
              <button 
                onClick={() => setIsProfileOpen(false)}
                className="rounded-md p-1 hover:bg-accent transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            
            <div className="flex items-center gap-6 mb-8">
              <div className="h-24 w-24 rounded-full bg-primary/10 flex items-center justify-center text-primary text-3xl font-bold">
                {viewingEmployee.name.charAt(0)}
              </div>
              <div>
                <h4 className="text-2xl font-bold">{viewingEmployee.name}</h4>
                <p className="text-muted-foreground">{viewingEmployee.role} • {viewingEmployee.department}</p>
                <span className={cn(
                  "mt-2 inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium uppercase tracking-wider",
                  viewingEmployee.status === 'Active' ? "bg-green-500/10 text-green-500" : "bg-yellow-500/10 text-yellow-500"
                )}>
                  {viewingEmployee.status}
                </span>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-6">
              <div className="space-y-1">
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Employee ID</p>
                <p className="font-mono">{viewingEmployee.id}</p>
              </div>
              <div className="space-y-1">
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Email Address</p>
                <p className="flex items-center gap-2">
                  <Mail size={14} className="text-muted-foreground" />
                  {viewingEmployee.email}
                </p>
              </div>
              <div className="space-y-1">
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Phone Number</p>
                <p className="flex items-center gap-2">
                  <Phone size={14} className="text-muted-foreground" />
                  +1 (555) 000-0000
                </p>
              </div>
              <div className="space-y-1">
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Location</p>
                <p className="flex items-center gap-2">
                  <MapPin size={14} className="text-muted-foreground" />
                  San Francisco, CA
                </p>
              </div>
              <div className="space-y-1">
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Worked Days</p>
                <p className="flex items-center gap-2 font-bold text-primary">
                  <CalendarCheck size={14} />
                  {viewingEmployee.workedDays || 0} Days
                </p>
              </div>
            </div>

            <div className="mt-8 pt-6 border-t border-border">
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-4">Assigned Projects</p>
              <div className="space-y-3">
                {projects.filter(p => p.assignedTo === viewingEmployee.name).length > 0 ? (
                  projects.filter(p => p.assignedTo === viewingEmployee.name).map(project => (
                    <div key={project.id} className="flex items-center justify-between p-3 rounded-lg border border-border bg-muted/20">
                      <div>
                        <p className="text-sm font-bold">{project.name}</p>
                        <p className="text-[10px] text-muted-foreground uppercase tracking-wider">{project.client}</p>
                      </div>
                      <span className={cn(
                        "px-2 py-0.5 rounded-full text-[10px] font-bold uppercase",
                        project.status === 'Active' ? "bg-blue-500/10 text-blue-500" : "bg-muted text-muted-foreground"
                      )}>
                        {project.status}
                      </span>
                    </div>
                  ))
                ) : (
                  <p className="text-sm text-muted-foreground italic">No projects assigned yet.</p>
                )}
              </div>
            </div>

            <div className="mt-8 pt-6 border-t border-border flex gap-3">
              <button 
                onClick={() => {
                  setIsProfileOpen(false);
                  handleOpenEditModal(viewingEmployee);
                }}
                className="flex-1 flex items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
              >
                <Edit size={16} />
                Edit Profile
              </button>
              <button 
                onClick={() => setIsProfileOpen(false)}
                className="flex-1 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Employee Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="mb-4 flex items-center justify-between">
              <h3 className="text-lg font-semibold">{editingEmployee ? 'Edit Employee' : 'Add New Employee'}</h3>
              <button 
                onClick={() => setIsModalOpen(false)}
                className="rounded-md p-1 hover:bg-accent transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Full Name</label>
                <input 
                  type="text" 
                  required
                  placeholder="e.g. John Doe"
                  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/50"
                  value={formData.name || ''}
                  onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))}
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Department</label>
                  <input 
                    type="text" 
                    required
                    placeholder="e.g. Engineering"
                    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/50"
                    value={formData.department || ''}
                    onChange={e => setFormData(prev => ({ ...prev, department: e.target.value }))}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Role</label>
                  <input 
                    type="text" 
                    required
                    placeholder="e.g. Developer"
                    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/50"
                    value={formData.role || ''}
                    onChange={e => setFormData(prev => ({ ...prev, role: e.target.value }))}
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Employment Type</label>
                  <select 
                    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/50 [&>option]:bg-background [&>option]:text-foreground"
                    value={formData.type || 'Internal'}
                    onChange={e => setFormData(prev => ({ ...prev, type: e.target.value as any }))}
                  >
                    <option value="Internal">Internal (Employee)</option>
                    <option value="External">External (Contractor)</option>
                  </select>
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Status</label>
                  <select 
                    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/50"
                    value={formData.status || 'Active'}
                    onChange={e => setFormData(prev => ({ ...prev, status: e.target.value }))}
                  >
                    <option value="Active">Active</option>
                    <option value="On Leave">On Leave</option>
                    <option value="Pending Approval">Pending Approval</option>
                  </select>
                </div>
              </div>
              <div className="flex gap-3 pt-4">
                <button 
                  type="button"
                  onClick={() => setIsModalOpen(false)}
                  className="flex-1 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  disabled={isSubmitting}
                  className={cn(
                    "flex-1 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors",
                    isSubmitting && "opacity-50 cursor-not-allowed"
                  )}
                >
                  {isSubmitting ? (
                    <div className="flex items-center justify-center gap-2">
                       <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />
                       Saving...
                    </div>
                  ) : (
                    editingEmployee ? 'Update' : 'Create'
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      <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 employees by name, ID or department..."
            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" 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",
              (filterDepartment !== 'All' || filterStatus !== 'All') && "border-primary text-primary"
            )}
          >
            <Filter size={18} />
            Filters
            {(filterDepartment !== 'All' || filterStatus !== 'All') && (
              <span className="flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground">
                {[filterDepartment, filterStatus].filter(f => f !== 'All').length}
              </span>
            )}
          </button>

          {isFilterOpen && (
            <div className="absolute right-0 mt-2 z-50 w-64 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 Options</h4>
                <button 
                  onClick={() => {
                    setFilterDepartment('All');
                    setFilterStatus('All');
                  }}
                  className="text-[10px] font-bold uppercase tracking-wider text-primary hover:underline"
                >
                  Reset
                </button>
              </div>
              
              <div className="space-y-4">
                <div className="space-y-2">
                  <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Department</label>
                  <select 
                    value={filterDepartment}
                    onChange={(e) => setFilterDepartment(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 Departments</option>
                    {Array.from(new Set(engineers.map(e => e.department))).filter(Boolean).sort().map(dept => (
                      <option key={dept} value={dept}>{dept}</option>
                    ))}
                  </select>
                </div>

                <div className="space-y-2">
                  <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Status</label>
                  <select 
                    value={filterStatus}
                    onChange={(e) => setFilterStatus(e.target.value)}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="All">All Statuses</option>
                    <option value="Active">Active</option>
                    <option value="On Leave">On Leave</option>
                    <option value="Pending Approval">Pending Approval</option>
                  </select>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card shadow-sm overflow-hidden">
        <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-6 py-4 font-semibold">Employee</th>
                <th className="px-6 py-4 font-semibold">ID</th>
                <th className="px-6 py-4 font-semibold">Department</th>
                <th className="px-6 py-4 font-semibold">Role</th>
                <th className="px-6 py-4 font-semibold">Worked Days</th>
                <th className="px-6 py-4 font-semibold">Status</th>
                <th className="px-6 py-4 font-semibold text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {filteredEmployees.map((emp) => (
                <tr key={emp.id} className="hover:bg-accent/50 transition-colors group">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold group-hover:bg-primary group-hover:text-primary-foreground transition-colors">
                        {emp.name.charAt(0)}
                      </div>
                      <div>
                        <p className="font-medium">{emp.name}</p>
                        <p className="text-xs text-muted-foreground">{emp.email}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-muted-foreground font-mono text-xs">{emp.id}</td>
                  <td className="px-6 py-4">{emp.department}</td>
                  <td className="px-6 py-4">{emp.role}</td>
                  <td className="px-6 py-4 font-medium text-center">
                    <span className="inline-flex items-center justify-center h-8 w-8 rounded-full bg-primary/5 text-primary border border-primary/10">
                      {emp.workedDays || 0}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <span className={cn(
                      "inline-flex items-center rounded-full px-2 py-1 text-[10px] font-bold uppercase tracking-wider",
                      emp.status === 'Active' ? "bg-green-500/10 text-green-500" : 
                      emp.status === 'Pending Approval' ? "bg-orange-500/10 text-orange-500" :
                      "bg-yellow-500/10 text-yellow-500"
                    )}>
                      {emp.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-right relative">
                    <button 
                      onClick={(e) => {
                        const rect = e.currentTarget.getBoundingClientRect();
                        setMenuPosition({ 
                          top: rect.bottom + window.scrollY, 
                          left: rect.right + window.scrollX - 192 // 192px is w-48
                        });
                        setActiveMenu(activeMenu === emp.id ? null : emp.id)
                      }}
                      className={cn(
                        "rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors",
                        activeMenu === emp.id && "bg-accent text-foreground"
                      )}
                    >
                      <MoreVertical size={18} />
                    </button>

                    {activeMenu === emp.id && createPortal(
                      <div 
                        ref={menuRef}
                        style={{ 
                          position: 'absolute', 
                          top: menuPosition.top, 
                          left: menuPosition.left,
                          zIndex: 9999
                        }}
                        className="w-48 rounded-lg border border-border bg-card p-1 shadow-lg animate-in fade-in zoom-in duration-150"
                      >
                        <button 
                          onClick={() => handleOpenProfile(emp)}
                          className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-accent transition-colors"
                        >
                          <User size={16} className="text-muted-foreground" />
                          View Details
                        </button>
                        {hasPermission('hr.export') && (
                          <button 
                            onClick={() => handleDownloadEmployee(emp)}
                            className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-accent transition-colors"
                          >
                            <Download size={16} className="text-muted-foreground" />
                            Download Details
                          </button>
                        )}
                        {hasPermission('hr.edit') && (
                          <>
                            {emp.status === 'Pending Approval' && (
                              <button 
                                disabled={isSubmitting}
                                onClick={async () => {
                                  setIsSubmitting(true);
                                  try {
                                    await updateEngineer(emp.id, { status: 'Active' });
                                    toast.success(`${emp.name} approved successfully`);
                                    setActiveMenu(null);
                                  } catch (error) {
                                    toast.error('Failed to approve employee');
                                  } finally {
                                    setIsSubmitting(false);
                                  }
                                }}
                                className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-green-600 hover:bg-green-50 transition-colors disabled:opacity-50"
                              >
                                <ShieldCheck size={16} />
                                Approve Employee
                              </button>
                            )}
                            <button 
                              onClick={() => handleOpenEditModal(emp)}
                              className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-accent transition-colors"
                            >
                              <Edit size={16} className="text-muted-foreground" />
                              Edit Details
                            </button>
                            <button 
                              onClick={() => handleStatusChange(emp.id, emp.status)}
                              className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-accent transition-colors"
                            >
                              <ShieldCheck size={16} className="text-muted-foreground" />
                              Change Status
                            </button>
                          </>
                        )}
                        {hasPermission('hr.delete') && (
                          <>
                            <div className="my-1 border-t border-border" />
                            <button 
                              onClick={() => handleDeleteEmployee(emp.id, emp.name)}
                              className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-destructive hover:bg-destructive/10 transition-colors"
                            >
                              <Trash2 size={16} />
                              Delete Employee
                            </button>
                          </>
                        )}
                      </div>,
                      document.body
                    )}
                  </td>
                </tr>
              ))}
              {filteredEmployees.length === 0 && (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-muted-foreground">
                    No employees found matching your search.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
