import React, { useState, useRef, useEffect, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { HardHat, UserPlus, Briefcase, Mail, Phone, MapPin, MoreVertical, Search, Filter, Edit, User, Trash2, ShieldCheck, X, CalendarCheck, ChevronDown, FileBarChart, Wrench, Users, DollarSign, TrendingUp, ExternalLink, Globe, Building, Download, Upload } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp, Engineer } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';

export function EngineerManagement() {
  const { engineers, addEngineer, updateEngineer, deleteEngineer, projects, syncEngineersFromProjects } = 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 [isSyncing, setIsSyncing] = useState(false);
  const [editingEngineer, setEditingEngineer] = useState<Engineer | null>(null);
  const [viewingEngineer, setViewingEngineer] = useState<Engineer | null>(null);
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [filterStatus, setFilterStatus] = useState('All');
  const [formData, setFormData] = useState<Partial<Engineer>>({
    name: '',
    role: '',
    department: '',
    email: '',
    phone: '',
    status: 'Available',
    experience: '',
    type: 'External',
    skills: []
  });
  const menuRef = useRef<HTMLDivElement>(null);
  const filterRef = useRef<HTMLDivElement>(null);

  // Summary Stats
  const externalEngineers = engineers.filter(e => e.type === 'External');
  const totalEngineers = externalEngineers.length;
  const availableCount = externalEngineers.filter(e => e.status === 'Available').length;
  const activeCount = externalEngineers.filter(e => e.status === 'Active').length;
  const pendingApprovalCount = externalEngineers.filter(e => e.status === 'Pending Approval').length;

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

  const handleSyncFromProjects = async () => {
    if (isSyncing || isSubmitting) return;
    setIsSyncing(true);
    setIsSubmitting(true);
    try {
      const addedCount = await syncEngineersFromProjects();

      if (addedCount > 0) {
        toast.success(`Synced ${addedCount} new engineers from projects`);
      } else {
        toast.info('No new engineers found in projects');
      }
    } catch (error) {
      toast.error('Failed to sync engineers');
    } finally {
      setIsSyncing(false);
      setIsSubmitting(false);
    }
  };

  const handleOpenAddModal = () => {
    setEditingEngineer(null);
    setFormData({
      name: '',
      role: '',
      department: '',
      email: '',
      phone: '',
      status: 'Available',
      experience: '',
      type: 'External',
      skills: []
    });
    setIsModalOpen(true);
  };

  const handleOpenEditModal = (eng: Engineer) => {
    setEditingEngineer(eng);
    setFormData({ ...eng });
    setIsModalOpen(true);
    setActiveMenu(null);
  };

  const handleOpenProfile = (eng: Engineer) => {
    setViewingEngineer(eng);
    setIsProfileOpen(true);
    setActiveMenu(null);
  };

  const handleDownloadEngineer = (eng: Engineer) => {
    try {
      const fieldMapping: { [key: string]: string } = {
        id: 'Engineer ID',
        name: 'Full Name',
        role: 'Role',
        department: 'Department',
        email: 'Email Address',
        phone: 'Phone Number',
        status: 'Status',
        experience: 'Experience',
        type: 'Type',
        skills: 'Skills'
      };

      const keys = Object.keys(fieldMapping);
      const headers = keys.map(k => fieldMapping[k]).join(',');
      
      const values = keys.map(key => {
        const val = (eng as any)[key];
        let cell = '';
        
        if (Array.isArray(val)) {
          cell = val.join(' | ');
        } else if (val !== undefined && val !== null) {
          cell = String(val);
        }
        
        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 link = document.createElement('a');
      link.setAttribute("href", url);
      link.setAttribute("download", `${eng.name.replace(/\s+/g, '_')}_details.csv`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      
      toast.success(`Downloading details for ${eng.name} as CSV`);
      setActiveMenu(null);
    } catch (error) {
      console.error('Download Error:', error);
      toast.error('Failed to download engineer details');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;

    setIsSubmitting(true);
    try {
      if (editingEngineer) {
        await updateEngineer(editingEngineer.id, formData);
        toast.success(formData.type === 'Internal' ? 'Moved to Employees' : 'Engineer updated successfully');
        if (formData.type === 'Internal') {
          navigate('/employees');
        }
      } else {
        const newId = `ENG-${Math.random().toString(36).substr(2, 5).toUpperCase()}`;
        await addEngineer({ ...formData, id: newId } as Engineer);
        toast.success(formData.type === 'Internal' ? 'Internal employee added to Employee Directory' : 'Engineer added successfully');
        if (formData.type === 'Internal') {
          navigate('/employees');
        }
      }
      setIsModalOpen(false);
    } catch (error: any) {
      console.error('[Engineers] Submit error:', error);
      // AppContext withSyncLock handled the error toast
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      await deleteEngineer(id);
      toast.success('Engineer deleted successfully');
    } catch (error) {
      toast.error('Failed to delete engineer');
    } finally {
      setIsSubmitting(false);
      setActiveMenu(null);
    }
  };

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

    const headers = ['ID', 'Name', 'Role', 'Department', 'Email', 'Phone', 'Status', 'Type', 'Experience'];
    const csvRows = [
      headers.join(','),
      ...engineers.map(e => [
        `"${e.id}"`,
        `"${e.name}"`,
        `"${e.role}"`,
        `"${e.department}"`,
        `"${e.email}"`,
        `"${e.phone}"`,
        `"${e.status}"`,
        `"${e.type}"`,
        `"${e.experience}"`
      ].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', `engineers_export_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success('Engineers 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 newEngs: any[] = [];
        for (let i = 1; i < rows.length; i++) {
          const matches = rows[i].match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
          if (!matches || matches.length < 7) continue;

          const clean = (val: string) => val.replace(/^"|"$/g, '').trim();
          
          const eng = {
            id: clean(matches[0]),
            name: clean(matches[1]),
            role: clean(matches[2]),
            department: clean(matches[3]),
            email: clean(matches[4]),
            phone: clean(matches[5]),
            status: clean(matches[6]) as any,
            type: clean(matches[7]) as any || 'External',
            experience: clean(matches[8]) || '',
            skills: []
          };
          newEngs.push(eng);
        }

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

        const existingIds = new Set(engineers.map(e => e.id));
        const uniqueNew = newEngs.filter(e => !existingIds.has(e.id));
        
        if (uniqueNew.length === 0) {
          toast.info('All records in CSV already exist');
        } else {
          for (const eng of uniqueNew) {
            await addEngineer(eng);
          }
          toast.success(`Successfully imported ${uniqueNew.length} new engineers`);
        }
      } 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 filteredEngineers = engineers.filter(eng => {
    const matchesSearch = 
      eng.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      eng.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
      eng.role.toLowerCase().includes(searchQuery.toLowerCase()) ||
      eng.email.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesStatus = filterStatus === 'All' || eng.status === filterStatus;
    const isExternal = eng.type === 'External';
    
    return matchesSearch && matchesStatus && isExternal;
  });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Engineer Database</h1>
          <p className="text-muted-foreground">Manage internal and external technical staff resources.</p>
        </div>
        <div className="flex items-center gap-3">
          {hasPermission('hr.create') && (
            <div className="relative">
              <input 
                type="file" 
                accept=".csv"
                className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                onChange={handleImportCSV}
              />
              <button className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors">
                <Upload size={18} />
                Import CSV
              </button>
            </div>
          )}
          {hasPermission('hr.export') && (
            <button 
              onClick={handleExportCSV}
              className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
            >
              <Download size={18} />
              Export CSV
            </button>
          )}
          {hasPermission('hr.edit') && (
            <button 
              onClick={handleSyncFromProjects}
              disabled={isSyncing}
              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 disabled:opacity-50"
            >
              <Wrench size={18} className={cn(isSyncing && "animate-spin")} />
              {isSyncing ? 'Syncing...' : 'Sync from Projects'}
            </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 shadow-sm"
            >
              <UserPlus size={18} />
              Add Engineer
            </button>
          )}
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <div className="flex items-center justify-between mb-2">
            <p className="text-sm font-medium text-muted-foreground">Total External</p>
            <Users className="text-primary" size={18} />
          </div>
          <div className="flex items-baseline gap-2">
            <h3 className="text-2xl font-bold">{totalEngineers}</h3>
            <span className="text-xs font-medium text-muted-foreground">Database total</span>
          </div>
        </div>

        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <div className="flex items-center justify-between mb-2">
            <p className="text-sm font-medium text-muted-foreground">Currently Active</p>
            <Briefcase className="text-blue-500" size={18} />
          </div>
          <div className="flex items-baseline gap-2">
            <h3 className="text-2xl font-bold">{activeCount}</h3>
            <span className="text-xs font-medium text-muted-foreground">On Projects</span>
          </div>
        </div>

        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <div className="flex items-center justify-between mb-2">
            <p className="text-sm font-medium text-muted-foreground">Available Now</p>
            <TrendingUp className="text-green-500" size={18} />
          </div>
          <div className="flex items-baseline gap-2">
            <h3 className="text-2xl font-bold">{availableCount}</h3>
            <span className="text-xs font-medium text-green-500">Ready for projects</span>
          </div>
        </div>

        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <div className="flex items-center justify-between mb-2">
            <p className="text-sm font-medium text-muted-foreground">Pending Approval</p>
            <ShieldCheck className="text-orange-500" size={18} />
          </div>
          <div className="flex items-baseline gap-2">
            <h3 className="text-2xl font-bold">{pendingApprovalCount}</h3>
            <span className="text-xs font-medium text-orange-500">New hires</span>
          </div>
        </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 engineers by name, ID, role or email..."
            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",
              filterStatus !== 'All' && "border-primary text-primary"
            )}
          >
            <Filter size={18} />
            Filters
            {filterStatus !== 'All' && (
              <span className="flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground">
                {[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={() => {
                    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">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="Available">Available</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">Engineer</th>
                <th className="px-6 py-4 font-semibold">Type</th>
                <th className="px-6 py-4 font-semibold">Contact Info</th>
                <th className="px-6 py-4 font-semibold">Role</th>
                <th className="px-6 py-4 font-semibold">Experience</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">
              {filteredEngineers.map((eng) => (
                <tr key={eng.id} className="hover:bg-accent/30 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">
                        {eng.name.charAt(0)}
                      </div>
                      <div>
                        <p className="font-bold">{eng.name}</p>
                        <p className="text-[10px] font-mono text-muted-foreground">{eng.id}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span className={cn(
                      "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-bold uppercase",
                      eng.type === 'Internal' ? "bg-blue-500/10 text-blue-500" : "bg-purple-500/10 text-purple-500"
                    )}>
                      {eng.type === 'Internal' ? <Building size={10} /> : <Globe size={10} />}
                      {eng.type}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <div className="space-y-1">
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <Mail size={12} className="text-primary/70" />
                        {eng.email}
                      </div>
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <Phone size={12} className="text-primary/70" />
                        {eng.phone}
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span className="inline-flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs font-medium">
                      <HardHat size={12} className="text-primary" />
                      {eng.role}
                    </span>
                  </td>
                  <td className="px-6 py-4 font-medium">
                    {eng.experience}
                  </td>
                  <td className="px-6 py-4">
                    <span className={cn(
                      "inline-flex items-center rounded-full px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-wider",
                      eng.status === 'Available' ? "bg-green-500/10 text-green-500" : 
                      eng.status === 'Active' ? "bg-blue-500/10 text-blue-500" : 
                      eng.status === 'Pending Approval' ? "bg-orange-500/10 text-orange-500" :
                      "bg-yellow-500/10 text-yellow-500"
                    )}>
                      {eng.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 === eng.id ? null : eng.id)
                      }}
                      className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
                    >
                      <MoreVertical size={18} />
                    </button>
                    {activeMenu === eng.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(eng)}
                          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 Profile
                        </button>
                        {hasPermission('hr.export') && (
                          <button 
                            onClick={() => handleDownloadEngineer(eng)}
                            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>
                        )}
                        {eng.status === 'Pending Approval' && hasPermission('hr.edit') && (
                          <button 
                            disabled={isSubmitting}
                            onClick={async () => {
                              if (isSubmitting) return;
                              setIsSubmitting(true);
                              try {
                                await updateEngineer(eng.id, { status: 'Available' });
                                toast.success(`${eng.name} approved and marked as Available`);
                                setActiveMenu(null);
                              } catch (error) {
                                toast.error('Failed to approve engineer');
                              } 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 Hire
                          </button>
                        )}
                        {hasPermission('hr.edit') && (
                          <button 
                            onClick={() => handleOpenEditModal(eng)}
                            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>
                        )}
                        <div className="my-1 border-t border-border" />
                        {hasPermission('hr.delete') && (
                          <button 
                            onClick={() => handleDelete(eng.id)}
                            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
                          </button>
                        )}
                      </div>,
                      document.body
                    )}
                  </td>
                </tr>
              ))}
              {filteredEngineers.length === 0 && (
                <tr>
                  <td colSpan={7} className="px-6 py-12 text-center text-muted-foreground italic">
                    No engineers found in the database.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Engineer Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="mb-4 flex items-center justify-between">
              <h3 className="text-lg font-semibold">{editingEngineer ? 'Edit Engineer' : 'Add New Engineer'}</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="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Full Name</label>
                  <input 
                    type="text" 
                    required
                    placeholder="e.g. Alex Rivera"
                    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="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 || 'External'}
                    onChange={e => setFormData(prev => ({ ...prev, type: e.target.value as any }))}
                  >
                    <option value="External">External (Contractor)</option>
                    <option value="Internal">Internal (Staff)</option>
                  </select>
                </div>
              </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" 
                    placeholder="e.g. Backend"
                    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. Senior Engineer"
                    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">Email</label>
                  <input 
                    type="email" 
                    required
                    placeholder="alex@company.com"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                    value={formData.email || ''}
                    onChange={e => setFormData(prev => ({ ...prev, email: e.target.value }))}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Phone</label>
                  <input 
                    type="text" 
                    placeholder="+1 (555) 000-0000"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                    value={formData.phone || ''}
                    onChange={e => setFormData(prev => ({ ...prev, phone: e.target.value }))}
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Experience</label>
                  <input 
                    type="text" 
                    placeholder="e.g. 5 years"
                    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.experience || ''}
                    onChange={e => setFormData(prev => ({ ...prev, experience: e.target.value }))}
                  />
                </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 || 'Available'}
                    onChange={e => setFormData(prev => ({ ...prev, status: e.target.value as any }))}
                  >
                    <option value="Available">Available</option>
                    <option value="Active">Active</option>
                    <option value="On Leave">On Leave</option>
                    <option value="Pending Approval">Pending Approval</option>
                  </select>
                </div>
                <div className="space-y-2 col-span-2">
                  <label className="text-sm font-medium">Skills (comma separated)</label>
                  <input 
                    type="text" 
                    placeholder="e.g. React, Node.js, AWS"
                    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.skills?.join(', ') || ''}
                    onChange={e => setFormData(prev => ({ ...prev, skills: e.target.value.split(',').map(s => s.trim()).filter(s => s !== '') }))}
                  />
                </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>
                  ) : (
                    editingEngineer ? 'Update' : 'Create'
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Profile Modal */}
      {isProfileOpen && viewingEngineer && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
          <div className="w-full max-w-2xl rounded-2xl border border-border bg-card shadow-2xl animate-in fade-in zoom-in duration-200 overflow-hidden">
            <div className="relative h-32 bg-gradient-to-r from-primary/20 via-primary/10 to-transparent">
              <button 
                onClick={() => setIsProfileOpen(false)}
                className="absolute right-4 top-4 rounded-full bg-background/50 p-2 hover:bg-background transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            
            <div className="px-8 pb-8">
              <div className="relative -mt-12 mb-6 flex items-end gap-6">
                <div className="h-24 w-24 rounded-2xl bg-primary flex items-center justify-center text-primary-foreground text-4xl font-bold shadow-xl border-4 border-card">
                  {viewingEngineer.name.charAt(0)}
                </div>
                <div className="pb-2">
                  <h4 className="text-2xl font-bold">{viewingEngineer.name}</h4>
                  <div className="flex items-center gap-2 text-muted-foreground">
                    <HardHat size={16} className="text-primary" />
                    <span>{viewingEngineer.role}</span>
                  </div>
                </div>
                <div className="ml-auto pb-2">
                  <span className={cn(
                    "inline-flex items-center rounded-full px-3 py-1 text-xs font-bold uppercase tracking-wider",
                    viewingEngineer.status === 'Available' ? "bg-green-500/10 text-green-500" : 
                    viewingEngineer.status === 'Active' ? "bg-blue-500/10 text-blue-500" : "bg-yellow-500/10 text-yellow-500"
                  )}>
                    {viewingEngineer.status}
                  </span>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                <div className="space-y-6">
                  <section className="space-y-3">
                    <h5 className="text-[10px] font-bold text-muted-foreground uppercase tracking-widest">Contact Information</h5>
                    <div className="space-y-3 rounded-xl border border-border p-4 bg-muted/20">
                      <div className="flex items-center gap-3">
                        <div className="h-8 w-8 rounded-lg bg-card flex items-center justify-center border border-border">
                          <Mail size={14} className="text-primary" />
                        </div>
                        <div>
                          <p className="text-[10px] text-muted-foreground uppercase font-bold">Email</p>
                          <p className="text-sm font-medium">{viewingEngineer.email}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-3">
                        <div className="h-8 w-8 rounded-lg bg-card flex items-center justify-center border border-border">
                          <Phone size={14} className="text-primary" />
                        </div>
                        <div>
                          <p className="text-[10px] text-muted-foreground uppercase font-bold">Phone</p>
                          <p className="text-sm font-medium">{viewingEngineer.phone}</p>
                        </div>
                      </div>
                    </div>
                  </section>

                  <section className="space-y-3">
                    <h5 className="text-[10px] font-bold text-muted-foreground uppercase tracking-widest">System Info</h5>
                    <div className="grid grid-cols-2 gap-3">
                      <div className="rounded-xl border border-border p-4 bg-muted/20">
                        <p className="text-[10px] text-muted-foreground uppercase font-bold">Engineer ID</p>
                        <p className="font-mono text-xs">{viewingEngineer.id}</p>
                      </div>
                      <div className="rounded-xl border border-border p-4 bg-muted/20">
                        <p className="text-[10px] text-muted-foreground uppercase font-bold">Type</p>
                        <p className="text-xs font-medium">{viewingEngineer.type}</p>
                      </div>
                    </div>
                  </section>
                </div>

                <div className="space-y-6">
                  <section className="space-y-3">
                    <h5 className="text-[10px] font-bold text-muted-foreground uppercase tracking-widest">Technical Profile</h5>
                    <div className="space-y-4 rounded-xl border border-border p-6 bg-primary/5">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Briefcase size={16} className="text-primary" />
                          <span className="text-sm font-medium">Experience</span>
                        </div>
                        <span className="text-lg font-bold text-primary">{viewingEngineer.experience}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Building size={16} className="text-primary" />
                          <span className="text-sm font-medium">Department</span>
                        </div>
                        <span className="text-lg font-bold text-primary">{viewingEngineer.department || 'N/A'}</span>
                      </div>
                    </div>
                  </section>

                  <div className="flex gap-3">
                    <button 
                      onClick={() => navigate(`/projects?search=${encodeURIComponent(viewingEngineer.name)}`)}
                      className="flex-1 flex items-center justify-center gap-2 rounded-xl bg-primary px-4 py-3 text-sm font-bold text-primary-foreground hover:bg-primary/90 transition-all shadow-lg shadow-primary/20"
                    >
                      <ExternalLink size={16} />
                      View Projects
                    </button>
                  </div>
                  <section className="space-y-3">
                    <h5 className="text-[10px] font-bold text-muted-foreground uppercase tracking-widest">Skills & Expertise</h5>
                    <div className="flex flex-wrap gap-2">
                      {viewingEngineer.skills && viewingEngineer.skills.length > 0 ? (
                        viewingEngineer.skills.map((skill, idx) => (
                          <span key={idx} className="px-2 py-1 rounded-md bg-primary/10 text-primary text-[10px] font-bold uppercase tracking-wider">
                            {skill}
                          </span>
                        ))
                      ) : (
                        <span className="text-xs text-muted-foreground italic">No skills listed</span>
                      )}
                    </div>
                  </section>

                  <section className="space-y-3">
                    <h5 className="text-[10px] font-bold text-muted-foreground uppercase tracking-widest">Assigned Projects</h5>
                    <div className="space-y-2">
                      {projects.filter(p => p.assignedTo === viewingEngineer.name).length > 0 ? (
                        projects.filter(p => p.assignedTo === viewingEngineer.name).map(project => (
                          <div key={project.id} className="flex items-center justify-between p-3 rounded-xl border border-border bg-card hover:border-primary/50 transition-all group">
                            <div>
                              <p className="text-xs font-bold group-hover:text-primary transition-colors">{project.name}</p>
                              <p className="text-[10px] text-muted-foreground">{project.client}</p>
                            </div>
                            <span className={cn(
                              "px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider",
                              project.status === 'In Progress' ? "bg-blue-500/10 text-blue-500" :
                              project.status === 'Completed' ? "bg-green-500/10 text-green-500" :
                              "bg-yellow-500/10 text-yellow-500"
                            )}>
                              {project.status}
                            </span>
                          </div>
                        ))
                      ) : (
                        <div className="p-4 rounded-xl border border-dashed border-border text-center text-xs text-muted-foreground">
                          No active project assignments
                        </div>
                      )}
                    </div>
                  </section>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

