import React, { useState } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import EmployerLayout from '@/Layouts/EmployerLayout';
import { 
    ArrowLeft, 
    MessageSquare, 
    CheckCircle2, 
    XCircle, 
    Globe2, 
    Briefcase, 
    DollarSign,
    MoreHorizontal,
    Search,
    Filter,
    ShieldCheck,
    Star,
    X,
    FileText
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';

export default function Applicants({ job, applicants: initialApplicants, isShortlistedOnly = false }) {
    const [searchTerm, setSearchTerm] = useState('');
    const [applicants, setApplicants] = useState(initialApplicants || []);
    
    // Modal states
    const [selectedApp, setSelectedApp] = useState(null);
    const [newStatus, setNewStatus] = useState('');
    const [notes, setNotes] = useState('');
    const [showModal, setShowModal] = useState(false);

    const filteredApplicants = applicants.filter(a => 
        a.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        a.nationality.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const openStatusModal = (app, statusPreset = '') => {
        setSelectedApp(app);
        setNewStatus(statusPreset || app.status || 'Applied');
        setNotes(app.notes || '');
        setShowModal(true);
    };

    const handleSaveStatus = () => {
        if (!selectedApp) return;

        router.post(`/employer/candidates/${selectedApp.application_id}/status`, {
            status: newStatus,
            notes: notes
        }, {
            onSuccess: () => {
                toast.success('Applicant status updated successfully.');
                setShowModal(false);
                setSelectedApp(null);
            },
            onError: (errors) => {
                toast.error('Failed to update status: ' + (errors.error || errors.status || 'Error occurred'));
            }
        });
    };

    const pageTitle = isShortlistedOnly ? 'Shortlisted Workers' : (job ? 'Job Applicants' : 'All Applicants');
    const headerTitle = isShortlistedOnly ? 'Shortlisted Workers' : (job ? `Applicants for ${job.title}` : 'All Job Applicants');

    return (
        <EmployerLayout title={pageTitle}>
            <Head title={pageTitle} />

            <div className="space-y-8 select-none pb-12">
                {/* Job Header Info */}
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
                    <div className="space-y-2">
                        <Link
                            href={job ? "/employer/jobs" : "/employer/dashboard"}
                            className="inline-flex items-center space-x-2 text-[10px] font-black text-[#185FA5] uppercase tracking-widest hover:translate-x-[-4px] transition-transform"
                        >
                            <ArrowLeft className="w-3.5 h-3.5" />
                            <span>{job ? 'Back to My Jobs' : 'Back to Dashboard'}</span>
                        </Link>
                        <h1 className="text-2xl font-black text-slate-900 tracking-tight">
                            {isShortlistedOnly ? (
                                <span>Shortlisted <span className="text-[#185FA5]">Workers</span></span>
                            ) : (
                                <span>Applicants for <span className="text-[#185FA5]">{job?.title || 'All Jobs'}</span></span>
                            )}
                        </h1>
                        {job && (
                            <div className="flex items-center space-x-3 text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                                <span className="flex items-center"><DollarSign className="w-3.5 h-3.5 mr-1" /> {job.salary} AED</span>
                            </div>
                        )}
                    </div>
                    
                    <div className="bg-white px-6 py-4 rounded-2xl border border-slate-200 shadow-sm flex items-center space-x-4 flex-shrink-0">
                        <div className="text-right">
                            <div className="text-[9px] font-black text-slate-400 uppercase tracking-widest">
                                {isShortlistedOnly ? 'Total Shortlisted' : (job ? 'Hiring Progress' : 'Total Applicants')}
                            </div>
                            <div className="text-lg font-black text-slate-900 tracking-tight">
                                {isShortlistedOnly ? (
                                    <span>{applicants.length} <span className="text-slate-300 text-sm">Workers</span></span>
                                ) : job ? (
                                    <span>{applicants.filter(a => a.status?.toLowerCase() === 'hired').length} / {job.workers_needed} <span className="text-slate-300 text-sm">Positions</span></span>
                                ) : (
                                    <span>{applicants.length} <span className="text-slate-300 text-sm">Applicants</span></span>
                                )}
                            </div>
                        </div>
                        <div className="w-12 h-12 rounded-xl bg-blue-50 flex items-center justify-center">
                            <Star className="w-6 h-6 text-[#185FA5]" />
                        </div>
                    </div>
                </div>

                {/* Filters */}
                <div className="bg-white p-4 rounded-2xl border border-slate-200 shadow-sm flex flex-col sm:flex-row gap-4">
                    <div className="relative flex-1">
                        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                        <input 
                            type="text" 
                            placeholder="Find applicant by name or nationality..."
                            className="w-full pl-11 pr-4 py-2.5 bg-slate-50 border border-slate-100 rounded-xl text-xs font-bold text-slate-900 focus:ring-4 focus:ring-blue-500/10 focus:border-[#185FA5] outline-none transition-all"
                            value={searchTerm}
                            onChange={e => setSearchTerm(e.target.value)}
                        />
                    </div>
                    <button className="flex items-center justify-center space-x-2 px-6 py-2.5 bg-white border border-slate-200 rounded-xl text-[10px] font-black text-slate-600 hover:bg-slate-50 transition-colors uppercase tracking-widest">
                        <Filter className="w-3.5 h-3.5" />
                        <span>Filter Matches</span>
                    </button>
                </div>

                {/* Applicants Grid */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {filteredApplicants.length > 0 ? (
                        filteredApplicants.map((applicant) => (
                            <div key={applicant.id} className="bg-white rounded-[24px] border border-slate-200 shadow-sm overflow-hidden flex flex-col group hover:shadow-md transition-all">
                                <div className="p-6 space-y-5">
                                    {/* Applicant Header */}
                                    <div className="flex items-start justify-between">
                                        <div className="flex items-center space-x-3">
                                            <div className="w-12 h-12 rounded-full bg-blue-50 text-[#185FA5] flex items-center justify-center font-bold text-lg border-2 border-white shadow-sm ring-1 ring-slate-100">
                                                {applicant.name.charAt(0)}
                                            </div>
                                            <div>
                                                <h3 className="font-bold text-slate-900 group-hover:text-[#185FA5] transition-colors line-clamp-1 flex items-center gap-1.5">
                                                    <span>{applicant.name}</span>
                                                    {applicant.is_saved && (
                                                        <Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400 flex-shrink-0" />
                                                    )}
                                                </h3>
                                                <div className="flex items-center space-x-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest mt-0.5">
                                                    <Globe2 className="w-3.5 h-3.5" />
                                                    <span>{applicant.nationality}</span>
                                                </div>
                                                {applicant.job_title && (
                                                    <div className="text-[10px] text-slate-500 font-bold mt-1">
                                                        Applied: <span className="text-[#185FA5]">{applicant.job_title}</span>
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                        <div className="flex flex-col items-end space-y-1">
                                            <div className="flex items-center space-x-1 text-emerald-600 font-black text-[10px] bg-emerald-50 px-2 py-0.5 rounded-full">
                                                <ShieldCheck className="w-3 h-3" />
                                                <span>{applicant.match_score}% Match</span>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Stats Grid */}
                                    <div className="grid grid-cols-2 gap-3 p-4 bg-slate-50/50 rounded-2xl border border-slate-50">
                                        <div className="space-y-1">
                                            <div className="text-[8px] font-black text-slate-400 uppercase tracking-widest">Experience</div>
                                            <div className="text-[11px] font-bold text-slate-700">{applicant.experience}</div>
                                        </div>
                                        <div className="space-y-1">
                                            <div className="text-[8px] font-black text-slate-400 uppercase tracking-widest">Expected Pay</div>
                                            <div className="text-[11px] font-bold text-slate-700">{applicant.salary} AED</div>
                                        </div>
                                    </div>

                                    {/* Internal Notes Preview */}
                                    {applicant.notes && (
                                        <div className="p-3 bg-blue-50/50 rounded-xl border border-blue-50 text-[10px] text-slate-600 italic">
                                            <FileText className="w-3 h-3 inline mr-1 text-[#185FA5]" />
                                            {applicant.notes}
                                        </div>
                                    )}

                                    {/* Current Status Badge */}
                                    <div className="flex items-center justify-between">
                                        <span className={`px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest cursor-pointer hover:opacity-85 transition-opacity ${
                                            applicant.status?.toLowerCase() === 'hired' ? 'bg-emerald-100 text-emerald-700' :
                                            applicant.status?.toLowerCase() === 'rejected' ? 'bg-rose-100 text-rose-700' :
                                            'bg-amber-100 text-amber-700'
                                        }`} onClick={() => openStatusModal(applicant)}>
                                            {applicant.status}
                                        </span>
                                        <div className="flex items-center space-x-1 text-[10px] font-bold text-slate-400">
                                            <Link href={`/employer/workers/${applicant.id}`} className="hover:text-[#185FA5] flex items-center underline underline-offset-2">
                                                View Full Profile
                                            </Link>
                                        </div>
                                    </div>
                                </div>

                                {/* Actions Bar */}
                                <div className="p-4 bg-slate-50 border-t border-slate-100 flex items-center space-x-2">
                                    <Link 
                                        href={`/employer/messages/start/${applicant.id}`}
                                        className="flex-1 bg-white border border-slate-200 text-[#185FA5] hover:bg-blue-50 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all flex items-center justify-center space-x-2"
                                    >
                                        <MessageSquare className="w-3.5 h-3.5" />
                                        <span>Chat</span>
                                    </Link>
                                    <button 
                                        onClick={() => openStatusModal(applicant)}
                                        className="p-2.5 bg-[#185FA5] text-white hover:bg-[#144f8a] rounded-xl transition-all shadow-sm shadow-blue-500/10"
                                        title="Change Status / Hire"
                                    >
                                        <CheckCircle2 className="w-4 h-4" />
                                    </button>
                                    <button 
                                        onClick={() => openStatusModal(applicant, 'Rejected')}
                                        className="p-2.5 bg-white border border-slate-200 text-rose-500 hover:bg-rose-50 rounded-xl transition-all"
                                        title="Reject Candidate"
                                    >
                                        <XCircle className="w-4 h-4" />
                                    </button>
                                </div>
                            </div>
                        ))
                    ) : (
                        <div className="col-span-full py-20 text-center">
                            <Briefcase className="w-12 h-12 text-slate-200 mx-auto mb-3" />
                            <p className="text-xs font-bold text-slate-400 uppercase tracking-widest">No applicants found for this job yet.</p>
                        </div>
                    )}
                </div>
            </div>

            {/* Status Update Modal */}
            {showModal && (
                <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 transition-all">
                    <div className="bg-white w-full max-w-lg rounded-[28px] shadow-2xl border border-slate-100 overflow-hidden flex flex-col animate-in fade-in zoom-in-95 duration-200">
                        {/* Modal Header */}
                        <div className="p-6 border-b border-slate-100 flex items-center justify-between">
                            <div>
                                <h3 className="font-black text-slate-900 text-base">Update Application Status</h3>
                                <p className="text-[10px] font-bold text-[#185FA5] uppercase tracking-widest mt-0.5">{selectedApp?.name}</p>
                            </div>
                            <button 
                                onClick={() => { setShowModal(false); setSelectedApp(null); }}
                                className="p-2 hover:bg-slate-50 text-slate-400 hover:text-slate-950 rounded-full transition-colors"
                            >
                                <X className="w-5 h-5" />
                            </button>
                        </div>

                        {/* Modal Body */}
                        <div className="p-6 space-y-5">
                            {/* Status Selector */}
                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Select Stage</label>
                                <select 
                                    value={newStatus} 
                                    onChange={(e) => setNewStatus(e.target.value)}
                                    className="w-full px-4 py-3 bg-slate-50 border border-slate-100 rounded-xl text-xs font-bold text-slate-900 focus:ring-4 focus:ring-blue-500/10 focus:border-[#185FA5] outline-none transition-all"
                                >
                                    <option value="Applied">Applied (Reviewing)</option>
                                    <option value="Shortlisted">Shortlisted (Save Candidate)</option>
                                    <option value="Contacted">Contacted</option>
                                    <option value="Interview Scheduled">Interview Scheduled</option>
                                    <option value="Selected">Selected</option>
                                    <option value="Rejected">Rejected</option>
                                    <option value="Hired">Hired</option>
                                </select>
                            </div>

                            {/* Notes Textarea */}
                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Internal Employer Notes</label>
                                <textarea 
                                    value={notes} 
                                    onChange={(e) => setNotes(e.target.value)}
                                    placeholder="Add any internal feedback, interview times, or notes about this candidate..."
                                    rows={4}
                                    className="w-full px-4 py-3 bg-slate-50 border border-slate-100 rounded-xl text-xs font-medium text-slate-900 placeholder-slate-400 focus:ring-4 focus:ring-blue-500/10 focus:border-[#185FA5] outline-none transition-all resize-none"
                                />
                            </div>

                            {/* Status History Audit Trail */}
                            {selectedApp?.status_history && selectedApp.status_history.length > 0 && (
                                <div className="space-y-2 pt-2">
                                    <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Status Audit Log</label>
                                    <div className="max-h-24 overflow-y-auto space-y-2 pr-1 border border-slate-100 rounded-xl p-2 bg-slate-50/40">
                                        {selectedApp.status_history.map((hist, index) => (
                                            <div key={index} className="text-[9px] text-slate-500 flex justify-between items-start">
                                                <div>
                                                    <span className="font-bold uppercase text-[#185FA5]">{hist.status}</span>
                                                    {hist.notes && <span className="ml-1 text-slate-400 italic">({hist.notes})</span>}
                                                </div>
                                                <span className="text-[8px] font-mono text-slate-300">{new Date(hist.timestamp).toLocaleDateString()}</span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Modal Footer */}
                        <div className="p-6 bg-slate-50 border-t border-slate-100 flex items-center justify-end space-x-3">
                            <button 
                                onClick={() => { setShowModal(false); setSelectedApp(null); }}
                                className="px-5 py-2.5 bg-white border border-slate-200 hover:bg-slate-100 rounded-xl text-[10px] font-black uppercase tracking-widest text-slate-600 transition-colors"
                            >
                                Cancel
                            </button>
                            <button 
                                onClick={handleSaveStatus}
                                className="px-5 py-2.5 bg-[#185FA5] hover:bg-[#144f8a] text-white rounded-xl text-[10px] font-black uppercase tracking-widest transition-all shadow-md shadow-blue-500/10"
                            >
                                Save Status
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </EmployerLayout>
    );
}
