import React, { useState, useRef, useEffect, useMemo } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { 
  Users, 
  Plus, 
  Search, 
  Filter, 
  MoreHorizontal, 
  Briefcase, 
  UserPlus, 
  Calendar,
  ChevronRight,
  Clock,
  CheckCircle2,
  AlertCircle,
  FileText,
  Mail,
  Phone,
  MapPin,
  Trash2,
  X,
  Download,
  Upload
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp, JobOpening, Candidate } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';

export function Recruitment() {
  const { jobs, candidates, addJob, updateJob, deleteJob, addCandidate, updateCandidate, deleteCandidate, addEngineer } = useApp();
  const { hasPermission } = useAuth();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [activeTab, setActiveTab] = useState<'jobs' | 'candidates'>('jobs');

  useEffect(() => {
    const create = searchParams.get('create');
    if (create === 'true') {
      setIsCandidateModalOpen(true);
      setActiveTab('candidates');
      const newParams = new URLSearchParams(searchParams);
      newParams.delete('create');
      setSearchParams(newParams, { replace: true });
    }
  }, [searchParams, setSearchParams]);
  const [searchQuery, setSearchQuery] = useState('');
  const [jobStatusFilter, setJobStatusFilter] = useState<string>('All');
  const [jobOpeningStatusFilter, setJobOpeningStatusFilter] = useState<string>('All');
  const [activeMenu, setActiveMenu] = useState<string | null>(null);
  const [editingJobId, setEditingJobId] = useState<string | null>(null);
  const [isJobModalOpen, setIsJobModalOpen] = useState(false);
  const [isCandidateModalOpen, setIsCandidateModalOpen] = useState(false);
  const [jobFormData, setJobFormData] = useState({
    title: '',
    department: '',
    location: '',
    type: 'Full-time' as const,
    status: 'Draft' as const
  });
  const [candidateFormData, setCandidateFormData] = useState({
    name: '',
    role: '',
    experience: '',
    status: 'Applied' as const,
    email: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

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

  const handleAddJob = () => {
    setEditingJobId(null);
    setJobFormData({
      title: '',
      department: '',
      location: '',
      type: 'Full-time',
      status: 'Draft'
    });
    setIsJobModalOpen(true);
  };

  const handleEditJob = (job: JobOpening) => {
    setEditingJobId(job.id);
    setJobFormData({
      title: job.title,
      department: job.department,
      location: job.location,
      type: job.type,
      status: job.status
    });
    setIsJobModalOpen(true);
    setActiveMenu(null);
  };

  const handleJobSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      if (editingJobId) {
        await updateJob(editingJobId, jobFormData);
        toast.success('Job opening updated successfully');
      } else {
        const newJob: JobOpening = {
          id: `JOB-00${jobs.length + 1}`,
          ...jobFormData,
          applicants: 0,
          postedDate: new Date().toISOString().split('T')[0]
        };
        await addJob(newJob);
        toast.success(jobFormData.status === 'Open' ? 'Job opening posted successfully' : 'Job opening created as draft');
      }
      setIsJobModalOpen(false);
      setEditingJobId(null);
    } catch (error) {
      toast.error(editingJobId ? 'Failed to update job' : 'Failed to post job');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleAddCandidate = () => {
    setCandidateFormData({
      name: '',
      role: '',
      experience: '',
      status: 'Applied',
      email: ''
    });
    setIsCandidateModalOpen(true);
  };

  const handleCandidateSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      const newCandidate: Candidate = {
        id: `CAN-00${candidates.length + 1}`,
        ...candidateFormData,
        appliedDate: new Date().toISOString().split('T')[0]
      };
      await addCandidate(newCandidate);
      setIsCandidateModalOpen(false);
      toast.success(`Candidate ${candidateFormData.name} added successfully`);
    } catch (error) {
      toast.error('Failed to add candidate');
    } finally {
      setIsSubmitting(false);
    }
  };

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

    const headers = ['ID', 'Name', 'Role', 'Experience', 'Status', 'Email'];
    const csvRows = [
      headers.join(','),
      ...candidates.map(c => [
        `"${c.id}"`,
        `"${c.name}"`,
        `"${c.role}"`,
        `"${c.experience}"`,
        `"${c.status}"`,
        `"${c.email}"`
      ].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', `candidates_export_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success('Candidates exported successfully');
  };

  const handleImportCandidatesCSV = (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 newCandidates: any[] = [];
        for (let i = 1; i < rows.length; i++) {
          const matches = rows[i].match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
          if (!matches || matches.length < 5) continue;

          const clean = (val: string) => val.replace(/^"|"$/g, '').trim();
          
          const candidate = {
            id: clean(matches[0]),
            name: clean(matches[1]),
            role: clean(matches[2]),
            experience: clean(matches[3]),
            status: clean(matches[4]) as any,
            email: clean(matches[5]) || '',
            appliedDate: new Date().toISOString().split('T')[0]
          };
          newCandidates.push(candidate);
        }

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

        const existingIds = new Set(candidates.map(c => c.id));
        const uniqueNew = newCandidates.filter(c => !existingIds.has(c.id));
        
        if (uniqueNew.length === 0) {
          toast.info('All records in CSV already exist');
        } else {
          for (const cand of uniqueNew) {
            await addCandidate(cand);
          }
          toast.success(`Successfully imported ${uniqueNew.length} new candidates`);
        }
      } 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 updateCandidateStatusHandler = async (candidateId: string, newStatus: Candidate['status']) => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      await updateCandidate(candidateId, { status: newStatus });
      
      if (newStatus === 'Hired') {
        const candidate = candidates.find(c => c.id === candidateId);
        if (candidate) {
          const newEngineerId = `ENG-${Math.random().toString(36).substr(2, 5).toUpperCase()}`;
          await addEngineer({
            id: newEngineerId,
            name: candidate.name,
            role: candidate.role,
            email: candidate.email,
            phone: 'N/A',
            department: 'Pending Assignment',
            status: 'Pending Approval',
            experience: candidate.experience,
            type: 'Internal'
          });
          toast.success(`Candidate ${candidate.name} hired!`, {
            description: "Transferred to Employees directory for final approval.",
            action: {
              label: "View Employees",
              onClick: () => navigate('/employees')
            }
          });
        }
      } else {
        toast.success(`Status updated to ${newStatus}`);
      }
      
      setActiveMenu(null);
    } catch (error) {
      toast.error('Failed to update status');
    } finally {
      setIsSubmitting(false);
    }
  };

  const filteredJobs = jobs.filter(j => {
    const query = searchQuery.toLowerCase();
    const matchesQuery = j.title.toLowerCase().includes(query) ||
      j.department.toLowerCase().includes(query);
    
    if (jobOpeningStatusFilter === 'All') return matchesQuery;
    return matchesQuery && j.status === jobOpeningStatusFilter;
  });

  const filteredCandidates = candidates.filter(c => {
    const query = searchQuery.toLowerCase();
    const matchesQuery = c.name.toLowerCase().includes(query) ||
      c.role.toLowerCase().includes(query) ||
      c.status.toLowerCase().includes(query);
    
    if (jobStatusFilter === 'All') return matchesQuery;
    
    const job = jobs.find(j => j.title === c.role);
    return matchesQuery && job?.status === jobStatusFilter;
  });

  const applicantsLast30Days = useMemo(() => {
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    return candidates.filter(c => new Date(c.appliedDate).getTime() >= thirtyDaysAgo.getTime()).length;
  }, [candidates]);

  const jobsPostedLast30Days = useMemo(() => {
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    return jobs.filter(j => new Date(j.postedDate).getTime() >= thirtyDaysAgo.getTime()).length;
  }, [jobs]);

  const candidatesInPipeline = useMemo(() => {
    return candidates.filter(c => ['Screening', 'Interview', 'Offer'].includes(c.status)).length;
  }, [candidates]);

  return (
    <div className="space-y-10 pb-20">
      {/* Editorial Header */}
      <div className="relative overflow-hidden rounded-3xl bg-slate-950 p-8 md:p-12 text-white shadow-2xl">
        <div className="relative z-10 max-w-2xl">
          <h1 className="font-serif text-5xl md:text-7xl font-bold leading-tight tracking-tighter mb-4">
            Find the <span className="italic text-blue-400">Perfect</span> Match.
          </h1>
          <p className="text-lg md:text-xl text-slate-400 font-light max-w-lg mb-8">
            Our recruitment engine helps you scale your engineering teams with precision and speed.
          </p>
          <div className="flex flex-wrap gap-3">
            {hasPermission('hr.create') && (
              <button 
                onClick={handleAddJob}
                className="group flex items-center gap-2 rounded-full bg-blue-500 px-6 py-3 text-sm font-semibold text-white hover:bg-blue-400 transition-all shadow-lg shadow-blue-500/20"
              >
                <Plus size={18} className="group-hover:rotate-90 transition-transform" />
                Post New Job
              </button>
            )}
            {hasPermission('hr.create') && (
              <button 
                onClick={handleAddCandidate}
                className="flex items-center gap-2 rounded-full bg-white/10 px-6 py-3 text-sm font-semibold text-white hover:bg-white/20 transition-all backdrop-blur-md"
              >
                <UserPlus size={18} />
                Add Candidate
              </button>
            )}
            {hasPermission('hr.create') && (
              <div className="relative">
                <input 
                  type="file" 
                  accept=".csv"
                  className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                  onChange={handleImportCandidatesCSV}
                />
                <button className="flex items-center gap-2 rounded-full bg-white/10 px-6 py-3 text-sm font-semibold text-white hover:bg-white/20 transition-all backdrop-blur-md">
                  <Upload size={18} />
                  Import Candidates
                </button>
              </div>
            )}
            {hasPermission('hr.export') && (
              <button 
                onClick={handleExportCandidatesCSV}
                className="flex items-center gap-2 rounded-full bg-white/10 px-6 py-3 text-sm font-semibold text-white hover:bg-white/20 transition-all backdrop-blur-md"
              >
                <Download size={18} />
                Export Candidates
              </button>
            )}
          </div>
        </div>
        
        {/* Decorative elements */}
        <div className="absolute top-0 right-0 -translate-y-1/2 translate-x-1/4 w-96 h-96 bg-blue-500/20 rounded-full blur-3xl" />
        <div className="absolute bottom-0 right-0 translate-y-1/2 translate-x-1/4 w-64 h-64 bg-purple-500/10 rounded-full blur-3xl" />
      </div>

      {/* Recruitment Stats - Clean Utility Style */}
      <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
        <RecruitmentStatCard 
          title="Active Openings" 
          value={jobs.filter(j => j.status === 'Open' || j.status === 'Interviewing').length.toString()} 
          icon={Briefcase} 
          trend={`${jobsPostedLast30Days} posted recently`} 
          trendColor="text-blue-500"
          onClick={() => setActiveTab('jobs')}
        />
        <RecruitmentStatCard 
          title="Total Applicants" 
          value={candidates.length.toString()} 
          icon={Users} 
          trend={`${applicantsLast30Days} in last 30 days`} 
          trendColor="text-blue-500"
          onClick={() => {
            setActiveTab('candidates');
            setSearchQuery('');
          }}
        />
        <RecruitmentStatCard 
          title="In Pipeline" 
          value={candidatesInPipeline.toString()} 
          icon={Calendar} 
          trend={`${candidates.filter(c => c.status === 'Interview').length} interviewing`} 
          trendColor="text-purple-500"
          onClick={() => {
            setActiveTab('candidates');
            setSearchQuery('');
          }}
        />
        <RecruitmentStatCard 
          title="Hired" 
          value={jobs.filter(j => j.status === 'Closed').length.toString()} 
          icon={CheckCircle2} 
          trend={`${candidates.filter(c => c.status === 'Hired').length} hired`} 
          trendColor="text-green-500"
          onClick={() => {
            setActiveTab('jobs');
            setSearchQuery('Closed');
          }}
        />
      </div>

      <div className="space-y-6">
        {/* Tab Switcher - Minimalist */}
        <div className="flex items-center justify-between border-b border-border">
          <div className="flex">
                <button 
                  onClick={() => setActiveTab('jobs')}
                  className={cn(
                    "px-8 py-4 text-sm font-bold tracking-widest uppercase transition-all relative",
                    activeTab === 'jobs' ? "text-foreground" : "text-muted-foreground hover:text-foreground"
                  )}
                >
                  Job Openings
                  {activeTab === 'jobs' && <div className="absolute bottom-0 left-0 right-0 h-1 bg-blue-500" />}
                </button>
                <button
                  onClick={() => setActiveTab('candidates')}
                  className={cn(
                    "px-8 py-4 text-sm font-bold tracking-widest uppercase transition-all relative",
                    activeTab === 'candidates' ? "text-foreground" : "text-muted-foreground hover:text-foreground"
                  )}
                >
                  Candidates
                  {activeTab === 'candidates' && <div className="absolute bottom-0 left-0 right-0 h-1 bg-blue-500" />}
                </button>
          </div>
        </div>

        {/* Search & Filters - Refined */}
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center justify-between bg-card p-4 rounded-2xl shadow-sm border border-border">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
            <input
              type="text"
              placeholder={activeTab === 'jobs' ? "Search positions..." : "Search candidates..."}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="h-12 w-full rounded-xl border-none bg-muted pl-12 pr-4 text-sm focus:ring-2 focus:ring-blue-500/20 transition-all text-foreground"
            />
          </div>
          <div className="flex items-center gap-3">
            {activeTab === 'candidates' && (
              <select
                value={jobStatusFilter}
                onChange={(e) => setJobStatusFilter(e.target.value)}
                className="h-12 rounded-xl border-border bg-card px-4 text-sm font-medium focus:ring-2 focus:ring-blue-500/20 text-foreground"
              >
                <option value="All">All Jobs</option>
                <option value="Open">Open</option>
                <option value="Interviewing">Interviewing</option>
                <option value="Closed">Closed</option>
                <option value="Rejected">Cancelled</option>
                <option value="Draft">Draft</option>
              </select>
            )}
            {activeTab === 'jobs' && (
              <select
                value={jobOpeningStatusFilter}
                onChange={(e) => setJobOpeningStatusFilter(e.target.value)}
                className="h-12 rounded-xl border-border bg-card px-4 text-sm font-medium focus:ring-2 focus:ring-blue-500/20 text-foreground"
              >
                <option value="All">All Statuses</option>
                <option value="Open">Open</option>
                <option value="Interviewing">Interviewing</option>
                <option value="Draft">Draft</option>
                <option value="Closed">Closed</option>
                <option value="Rejected">Cancelled</option>
              </select>
            )}
            <button 
              onClick={() => {
                setSearchQuery('');
                setJobOpeningStatusFilter('All');
                setJobStatusFilter('All');
              }}
              className="h-12 px-6 rounded-xl border border-border bg-card text-sm font-bold uppercase tracking-wider hover:bg-accent transition-all text-foreground"
            >
              Reset
            </button>
          </div>
        </div>

      {activeTab === 'jobs' ? (
          <div className="grid gap-8 md:grid-cols-2 xl:grid-cols-3">
            {filteredJobs.map((job) => (
              <div key={job.id} className="group relative flex flex-col rounded-3xl border border-border bg-card p-8 shadow-sm hover:shadow-xl hover:-translate-y-1 transition-all duration-300">
                <div className="flex items-start justify-between mb-6">
                  <div className="space-y-1">
                    <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-blue-500">{job.department}</span>
                    <h3 className="font-serif text-2xl font-bold leading-tight group-hover:text-blue-600 transition-colors text-foreground">{job.title}</h3>
                  </div>
                    {hasPermission('hr.edit') && (
                      <div className="relative">
                        <button 
                          onClick={() => setActiveMenu(activeMenu === job.id ? null : job.id)}
                          className={cn(
                            "p-2 hover:bg-muted rounded-full text-muted-foreground transition-colors",
                            activeMenu === job.id && "bg-muted text-foreground"
                          )}
                        >
                          <MoreHorizontal size={20} />
                        </button>
                        
                        {activeMenu === job.id && (
                          <div 
                            ref={menuRef}
                            className="absolute right-0 top-10 z-50 w-48 rounded-2xl border border-border bg-popover p-2 shadow-2xl animate-in fade-in zoom-in duration-200"
                          >
                            {hasPermission('hr.edit') && (
                              <button 
                                onClick={() => handleEditJob(job)}
                                className="flex w-full items-center gap-3 rounded-xl px-4 py-2.5 text-left text-sm font-medium hover:bg-accent transition-colors text-popover-foreground"
                              >
                                Edit Details
                              </button>
                            )}
                            {hasPermission('hr.edit') && (
                              <button 
                                disabled={isSubmitting}
                                onClick={async () => {
                                  if (isSubmitting) return;
                                  setIsSubmitting(true);
                                  try {
                                    await updateJob(job.id, { status: job.status === 'Open' ? 'Closed' : 'Open' });
                                    toast.info(`Job status updated`);
                                    setActiveMenu(null);
                                  } catch (error) {
                                    toast.error('Failed to update status');
                                  } finally {
                                    setIsSubmitting(false);
                                  }
                                }}
                                className="flex w-full items-center gap-3 rounded-xl px-4 py-2.5 text-left text-sm font-medium hover:bg-accent transition-colors disabled:opacity-50 text-popover-foreground"
                              >
                                Toggle Status
                              </button>
                            )}
                            <div className="my-1 border-t border-border" />
                            {hasPermission('hr.delete') && (
                              <button 
                                disabled={isSubmitting}
                                onClick={async () => {
                                  if (isSubmitting) return;
                                  setIsSubmitting(true);
                                  try {
                                    await deleteJob(job.id);
                                    toast.error('Job opening deleted');
                                    setActiveMenu(null);
                                  } catch (error) {
                                    toast.error('Failed to delete job');
                                  } finally {
                                    setIsSubmitting(false);
                                  }
                                }}
                                className="flex w-full items-center gap-3 rounded-xl px-4 py-2.5 text-left text-sm font-medium text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50"
                              >
                                Delete Job
                              </button>
                            )}
                          </div>
                        )}
                      </div>
                    )}
                </div>

                <div className="grid grid-cols-2 gap-4 mb-8">
                  <div className="flex items-center gap-3 text-muted-foreground">
                    <div className="p-2 rounded-lg bg-muted">
                      <MapPin size={16} />
                    </div>
                    <span className="text-sm font-medium">{job.location}</span>
                  </div>
                  <div className="flex items-center gap-3 text-muted-foreground">
                    <div className="p-2 rounded-lg bg-muted">
                      <Clock size={16} />
                    </div>
                    <span className="text-sm font-medium">{job.type}</span>
                  </div>
                </div>

                <div className="mt-auto flex items-center justify-between">
                  <div 
                    onClick={() => {
                      setSearchQuery(job.title);
                      setActiveTab('candidates');
                      window.scrollTo({ top: 0, behavior: 'smooth' });
                    }}
                    className="flex -space-x-2 cursor-pointer hover:opacity-80 transition-opacity"
                  >
                    {[1, 2, 3].map((i) => (
                      <div key={i} className="h-8 w-8 rounded-full border-2 border-card bg-muted flex items-center justify-center text-[10px] font-bold">
                        {String.fromCharCode(64 + i)}
                      </div>
                    ))}
                    <div className="h-8 w-8 rounded-full border-2 border-card bg-muted flex items-center justify-center text-[10px] font-bold text-muted-foreground">
                      +{job.applicants}
                    </div>
                  </div>
                  
                  <span className={cn(
                    "rounded-full px-4 py-1 text-[10px] font-bold uppercase tracking-widest",
                    job.status === 'Open' ? "bg-green-100 text-green-700" :
                    job.status === 'Interviewing' ? "bg-purple-100 text-purple-700" :
                    job.status === 'Draft' ? "bg-yellow-100 text-yellow-700" :
                    job.status === 'Rejected' ? "bg-red-100 text-red-700" :
                    "bg-slate-100 text-slate-600"
                  )}>
                    {job.status}
                  </span>
                </div>
              </div>
            ))}
            {filteredJobs.length === 0 && (
              <div className="col-span-full py-20 text-center bg-card rounded-3xl border border-dashed border-border">
                <div className="flex flex-col items-center gap-4">
                  <div className="p-6 rounded-full bg-muted">
                    <Briefcase size={48} className="text-muted-foreground/30" />
                  </div>
                  <div className="space-y-1">
                    <h3 className="text-xl font-bold text-foreground">No positions found</h3>
                    <p className="text-muted-foreground">Try adjusting your search or filters to find what you're looking for.</p>
                  </div>
                  <button 
                    onClick={() => {
                      setSearchQuery('');
                      setJobOpeningStatusFilter('All');
                    }}
                    className="mt-4 px-8 py-3 rounded-full bg-primary text-primary-foreground text-sm font-bold uppercase tracking-wider hover:bg-primary/90 transition-all"
                  >
                    Clear all filters
                  </button>
                </div>
              </div>
            )}
          </div>
      ) : (
        <div className="rounded-3xl border border-border bg-card overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead>
                <tr className="border-b border-border bg-muted/50">
                  <th className="px-8 py-5 font-bold uppercase tracking-widest text-[10px] text-muted-foreground">Candidate</th>
                  <th className="px-8 py-5 font-bold uppercase tracking-widest text-[10px] text-muted-foreground">Position</th>
                  <th className="px-8 py-5 font-bold uppercase tracking-widest text-[10px] text-muted-foreground">Experience</th>
                  <th className="px-8 py-5 font-bold uppercase tracking-widest text-[10px] text-muted-foreground">Status</th>
                  <th className="px-8 py-5 font-bold uppercase tracking-widest text-[10px] text-muted-foreground text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filteredCandidates.map((candidate) => (
                  <tr key={candidate.id} className="hover:bg-accent/5 transition-colors group">
                    <td className="px-8 py-6">
                      <div className="flex items-center gap-4">
                        <div className="h-12 w-12 rounded-2xl bg-blue-500/10 flex items-center justify-center text-blue-500 font-bold text-sm">
                          {candidate.name.split(' ').map(n => n[0]).join('')}
                        </div>
                        <div>
                          <p className="font-bold text-foreground group-hover:text-primary transition-colors">{candidate.name}</p>
                          <p className="text-xs text-muted-foreground">{candidate.email}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-8 py-6">
                      <div className="flex flex-col gap-1">
                        <span className="font-medium text-foreground/80">{candidate.role}</span>
                        {(() => {
                          const job = jobs.find(j => j.title === candidate.role);
                          if (!job) return null;
                          return (
                            <span className={cn(
                              "inline-flex w-fit items-center rounded-full px-2 py-0.5 text-[9px] font-bold uppercase tracking-tighter",
                              job.status === 'Open' ? "bg-green-500/10 text-green-500" :
                              job.status === 'Interviewing' ? "bg-purple-500/10 text-purple-500" :
                              job.status === 'Draft' ? "bg-yellow-500/10 text-yellow-500" :
                              job.status === 'Rejected' ? "bg-red-500/10 text-red-500" :
                              "bg-muted text-muted-foreground"
                            )}>
                              {job.status === 'Rejected' ? 'Cancelled' : job.status}
                            </span>
                          );
                        })()}
                      </div>
                    </td>
                    <td className="px-8 py-6 text-muted-foreground font-medium">{candidate.experience}</td>
                    <td className="px-8 py-6">
                      <span className={cn(
                        "inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] font-bold uppercase tracking-wider",
                        candidate.status === 'Hired' ? "bg-green-500 text-white" :
                        candidate.status === 'Offer' ? "bg-blue-500 text-white" :
                        candidate.status === 'Interview' ? "bg-purple-500 text-white" :
                        candidate.status === 'Rejected' ? "bg-red-500 text-white" :
                        "bg-muted text-muted-foreground"
                      )}>
                        {candidate.status}
                      </span>
                    </td>
                    <td className="px-8 py-6 text-right">
                      <div className="flex items-center justify-end gap-2">
                        {hasPermission('hr.export') && (
                          <button 
                            onClick={() => toast.info(`Viewing resume of ${candidate.name}`)}
                            className="h-10 w-10 flex items-center justify-center hover:bg-accent hover:shadow-md rounded-xl text-muted-foreground hover:text-primary transition-all"
                            title="View Resume"
                          >
                            <FileText size={18} />
                          </button>
                        )}
                        {(hasPermission('hr.edit') || hasPermission('hr.delete')) && (
                          <div className="relative">
                            <button 
                              onClick={() => setActiveMenu(activeMenu === candidate.id ? null : candidate.id)}
                              className={cn(
                                "h-10 w-10 flex items-center justify-center hover:bg-muted hover:shadow-md rounded-xl text-muted-foreground transition-all",
                                activeMenu === candidate.id && "bg-muted shadow-md text-foreground"
                              )}
                            >
                              <MoreHorizontal size={18} />
                            </button>

                            {activeMenu === candidate.id && (
                              <div 
                                ref={menuRef}
                                className="absolute right-0 top-12 z-50 w-56 rounded-2xl border border-border bg-card p-2 shadow-2xl animate-in fade-in zoom-in duration-200"
                              >
                                <div className="px-4 py-2 text-[10px] font-bold uppercase tracking-widest text-muted-foreground">Management</div>
                                {hasPermission('hr.edit') && (
                                  <button 
                                    onClick={() => {
                                      updateCandidateStatusHandler(candidate.id, 'Interview');
                                      toast.info(`Interview scheduled for ${candidate.name}`);
                                      setActiveMenu(null);
                                    }}
                                    className="flex w-full items-center gap-3 rounded-xl px-4 py-2.5 text-left text-sm font-medium hover:bg-accent transition-colors"
                                  >
                                    <Calendar size={16} className="text-muted-foreground" />
                                    Schedule Interview
                                  </button>
                                )}
                                {hasPermission('hr.edit') && (
                                  <button 
                                    onClick={() => {
                                      toast.info(`Sending email to ${candidate.name}`);
                                      setActiveMenu(null);
                                    }}
                                    className="flex w-full items-center gap-3 rounded-xl px-4 py-2.5 text-left text-sm font-medium hover:bg-accent transition-colors"
                                  >
                                    <Mail size={16} className="text-muted-foreground" />
                                    Send Message
                                  </button>
                                )}
                                
                                {hasPermission('hr.edit') && (
                                  <>
                                    <div className="my-2 border-t border-border" />
                                    <div className="px-4 py-2 text-[10px] font-bold uppercase tracking-widest text-muted-foreground">Status</div>
                                    
                                    <div className="grid grid-cols-2 gap-1 p-1">
                                      {['Screening', 'Interview', 'Offer', 'Hired', 'Rejected'].map((status) => (
                                        <button 
                                          key={status}
                                          disabled={isSubmitting}
                                          onClick={() => updateCandidateStatusHandler(candidate.id, status as any)}
                                          className={cn(
                                            "px-2 py-1.5 rounded-lg text-[10px] font-bold text-center transition-all disabled:opacity-50",
                                            candidate.status === status ? "bg-foreground text-background" : "bg-muted text-muted-foreground hover:bg-accent"
                                          )}
                                        >
                                          {status === 'Rejected' && isSubmitting && candidate.status !== status ? '...' : status}
                                        </button>
                                      ))}
                                    </div>
                                  </>
                                )}
                                
                                {hasPermission('hr.delete') && (
                                  <>
                                    <div className="my-2 border-t border-border" />
                                    <button 
                                      disabled={isSubmitting}
                                      onClick={async () => {
                                        if (isSubmitting) return;
                                        setIsSubmitting(true);
                                        try {
                                          await deleteCandidate(candidate.id);
                                          toast.error('Candidate removed');
                                          setActiveMenu(null);
                                        } catch (error) {
                                          toast.error('Failed to delete candidate');
                                        } finally {
                                          setIsSubmitting(false);
                                        }
                                      }}
                                      className="flex w-full items-center gap-3 rounded-xl px-4 py-2.5 text-left text-sm font-medium text-red-500 hover:bg-red-50 transition-colors disabled:opacity-50"
                                    >
                                      <Trash2 size={16} className="text-red-400" />
                                      Remove Candidate
                                    </button>
                                  </>
                                )}
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
                {filteredCandidates.length === 0 && (
                  <tr>
                    <td colSpan={5} className="px-8 py-20 text-center">
                      <div className="flex flex-col items-center gap-4">
                        <div className="p-6 rounded-full bg-muted">
                          <Users size={48} className="text-muted-foreground/30" />
                        </div>
                        <div className="space-y-1">
                          <h3 className="text-xl font-bold text-foreground">No candidates found</h3>
                          <p className="text-muted-foreground">Try adjusting your search or filters to find what you're looking for.</p>
                        </div>
                        <button 
                          onClick={() => {
                            setSearchQuery('');
                            setJobStatusFilter('All');
                          }}
                          className="mt-4 px-8 py-3 rounded-full bg-primary text-primary-foreground text-sm font-bold uppercase tracking-wider hover:bg-primary/90 transition-all"
                        >
                          Clear all filters
                        </button>
                      </div>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}
      </div>

      <PostJobModal 
        isOpen={isJobModalOpen}
        onClose={() => {
          setIsJobModalOpen(false);
          setEditingJobId(null);
        }}
        onSubmit={handleJobSubmit}
        formData={jobFormData}
        setFormData={setJobFormData}
        isEditing={!!editingJobId}
      />

      <AddCandidateModal 
        isOpen={isCandidateModalOpen}
        onClose={() => setIsCandidateModalOpen(false)}
        onSubmit={handleCandidateSubmit}
        formData={candidateFormData}
        setFormData={setCandidateFormData}
        availableRoles={jobs.filter(j => j.status === 'Open').map(j => j.title)}
      />
    </div>
  );
}

function PostJobModal({ isOpen, onClose, onSubmit, formData, setFormData, isEditing }: { 
  isOpen: boolean, 
  onClose: () => void, 
  onSubmit: (e: React.FormEvent) => void,
  formData: any,
  setFormData: any,
  isEditing?: boolean
}) {
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/40 backdrop-blur-md p-4 animate-in fade-in duration-300">
      <div className="w-full max-w-lg rounded-[2rem] border border-border bg-card p-10 shadow-2xl animate-in zoom-in-95 duration-300">
        <div className="flex items-center justify-between mb-8">
          <h2 className="font-serif text-3xl font-bold text-foreground">{isEditing ? 'Edit Position' : 'New Position'}</h2>
          <button onClick={onClose} className="rounded-full p-2 hover:bg-muted text-muted-foreground transition-colors">
            <X size={24} />
          </button>
        </div>

        <form onSubmit={onSubmit} className="space-y-6">
          <div className="space-y-2">
            <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Job Title</label>
            <input
              required
              type="text"
              value={formData.title || ''}
              onChange={(e) => setFormData({ ...formData, title: e.target.value })}
              placeholder="e.g. Senior Product Designer"
              className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
            />
          </div>

          <div className="grid grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Department</label>
              <input
                required
                type="text"
                value={formData.department || ''}
                onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                placeholder="e.g. Engineering"
                className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
              />
            </div>
            <div className="space-y-2">
              <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Location</label>
              <input
                required
                type="text"
                value={formData.location || ''}
                onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                placeholder="e.g. Remote or City, State"
                className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Employment Type</label>
              <select
                value={formData.type || 'Full-time'}
                onChange={(e) => setFormData({ ...formData, type: e.target.value as any })}
                className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
              >
                <option value="Full-time">Full-time</option>
                <option value="Contract">Contract</option>
                <option value="Remote">Remote</option>
              </select>
            </div>
            <div className="space-y-2">
              <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Status</label>
              <select
                value={formData.status || 'Draft'}
                onChange={(e) => setFormData({ ...formData, status: e.target.value as any })}
                className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
              >
                <option value="Draft">Draft</option>
                <option value="Open">Open</option>
                <option value="Interviewing">Interviewing</option>
                <option value="Closed">Closed</option>
                <option value="Rejected">Rejected</option>
              </select>
            </div>
          </div>

          <div className="flex justify-end gap-4 pt-6">
            <button
              type="button"
              onClick={onClose}
              className="h-14 px-8 rounded-2xl text-sm font-bold uppercase tracking-widest text-muted-foreground hover:text-foreground transition-all"
            >
              Cancel
            </button>
            <button
              type="submit"
              className="h-14 px-10 rounded-2xl bg-primary text-primary-foreground text-sm font-bold uppercase tracking-widest hover:bg-primary/90 transition-all shadow-xl shadow-primary/20"
            >
              {isEditing ? 'Update Position' : 'Publish Position'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function AddCandidateModal({ isOpen, onClose, onSubmit, formData, setFormData, availableRoles }: { 
  isOpen: boolean, 
  onClose: () => void, 
  onSubmit: (e: React.FormEvent) => void,
  formData: any,
  setFormData: any,
  availableRoles: string[]
}) {
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/40 backdrop-blur-md p-4 animate-in fade-in duration-300">
      <div className="w-full max-w-lg rounded-[2rem] border border-border bg-card p-10 shadow-2xl animate-in zoom-in-95 duration-300">
        <div className="flex items-center justify-between mb-8">
          <h2 className="font-serif text-3xl font-bold text-foreground">Add Candidate</h2>
          <button onClick={onClose} className="rounded-full p-2 hover:bg-muted text-muted-foreground transition-colors">
            <X size={24} />
          </button>
        </div>

        <form onSubmit={onSubmit} className="space-y-6">
          <div className="space-y-2">
            <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Full Name</label>
            <input
              required
              type="text"
              value={formData.name || ''}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              placeholder="e.g. John Doe"
              className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
            />
          </div>

          <div className="space-y-2">
            <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Email Address</label>
            <input
              required
              type="email"
              value={formData.email || ''}
              onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              placeholder="e.g. john.doe@example.com"
              className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
            />
          </div>

          <div className="grid grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Applied Role</label>
              <select
                required
                value={formData.role || ''}
                onChange={(e) => setFormData({ ...formData, role: e.target.value })}
                className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
              >
                <option value="" disabled>Select a role</option>
                {availableRoles.map(role => (
                  <option key={role} value={role}>{role}</option>
                ))}
                <option value="Other">Other</option>
              </select>
            </div>
            <div className="space-y-2">
              <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Experience</label>
              <input
                required
                type="text"
                value={formData.experience || ''}
                onChange={(e) => setFormData({ ...formData, experience: e.target.value })}
                placeholder="e.g. 5 years"
                className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
              />
            </div>
          </div>

          <div className="space-y-2">
            <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1">Application Status</label>
            <select
              value={formData.status || 'Applied'}
              onChange={(e) => setFormData({ ...formData, status: e.target.value as any })}
              className="h-14 w-full rounded-2xl border-none bg-muted px-6 text-sm font-medium focus:ring-2 focus:ring-primary/20 transition-all text-foreground"
            >
              <option value="Applied">Applied</option>
              <option value="Screening">Screening</option>
              <option value="Interview">Interview</option>
              <option value="Offer">Offer</option>
              <option value="Hired">Hired</option>
              <option value="Rejected">Rejected</option>
            </select>
          </div>

          <div className="flex justify-end gap-4 pt-6">
            <button
              type="button"
              onClick={onClose}
              className="h-14 px-8 rounded-2xl text-sm font-bold uppercase tracking-widest text-muted-foreground hover:text-foreground transition-all"
            >
              Cancel
            </button>
            <button
              type="submit"
              className="h-14 px-10 rounded-2xl bg-primary text-primary-foreground text-sm font-bold uppercase tracking-widest hover:bg-primary/90 transition-all shadow-xl shadow-primary/20"
            >
              Add Candidate
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function RecruitmentStatCard({ title, value, icon: Icon, trend, trendColor = "text-slate-500", onClick }: { title: string, value: string, icon: any, trend: string, trendColor?: string, onClick?: () => void }) {
  return (
    <div 
      onClick={onClick}
      className={cn(
        "group rounded-3xl border border-border bg-card p-6 shadow-sm transition-all duration-300",
        onClick && "cursor-pointer hover:shadow-xl hover:-translate-y-1 hover:border-primary/20"
      )}
    >
      <div className="flex items-center justify-between mb-4">
        <div className="p-3 rounded-2xl bg-muted text-muted-foreground group-hover:bg-primary/10 group-hover:text-primary transition-colors">
          <Icon size={24} />
        </div>
      </div>
      <div>
        <p className="text-sm font-bold uppercase tracking-widest text-muted-foreground mb-1">{title}</p>
        <p className="text-3xl font-serif font-bold text-foreground">{value}</p>
        <p className={cn("text-xs mt-2 font-medium", trendColor)}>{trend}</p>
      </div>
    </div>
  );
}
