import React, { useState, useMemo } from 'react'; import { Head, Link, router } from '@inertiajs/react'; import EmployerLayout from '../../Layouts/EmployerLayout'; import { useTranslation } from '../../lib/LanguageContext'; import { CheckCircle2, Globe2, Briefcase, DollarSign, MessageSquare, Trash2, SlidersHorizontal, ShieldCheck, AlertTriangle, Sparkles, Star, Eye, User, X, HeartHandshake, CheckCircle, MapPin, Calendar, Search, RotateCcw, ArrowUpDown } from 'lucide-react'; import FilterDrawer, { FilterSection, FilterSelect, FilterInput, FilterChips, FilterCheckboxList } from '../../components/Employer/FilterDrawer'; const getLanguageFlag = (lang) => { const flags = { 'English': '🇬🇧', 'Arabic': '🇦🇪', 'Tagalog': '🇵🇭', 'Hindi': '🇮🇳', 'Swahili': '🇰🇪', 'French': '🇫🇷', 'Indonesian': '🇮🇩' }; return flags[lang] || '🌐'; }; export default function Shortlist({ shortlistedWorkers, filtersMetadata = {} }) { const { t } = useTranslation(); const [workers, setWorkers] = useState(shortlistedWorkers || []); // Comparison & Quick Preview State const [comparisonIds, setComparisonIds] = useState([]); const [previewWorker, setPreviewWorker] = useState(null); // Basic Filters const [searchQuery, setSearchQuery] = useState(''); const [selectedProfession, setSelectedProfession] = useState('All Professions'); const [selectedNationalities, setSelectedNationalities] = useState([]); const [selectedGender, setSelectedGender] = useState('All Genders'); const [selectedExperience, setSelectedExperience] = useState('All Experience'); const [selectedReligion, setSelectedReligion] = useState('All Religions'); const [maxSalary, setMaxSalary] = useState(5000); // Advanced Multi-Select Filters & Sorting const [selectedLanguages, setSelectedLanguages] = useState([]); const [selectedVisaStatuses, setSelectedVisaStatuses] = useState([]); const [selectedSkills, setSelectedSkills] = useState([]); const [selectedWorkTypes, setSelectedWorkTypes] = useState([]); const [sortBy, setSortBy] = useState('default'); // Advanced Filters Toggle & Details const [filterLocation, setFilterLocation] = useState('All'); const [filterJobType, setFilterJobType] = useState('All'); const [filterAccommodation, setFilterAccommodation] = useState('All'); const [filterInCountry, setFilterInCountry] = useState('All'); const [filterVisaType, setFilterVisaType] = useState('All'); // Drawer const [drawerOpen, setDrawerOpen] = useState(false); const resetFilters = () => { setSearchQuery(''); setSelectedProfession('All Professions'); setSelectedNationalities([]); setSelectedGender('All Genders'); setSelectedExperience('All Experience'); setSelectedReligion('All Religions'); setMaxSalary(5000); setSelectedLanguages([]); setSelectedVisaStatuses([]); setSelectedSkills([]); setSelectedWorkTypes([]); setSortBy('default'); setFilterLocation('All'); setFilterJobType('All'); setFilterAccommodation('All'); setFilterInCountry('All'); setFilterVisaType('All'); }; const activeFilterCount = useMemo(() => { let count = 0; if (filterLocation !== 'All' && filterLocation.trim() !== '') count++; if (filterJobType !== 'All') count++; if (filterAccommodation !== 'All') count++; if (selectedNationalities.length > 0) count++; if (selectedGender !== 'All Genders') count++; if (selectedProfession !== 'All Professions') count++; if (filterInCountry !== 'All') count++; if (filterInCountry === 'In Country' && filterVisaType !== 'All') count++; if (selectedSkills.length > 0) count++; if (selectedLanguages.length > 0) count++; if (maxSalary < 5000) count++; return count; }, [filterLocation, filterJobType, filterAccommodation, selectedNationalities, selectedGender, selectedProfession, filterInCountry, filterVisaType, selectedSkills, selectedLanguages, maxSalary]); const activeFilterTags = useMemo(() => { const tags = []; if (filterLocation !== 'All' && filterLocation.trim()) tags.push({ key: 'loc', label: `📍 ${filterLocation}`, clear: () => setFilterLocation('All') }); if (filterJobType !== 'All') tags.push({ key: 'job', label: `💼 ${filterJobType}`, clear: () => setFilterJobType('All') }); if (filterAccommodation !== 'All') tags.push({ key: 'acc', label: `🏠 ${filterAccommodation.replace('_', '-')}`, clear: () => setFilterAccommodation('All') }); if (selectedNationalities.length > 0) tags.push({ key: 'nat', label: `🌍 ${selectedNationalities.length} Nat`, clear: () => setSelectedNationalities([]) }); if (selectedGender !== 'All Genders') tags.push({ key: 'gender', label: `🚻 ${selectedGender}`, clear: () => setSelectedGender('All Genders') }); if (selectedProfession !== 'All Professions') tags.push({ key: 'profession', label: `🧑‍🔧 ${selectedProfession}`, clear: () => setSelectedProfession('All Professions') }); if (filterInCountry !== 'All') tags.push({ key: 'country', label: `✈️ ${filterInCountry}`, clear: () => { setFilterInCountry('All'); setFilterVisaType('All'); } }); if (filterInCountry === 'In Country' && filterVisaType !== 'All') tags.push({ key: 'visa', label: `🪪 ${filterVisaType}`, clear: () => setFilterVisaType('All') }); if (selectedSkills.length > 0) tags.push({ key: 'skills', label: `🛠 ${selectedSkills.length} skill${selectedSkills.length > 1 ? 's' : ''}`, clear: () => setSelectedSkills([]) }); if (selectedLanguages.length > 0) tags.push({ key: 'lang', label: `🗣 ${selectedLanguages.length} lang`, clear: () => setSelectedLanguages([]) }); if (maxSalary < 5000) tags.push({ key: 'salary', label: `💰 < ${maxSalary} AED`, clear: () => setMaxSalary(5000) }); return tags; }, [filterLocation, filterJobType, filterAccommodation, selectedNationalities, selectedGender, selectedProfession, filterInCountry, filterVisaType, selectedSkills, selectedLanguages, maxSalary]); const toggleMultiSelect = (item, setSelectedList) => { setSelectedList(prev => prev.includes(item) ? prev.filter(x => x !== item) : [...prev, item] ); }; const removeWorker = (id) => { // Optimistic UI state update setWorkers(workers.filter(w => w.id !== id)); setComparisonIds(comparisonIds.filter(i => i !== id)); // Persist change to database router.post(`/employer/shortlist/${id}/remove`, {}, { preserveScroll: true }); }; const handleToggleComparison = (id) => { if (comparisonIds.includes(id)) { setComparisonIds(comparisonIds.filter(i => i !== id)); } else { if (comparisonIds.length >= 3) { alert(t('max_compare_alert', 'You can compare a maximum of 3 candidates.')); return; } setComparisonIds([...comparisonIds, id]); } }; // Filter and Sort Worker List const filteredWorkers = useMemo(() => { let list = [...workers]; list = list.filter(worker => { // Search Query if (searchQuery.trim() !== '') { const query = searchQuery.toLowerCase(); const matchName = worker.name.toLowerCase().includes(query); const matchBio = worker.bio?.toLowerCase().includes(query) || false; const matchSkills = worker.skills?.some(s => s.toLowerCase().includes(query)) || false; if (!matchName && !matchBio && !matchSkills) return false; } // Dropdown filters if (selectedProfession !== 'All Professions' && (!worker.main_profession || worker.main_profession.toLowerCase() !== selectedProfession.toLowerCase())) return false; if (selectedNationalities.length > 0 && (!worker.nationality || !selectedNationalities.map(n => n.toLowerCase()).includes(worker.nationality.toLowerCase()))) return false; if (selectedGender !== 'All Genders' && worker.gender && worker.gender.toLowerCase() !== selectedGender.toLowerCase()) return false; if (selectedExperience !== 'All Experience' && worker.experience !== selectedExperience) return false; if (selectedReligion !== 'All Religions' && worker.religion !== selectedReligion) return false; if (maxSalary < 5000 && worker.salary > maxSalary) return false; // Multi-select filters if (selectedLanguages.length > 0) { const hasLang = worker.languages?.some(l => selectedLanguages.includes(l)); if (!hasLang) return false; } if (selectedSkills.length > 0) { const hasSkill = worker.skills?.some(s => selectedSkills.includes(s.toLowerCase())); if (!hasSkill) return false; } if (selectedVisaStatuses.length > 0) { if (!selectedVisaStatuses.includes(worker.visa_status)) return false; } if (selectedWorkTypes.length > 0 && !selectedWorkTypes.includes(worker.preferred_job_type)) return false; // Preferred Location if (filterLocation !== 'All' && filterLocation.trim() !== '') { const locKey = filterLocation.toLowerCase(); const locationMapping = { 'dubai': ['dubai', 'marina', 'barsha', 'nahda', 'jumeirah', 'deira', 'downtown', 'silicon', 'sports', 'motor', 'jlt', 'jbr', 'meydan', 'ranches', 'bay', 'mirdif', 'quoz'], 'abu dhabi': ['abu dhabi', 'yas', 'khalifa', 'reem', 'saadiyat', 'raha', 'mussafah', 'zahiyah', 'karamah'], 'oman': ['oman', 'muscat', 'salalah', 'sohar', 'nizwa', 'sur', 'ibri', 'rustaq'] }; const allowedKeywords = locationMapping[locKey] || [locKey]; if (!worker.preferred_location) return false; const wLoc = worker.preferred_location.toLowerCase(); const matched = allowedKeywords.some(keyword => wLoc.includes(keyword)); if (!matched) return false; } // Job Type if (filterJobType !== 'All') { if (!worker.preferred_job_type || worker.preferred_job_type.toLowerCase() !== filterJobType.toLowerCase()) return false; } // Accommodation if (filterAccommodation !== 'All') { if (!worker.live_in_out || worker.live_in_out.toLowerCase() !== filterAccommodation.toLowerCase()) return false; } // In/Out Country if (filterInCountry !== 'All') { const wantInCountry = filterInCountry === 'In Country'; const wVal = worker.in_country; if ((wVal === true || wVal === '1' || wVal === 1) !== wantInCountry) return false; } // Visa Type (if in country) if (filterInCountry === 'In Country' && filterVisaType !== 'All') { if (!worker.visa_status || !worker.visa_status.toLowerCase().includes(filterVisaType.toLowerCase())) return false; } return true; }); // Sorting if (sortBy === 'salary_asc') { list.sort((a, b) => a.salary - b.salary); } else if (sortBy === 'salary_desc') { list.sort((a, b) => b.salary - a.salary); } else if (sortBy === 'rating') { list.sort((a, b) => b.rating - a.rating); } else if (sortBy === 'experience') { list.sort((a, b) => { const parseAge = (val) => { if (!val) return 0; if (typeof val === 'number') return val; const num = parseInt(val, 10); return isNaN(num) ? 0 : num; }; return parseAge(b.age) - parseAge(a.age); }); } return list; }, [ workers, searchQuery, selectedProfession, selectedNationalities, selectedGender, selectedExperience, selectedReligion, maxSalary, selectedLanguages, selectedVisaStatuses, selectedSkills, selectedWorkTypes, sortBy, filterLocation, filterJobType, filterAccommodation, filterInCountry, filterVisaType ]); const comparedWorkers = useMemo(() => { return workers.filter(w => comparisonIds.includes(w.id)); }, [workers, comparisonIds]); return (

{t('candidates_saved', 'You have {count} candidates saved for review').split('{count}')[0]} {workers.length} {t('candidates_saved', 'You have {count} candidates saved for review').split('{count}')[1]}

{t('browse_more', 'Browse more workers')}
{/* ── Filter Drawer ── */} setDrawerOpen(false)} onReset={resetFilters} activeCount={activeFilterCount} title="Filter Saved Workers" > {/* Profession */} {filtersMetadata.professions && ( setSelectedProfession(e.target.value)} > {filtersMetadata.professions.map(prof => ( ))} )} {/* Preferred Location */} setFilterLocation(e.target.value)} > {/* Job Type */} {/* Accommodation */} {/* Nationality */} {filtersMetadata.nationalities?.length > 1 && ( n !== 'All Nationalities')} selected={selectedNationalities} onToggle={nat => toggleMultiSelect(nat, setSelectedNationalities)} /> )} {/* Gender */} {/* Country Status */} { setFilterInCountry(val); if (val !== 'In Country') setFilterVisaType('All'); }} /> {/* Visa Type */}
setFilterVisaType(e.target.value)} disabled={filterInCountry !== 'In Country'} > {filterInCountry !== 'In Country' && (

Select "In Country" to enable this filter

)}
{/* Skills */} {filtersMetadata.skills?.length > 1 && ( s.toLowerCase())} selected={selectedSkills} onToggle={skill => toggleMultiSelect(skill, setSelectedSkills)} /> )} {/* Languages */} {filtersMetadata.languages?.length > 1 && ( toggleMultiSelect(lang, setSelectedLanguages)} /> )} {/* Salary Range */} setMaxSalary(Number(e.target.value))} className="w-full accent-[#185FA5]" />
500 AED 5,000 AED
{/* Filter and Search Panel */}
{/* Search */}
setSearchQuery(e.target.value)} placeholder={t('search_by_name_skills_bio', 'Search by name, skills, bio...')} className="w-full pl-11 pr-4 py-3 rounded-xl border border-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-[#185FA5]/20 focus:border-[#185FA5]" />
{/* Sort */}
{/* Reset */} {/* Filter Drawer button */}
{/* Active filter tags */} {activeFilterTags.length > 0 && (
Active: {activeFilterTags.map(tag => ( ))}
)}
{/* Listing metadata bar */}
{t('found_workers_matching', 'Found {count} workers matching your preferences') .split('{count}')[0]} {filteredWorkers.length} {t('found_workers_matching', 'Found {count} workers matching your preferences') .split('{count}')[1] || ''}
{t('direct_sponsoring_active', 'Direct Sponsorship Active')}
{workers.length > 0 ? ( filteredWorkers.length > 0 ? (
{filteredWorkers.map((worker) => { const isComparing = comparisonIds.includes(worker.id); return (
{/* Card Header with Photo Option and Availability indicator */}
{/* Photo (optional) container */}
{worker.photo ? ( {worker.name} ) : ( )}
{worker.name} {worker.main_profession && ( {worker.main_profession} )}
{/* Passport Status Verification Badge & Visa Status */}
{worker.visa_status && (worker.visa_status.toLowerCase().includes('tourist') || worker.visa_status.toLowerCase().includes('visit')) ? (
{worker.visa_status}
) : worker.visa_status && worker.visa_status.toLowerCase().includes('cancelled') ? (
{worker.visa_status}
) : (
{worker.visa_status}
)}
{worker.nationality} {worker.age} yrs
{/* Top Right Actions & Salary */}
{worker.salary} AED
/mo
{/* Card Body */}
{/* Details Table */}
Exp: {worker.experience}
{worker.preferred_job_type}
{worker.preferred_location || 'Not Specified'}
{worker.rating || '4.5'} ({worker.reviews_count || '12'})
{/* Core exact platform Skills List */}
{t('platform_skills', 'Platform Skills')}
{worker.skills?.slice(0, 3).map(skill => ( {skill} ))} {worker.skills?.length > 3 && ( +{worker.skills.length - 3} More )}
{/* Languages Badges with Visual Flags */}
{t('languages_spoken', 'Languages Spoken')}
{worker.languages?.map(lang => ( {getLanguageFlag(lang)} {lang} ))}
{/* Actions block */}
{t('open_profile', 'Open Profile')} {t('message', 'Message')}
); })}
) : (
{t('no_matching_results', 'No matching saved workers')}

{t('no_matching_results_desc', 'Try clearing or modifying your filters to find your saved candidates.')}

) ) : (
{t('shortlist_empty', 'Your shortlist is empty')}

{t('shortlist_empty_desc', 'Explore candidate profiles and add them to your saved shortlist.')}

{t('find_workers_now', 'Find Workers Now')}
)} {/* Worker Comparison Drawer */} {comparisonIds.length > 0 && (

{t('comparing_workers', 'Comparing Workers')} ({comparedWorkers.length} of 3)

{comparedWorkers.map(w => (
{w.photo ? ( {w.name} ) : ( {w.name.charAt(0)} )}
{w.name}
{w.nationality}
Salary: {w.salary} AED
Age: {w.age} yrs
Job Type: {w.preferred_job_type}
Location: {w.preferred_location || 'Not Specified'}
{/* Skills Display in Comparison */}
Skills
{w.skills?.map(skill => ( {skill} ))}
))}
)} {/* Quick Preview Modal overlay */} {previewWorker && (
{previewWorker.photo ? ( {previewWorker.name} ) : ( )}

{previewWorker.name}

{previewWorker.visa_expiry_date ? (
Visa Exp: {previewWorker.visa_expiry_date}
) : (
Visa Expiry Pending
)}
{previewWorker.nationality}
{t('expectations', 'Expectations')}
{previewWorker.salary} AED / mo
{t('job_type', 'Job Type')}
{previewWorker.preferred_job_type}
{t('gender', 'Gender')}
{previewWorker.gender || 'Female'}
{t('visa_status', 'Visa Status')}
{previewWorker.visa_status || 'Residence Visa'}
{t('preferred_location', 'Preferred Location')}
{previewWorker.preferred_location || 'Not Specified'}
{t('languages', 'Languages')}
{previewWorker.languages?.map(lang => ( {getLanguageFlag(lang)} {lang} ))}
{/* Core Platform Skills inside Quick Preview */}
{t('platform_skills', 'Platform Skills')}
{previewWorker.skills?.map(skill => ( {skill} ))}
{t('view_full_details', 'View Full Details')}
)}
); }