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
} from 'lucide-react';

const getLanguageFlag = (lang) => {
    const flags = {
        'English': '🇬🇧',
        'Arabic': '🇦🇪',
        'Tagalog': '🇵🇭',
        'Hindi': '🇮🇳',
        'Swahili': '🇰🇪',
        'French': '🇫🇷',
        'Indonesian': '🇮🇩'
    };
    return flags[lang] || '🌐';
};

export default function Shortlist({ shortlistedWorkers }) {
    const { t } = useTranslation();
    const [workers, setWorkers] = useState(shortlistedWorkers || []);
    
    // Comparison & Quick Preview State
    const [comparisonIds, setComparisonIds] = useState([]);
    const [previewWorker, setPreviewWorker] = useState(null);

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

    const comparedWorkers = useMemo(() => {
        return workers.filter(w => comparisonIds.includes(w.id));
    }, [workers, comparisonIds]);

    return (
        <EmployerLayout title={t('my_shortlist', 'My Shortlist')}>
            <Head title={`${t('shortlist', 'Shortlist')} - ${t('employer_portal', 'Employer Portal')}`} />

            <div className="space-y-6 select-none pb-16">
                <div className="flex items-center justify-between">
                    <p className="text-xs text-slate-500 font-medium">
                        {t('candidates_saved', 'You have {count} candidates saved for review').split('{count}')[0]}
                        <span className="text-slate-900 font-bold">{workers.length}</span>
                        {t('candidates_saved', 'You have {count} candidates saved for review').split('{count}')[1]}
                    </p>
                    <Link
                        href="/employer/workers"
                        className="text-xs font-bold text-[#185FA5] hover:underline flex items-center space-x-1"
                    >
                        <span>{t('browse_more', 'Browse more workers')}</span>
                    </Link>
                </div>

                {workers.length > 0 ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        {workers.map((worker) => {
                            const isComparing = comparisonIds.includes(worker.id);

                            return (
                                <div key={worker.id} className="bg-white rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-all flex flex-col justify-between overflow-hidden group relative">
                                    
                                    {/* Card Header with Photo Option and Availability indicator */}
                                    <div className="bg-slate-50/50 p-6 border-b border-slate-100 flex items-start justify-between relative">
                                        <div className="flex items-center space-x-3.5">
                                            {/* Photo (optional) container */}
                                            <div className="w-14 h-14 rounded-2xl bg-blue-100 text-[#185FA5] flex items-center justify-center font-bold text-xl border border-blue-200 shadow-inner flex-shrink-0 overflow-hidden relative">
                                                {worker.photo ? (
                                                    <img src={worker.photo} alt={worker.name} className="w-full h-full object-cover" />
                                                ) : (
                                                    <User className="w-6 h-6 text-slate-400" />
                                                )}
                                            </div>
                                            
                                            <div className="truncate">
                                                <div className="font-extrabold text-base text-slate-900 group-hover:text-[#185FA5] transition-colors truncate flex items-center space-x-1.5">
                                                    <span>{worker.name}</span>
                                                    {worker.verified && (
                                                        <span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-[8px] font-black uppercase tracking-wider bg-emerald-500 text-white shadow-xs gap-0.5" title="OCR Verified">
                                                            <CheckCircle2 className="w-3 h-3" />
                                                            <span>{t('verified', 'Verified')}</span>
                                                        </span>
                                                    )}
                                                </div>
                                                
                                                {/* Passport Status Verification Badge & Visa Status */}
                                                <div className="flex flex-wrap gap-1 mt-0.5">
                                                    <div className={`flex items-center space-x-1 text-[9px] font-black uppercase px-1.5 py-0.5 rounded border ${
                                                        worker.passport_status.toLowerCase().includes('pending')
                                                            ? 'text-amber-700 bg-amber-50 border-amber-200'
                                                            : 'text-emerald-700 bg-emerald-50 border-emerald-100'
                                                    }`}>
                                                        <ShieldCheck className={`w-3 h-3 flex-shrink-0 ${
                                                             worker.passport_status.toLowerCase().includes('pending')
                                                                 ? 'text-amber-600'
                                                                 : 'text-emerald-600'
                                                         }`} />
                                                        <span>{worker.passport_status}</span>
                                                    </div>
                                                    {worker.visa_status && (worker.visa_status.toLowerCase().includes('tourist') || worker.visa_status.toLowerCase().includes('visit')) ? (
                                                        <div className="flex items-center space-x-1 text-[9px] font-black uppercase text-amber-700 bg-amber-50 px-1.5 py-0.5 rounded border border-amber-200">
                                                            <AlertTriangle className="w-3 h-3 text-amber-600 flex-shrink-0 animate-bounce" />
                                                            <span>{worker.visa_status} ({t('warning', 'Warning')})</span>
                                                        </div>
                                                    ) : worker.visa_status && worker.visa_status.toLowerCase().includes('cancelled') ? (
                                                        <div className="flex items-center space-x-1 text-[9px] font-black uppercase text-rose-700 bg-rose-50 px-1.5 py-0.5 rounded border border-rose-200 animate-pulse">
                                                            <AlertTriangle className="w-3 h-3 text-rose-600 flex-shrink-0" />
                                                            <span>{worker.visa_status} ({t('warning', 'Warning')})</span>
                                                        </div>
                                                    ) : (
                                                        <div className="flex items-center space-x-1 text-[9px] font-black uppercase text-blue-700 bg-blue-50 px-1.5 py-0.5 rounded border border-blue-100">
                                                            <span>{worker.visa_status}</span>
                                                        </div>
                                                    )}
                                                </div>
                                                
                                                <div className="flex items-center space-x-1.5 text-xs text-slate-500 mt-1">
                                                    <Globe2 className="w-3.5 h-3.5 text-slate-400" />
                                                    <span className="font-bold">{worker.nationality}</span>
                                                    <span>•</span>
                                                    <span>{worker.age} yrs</span>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Top Right Availability status and trash remove button */}
                                        <div className="flex flex-col items-end space-y-2">
                                            <button
                                                type="button"
                                                onClick={() => removeWorker(worker.id)}
                                                className="p-2 bg-rose-50 text-rose-600 hover:bg-rose-100 rounded-xl transition-colors border border-rose-100"
                                                title={t('remove_from_shortlist', 'Remove from shortlist')}
                                            >
                                                <Trash2 className="w-3.5 h-3.5" />
                                            </button>
                                        </div>
                                    </div>

                                    {/* Card Body */}
                                    <div className="p-6 space-y-4 flex-1 flex flex-col justify-between">
                                        <div className="space-y-4">
                                            
                                            {/* Category Pill, Ratings & Cost */}
                                            <div className="flex items-center justify-between text-xs">
                                                <span className="px-2.5 py-1 bg-blue-50 text-[#185FA5] font-black rounded-lg border border-blue-100 uppercase tracking-wider text-[9px]">
                                                    {worker.category}
                                                </span>
                                                <div className="flex items-center space-x-1 font-bold text-slate-800">
                                                    <DollarSign className="w-3.5 h-3.5 text-emerald-600" />
                                                    <span className="text-sm font-black">{worker.salary} AED</span>
                                                    <span className="text-[10px] text-slate-400 font-medium">/mo</span>
                                                </div>
                                            </div>


                                            {/* Details Table */}
                                            <div className="grid grid-cols-2 gap-2.5 p-3.5 bg-slate-50 rounded-xl text-[11px] text-slate-600 font-bold">
                                                <div className="flex items-center space-x-1.5 truncate">
                                                    <Briefcase className="w-3.5 h-3.5 text-slate-400 flex-shrink-0" />
                                                    <span className="truncate">Exp: {worker.experience}</span>
                                                </div>
                                                <div className="flex items-center space-x-1.5 truncate">
                                                    <Sparkles className="w-3.5 h-3.5 text-slate-400 flex-shrink-0" />
                                                    <span className="truncate uppercase text-[10px]">{worker.preferred_job_type}</span>
                                                </div>
                                                <div className="flex items-center space-x-1.5 truncate col-span-2">
                                                    <Star className="w-3.5 h-3.5 text-amber-500 flex-shrink-0 fill-amber-500" />
                                                    <span className="truncate">{worker.rating || '4.5'} ({worker.reviews_count || '12'} reviews)</span>
                                                </div>
                                            </div>

                                            {/* Core exact platform Skills List */}
                                            <div className="space-y-1">
                                                <div className="text-[9px] font-black text-slate-400 uppercase tracking-widest">{t('platform_skills', 'Platform Skills')}</div>
                                                <div className="flex flex-wrap gap-1">
                                                    {worker.skills?.map(skill => (
                                                        <span key={skill} className="px-2.5 py-0.5 bg-blue-50 border border-blue-100 text-[#185FA5] text-[9px] font-black rounded-lg uppercase tracking-wider">
                                                            {skill}
                                                        </span>
                                                    ))}
                                                </div>
                                            </div>

                                            {/* Languages Badges with Visual Flags */}
                                            <div className="space-y-1">
                                                <div className="text-[9px] font-black text-slate-400 uppercase tracking-widest">{t('languages_spoken', 'Languages Spoken')}</div>
                                                <div className="flex flex-wrap gap-1.5">
                                                    {worker.languages?.map(lang => (
                                                        <span key={lang} className="text-[9px] bg-slate-100 text-slate-700 px-2 py-0.5 rounded font-bold uppercase flex items-center space-x-1 border border-slate-200">
                                                            <span>{getLanguageFlag(lang)}</span>
                                                            <span>{lang}</span>
                                                        </span>
                                                    ))}
                                                </div>
                                            </div>
                                        </div>

                                        {/* Actions block */}
                                        <div className="pt-4 border-t border-slate-100 space-y-2">
                                            <div className="grid grid-cols-2 gap-2">
                                                <button
                                                    type="button"
                                                    onClick={() => setPreviewWorker(worker)}
                                                    className="w-full bg-slate-50 border border-slate-200 hover:bg-slate-100 text-slate-700 rounded-xl h-10 font-bold text-xs flex items-center justify-center transition-colors space-x-1"
                                                >
                                                    <Eye className="w-3.5 h-3.5" />
                                                    <span>{t('quick_preview', 'Quick Preview')}</span>
                                                </button>

                                                <button
                                                    type="button"
                                                    onClick={() => handleToggleComparison(worker.id)}
                                                    className={`w-full rounded-xl h-10 font-bold text-xs flex items-center justify-center transition-colors border ${
                                                        isComparing 
                                                            ? 'bg-purple-600 border-purple-600 text-white hover:bg-purple-700' 
                                                            : 'bg-white border-slate-200 hover:bg-slate-50 text-slate-700'
                                                    }`}
                                                >
                                                    {isComparing ? t('comparing_active', 'Comparing ✓') : t('compare_candidate', 'Compare Candidate')}
                                                </button>
                                            </div>

                                            <div className="grid grid-cols-2 gap-2">
                                                <Link
                                                    href={`/employer/workers/${worker.id}`}
                                                    className="w-full bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl h-10 font-bold text-xs flex items-center justify-center transition-colors"
                                                >
                                                    {t('open_profile', 'Open Profile')}
                                                </Link>
                                                <Link
                                                    href={`/employer/messages/${worker.id}`}
                                                    className="w-full bg-[#185FA5] hover:bg-[#144f8a] text-white rounded-xl h-10 font-bold text-xs flex items-center justify-center space-x-1.5 transition-colors shadow-xs"
                                                >
                                                    <MessageSquare className="w-4 h-4" />
                                                    <span>{t('message', 'Message')}</span>
                                                </Link>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                ) : (
                    <div className="text-center py-16 bg-white rounded-2xl border border-slate-200 shadow-sm space-y-3">
                        <SlidersHorizontal className="w-12 h-12 text-slate-300 mx-auto" />
                        <div className="text-base font-bold text-slate-800">{t('shortlist_empty', 'Your shortlist is empty')}</div>
                        <p className="text-xs text-slate-500 max-w-sm mx-auto">
                            {t('shortlist_empty_desc', 'Explore candidate profiles and add them to your saved shortlist.')}
                        </p>
                        <Link
                            href="/employer/workers"
                            className="inline-block mt-2 bg-[#185FA5] text-white px-6 py-2.5 rounded-xl text-xs font-bold shadow-sm hover:bg-[#144f8a] transition-colors"
                        >
                            {t('find_workers_now', 'Find Workers Now')}
                        </Link>
                    </div>
                )}

                {/* Worker Comparison Drawer */}
                {comparisonIds.length > 0 && (
                    <div className="fixed bottom-0 left-0 right-0 bg-white border-t-2 border-[#185FA5] shadow-2xl p-6 z-50 animate-slide-up flex flex-col space-y-4 max-w-7xl mx-auto rounded-t-3xl">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-2">
                                <span className="w-2.5 h-2.5 rounded-full bg-[#185FA5] animate-ping" />
                                <h4 className="font-extrabold text-sm text-slate-900">{t('comparing_workers', 'Comparing Workers')} ({comparedWorkers.length} of 3)</h4>
                            </div>
                            <button 
                                onClick={() => setComparisonIds([])}
                                className="text-xs font-bold text-rose-600 hover:underline flex items-center space-x-1"
                            >
                                <X className="w-4 h-4" />
                                <span>{t('clear_all', 'Clear all')}</span>
                            </button>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                            {comparedWorkers.map(w => (
                                <div key={w.id} className="bg-slate-50 border border-slate-200 rounded-2xl p-4 space-y-3 relative">
                                    <button 
                                        onClick={() => handleToggleComparison(w.id)}
                                        className="absolute top-2 right-2 text-slate-400 hover:text-slate-600"
                                    >
                                        <X className="w-4 h-4" />
                                    </button>

                                    <div className="flex items-center space-x-2">
                                        <div className="w-8 h-8 rounded-full bg-blue-100 text-[#185FA5] font-black text-xs flex items-center justify-center overflow-hidden">
                                            {w.photo ? (
                                                <img src={w.photo} alt={w.name} className="w-full h-full object-cover" />
                                            ) : (
                                                <span>{w.name.charAt(0)}</span>
                                            )}
                                        </div>
                                        <div>
                                            <div className="font-bold text-xs text-slate-900 truncate max-w-[120px]">{w.name}</div>
                                            <div className="text-[10px] text-slate-500 font-bold">{w.nationality} • {w.category}</div>
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-2 gap-2 text-[10px] bg-white p-2.5 rounded-xl border border-slate-100 font-bold text-slate-600">
                                        <div>Salary: <span className="text-slate-800">{w.salary} AED</span></div>
                                        <div>Age: <span className="text-slate-800">{w.age} yrs</span></div>
                                        <div>Job Type: <span className="text-slate-800 uppercase">{w.preferred_job_type}</span></div>
                                        <div>Status: <span className="text-slate-800 font-black">{w.availability_status}</span></div>
                                    </div>

                                    {/* Skills Display in Comparison */}
                                    <div className="space-y-1">
                                        <div className="text-[8px] font-black text-slate-400 uppercase tracking-wider">Skills</div>
                                        <div className="flex flex-wrap gap-1">
                                            {w.skills?.map(skill => (
                                                <span key={skill} className="px-1.5 py-0.5 bg-blue-50 border border-blue-100 text-[#185FA5] text-[8px] font-black rounded uppercase tracking-wider">
                                                    {skill}
                                                </span>
                                            ))}
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Quick Preview Modal overlay */}
                {previewWorker && (
                    <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 z-50 animate-fade-in">
                        <div className="bg-white rounded-3xl w-full max-w-lg border border-slate-200 shadow-2xl p-6 relative animate-zoom-in space-y-6">
                            <button
                                onClick={() => setPreviewWorker(null)}
                                className="absolute top-4 right-4 p-2 bg-slate-50 hover:bg-slate-100 rounded-full text-slate-400 hover:text-slate-600 transition-colors"
                            >
                                <X className="w-5 h-5" />
                            </button>

                            <div className="flex items-center space-x-4">
                                <div className="w-16 h-16 bg-blue-50 text-[#185FA5] rounded-2xl border border-blue-100 font-black text-2xl flex items-center justify-center shadow-inner overflow-hidden flex-shrink-0">
                                    {previewWorker.photo ? (
                                        <img src={previewWorker.photo} alt={previewWorker.name} className="w-full h-full object-cover" />
                                    ) : (
                                        <User className="w-8 h-8 text-slate-400" />
                                    )}
                                </div>
                                <div>
                                    <div className="flex items-center space-x-1">
                                        <h4 className="font-extrabold text-lg text-slate-900">{previewWorker.name}</h4>
                                        {previewWorker.verified && <CheckCircle2 className="w-4 h-4 text-emerald-600" />}
                                    </div>
                                    
                                    <div className={`flex items-center space-x-1 font-black text-[9px] uppercase tracking-wider ${
                                         previewWorker.passport_status?.toLowerCase().includes('pending')
                                             ? 'text-amber-700 bg-amber-50 border border-amber-200 px-1.5 py-0.5 rounded'
                                             : 'text-emerald-700 bg-emerald-50 border border-emerald-100 px-1.5 py-0.5 rounded'
                                     }`}>
                                         <ShieldCheck className={`w-3.5 h-3.5 flex-shrink-0 ${
                                             previewWorker.passport_status?.toLowerCase().includes('pending')
                                                 ? 'text-amber-600'
                                                 : 'text-emerald-600'
                                         }`} />
                                         <span>{previewWorker.passport_status}</span>
                                     </div>
                                    <div className="text-xs text-slate-500 font-bold">{previewWorker.nationality} • {previewWorker.category}</div>
                                </div>
                            </div>

                            {previewWorker.bio ? (
                                <p className="text-xs text-slate-600 italic bg-slate-50 p-4 rounded-xl leading-relaxed">
                                    "{previewWorker.bio}"
                                </p>
                            ) : (
                                <p className="text-xs text-slate-400 italic bg-slate-50 p-4 rounded-xl leading-relaxed">
                                    {t('no_bio_provided', 'No bio details provided.')}
                                </p>
                            )}

                            <div className="grid grid-cols-2 gap-4 text-xs font-bold text-slate-600">
                                <div className="p-3 bg-slate-50/50 rounded-xl">
                                    <div className="text-[10px] text-slate-400 uppercase tracking-widest mb-0.5">{t('expectations', 'Expectations')}</div>
                                    <div className="text-slate-800">{previewWorker.salary} AED / mo</div>
                                </div>
                                <div className="p-3 bg-slate-50/50 rounded-xl">
                                    <div className="text-[10px] text-slate-400 uppercase tracking-widest mb-0.5">{t('job_preference', 'Job Preference')}</div>
                                    <div className="text-slate-800 uppercase text-[10px] mt-1">{previewWorker.preferred_job_type}</div>
                                </div>
                                <div className="p-3 bg-slate-50/50 rounded-xl col-span-2">
                                    <div className="text-[10px] text-slate-400 uppercase tracking-widest mb-0.5">{t('languages', 'Languages')}</div>
                                    <div className="flex flex-wrap gap-1.5 mt-1">
                                        {previewWorker.languages?.map(lang => (
                                            <span key={lang} className="text-[9px] bg-white border border-slate-200 text-slate-700 px-2 py-0.5 rounded font-bold flex items-center space-x-1">
                                                <span>{getLanguageFlag(lang)}</span>
                                                <span>{lang}</span>
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            </div>

                            {/* Core Platform Skills inside Quick Preview */}
                            <div className="space-y-1 pt-1">
                                <div className="text-[9px] font-black text-slate-400 uppercase tracking-widest">{t('platform_skills', 'Platform Skills')}</div>
                                <div className="flex flex-wrap gap-1">
                                    {previewWorker.skills?.map(skill => (
                                        <span key={skill} className="px-2.5 py-0.5 bg-blue-50 border border-blue-100 text-[#185FA5] text-[9px] font-black rounded-lg uppercase tracking-wider">
                                            {skill}
                                        </span>
                                    ))}
                                </div>
                            </div>

                            <div className="flex items-center space-x-3 pt-2">
                                <button
                                    onClick={() => removeWorker(previewWorker.id)}
                                    className="flex-1 border border-rose-200 hover:bg-rose-50 text-rose-600 rounded-xl h-11 text-xs font-bold flex items-center justify-center space-x-2"
                                >
                                    <Trash2 className="w-4 h-4" />
                                    <span>{t('remove_shortlist', 'Remove Shortlist')}</span>
                                </button>
                                <Link
                                    href={`/employer/workers/${previewWorker.id}`}
                                    className="flex-1 bg-[#185FA5] hover:bg-[#144f8a] text-white rounded-xl h-11 text-xs font-black flex items-center justify-center shadow-xs"
                                >
                                    {t('view_full_details', 'View Full Details')}
                                </Link>
                            </div>
                        </div>
                    </div>
                )}

            </div>
        </EmployerLayout>
    );
}
