"use client";

import { useRouter, useSearchParams } from "next/navigation";

import { useMemo } from "react";
import Link from "next/link";
import {
    X, CheckCircle, XCircle, MapPin, Mail, Sparkles, Building2, GraduationCap, Clock
} from "lucide-react";

interface CompareCandidatesProps {
    applications: any[];
    jobId?: string;
    onRemove?: (id: string) => void;
}

export function CompareCandidates({ applications, jobId, onRemove }: CompareCandidatesProps) {
    const router = useRouter();
    const searchParams = useSearchParams();

    // Derived Data
    const jobSkills = useMemo(() => {
        if (!applications.length) return [];
        // Assuming all selected apps are for the same job
        return applications[0].job.skills.map((js: any) => js.skill.name);
    }, [applications]);

    const screeningQuestions = useMemo(() => {
        if (!applications.length) return [];
        return applications[0].job.screening_questions || [];
    }, [applications]);

    if (!applications || applications.length === 0) {
        return (
            <div className="flex flex-col items-center justify-center py-20 bg-slate-50 rounded-2xl border-2 border-dashed border-slate-200">
                <p className="text-slate-500 font-medium">No candidates selected for comparison.</p>
            </div>
        );
    }

    // Grid layout adjustments based on number of candidates
    // Supported: 2 to 4
    const colClass = applications.length === 4 ? "grid-cols-4" :
        applications.length === 3 ? "grid-cols-3" : "grid-cols-2";

    return (
        <div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
            <div className="overflow-x-auto">
                <div className="min-w-[800px]">
                    {/* --- Headers (Candidate Profile Summary) --- */}
                    <div className={`grid ${colClass} divide-x divide-slate-100 border-b border-slate-200 bg-slate-50/50`}>
                        {applications.map(app => {
                            const candidate = app.candidate;
                            const profile = candidate.profile;
                            const score = app.score?.overall_score || app.match_score || 0;

                            return (
                                <div key={app.id} className="relative p-6 pt-10">
                                    <button
                                        onClick={() => {
                                            if (onRemove) {
                                                onRemove(app.id);
                                                return;
                                            }
                                            const currentIds = searchParams.get("ids")?.split(",") || [];
                                            const newIds = currentIds.filter(cid => cid !== app.id);

                                            if (newIds.length < 2) {
                                                router.push(`/dashboard/employer/jobs/${jobId}/ats`);
                                            } else {
                                                router.push(`/dashboard/employer/jobs/${jobId}/compare?ids=${newIds.join(",")}`);
                                            }
                                        }}
                                        className="absolute top-4 right-4 p-1.5 text-slate-400 hover:bg-slate-200 hover:text-slate-700 rounded-lg transition-colors"
                                        title="Remove from comparison"
                                    >
                                        <X className="w-4 h-4" />
                                    </button>

                                    <div className="flex flex-col items-center text-center">
                                        <div className="w-16 h-16 rounded-full bg-gradient-to-br from-primary/80 to-accent flex items-center justify-center text-white text-xl font-bold mb-3 shadow-md">
                                            {(candidate.name || 'U').charAt(0).toUpperCase()}
                                        </div>
                                        <Link href={`/dashboard/applications/${app.id}`} className="hover:text-primary transition-colors">
                                            <h3 className="font-bold text-slate-900 text-lg line-clamp-1">{candidate.name}</h3>
                                        </Link>
                                        <p className="text-sm text-slate-500 line-clamp-1 mt-0.5">{profile?.headline || "No headline"}</p>

                                        <div className="mt-4 inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-bold border border-slate-200 bg-white">
                                            <Sparkles className={`w-4 h-4 ${score >= 80 ? 'text-emerald-500' : score >= 50 ? 'text-amber-500' : 'text-slate-400'}`} />
                                            <span>{Math.round(score)}% Match</span>
                                        </div>

                                        <div className="mt-3 text-xs font-semibold px-2 py-1 rounded bg-slate-100 text-slate-600 line-clamp-1">
                                            Stage: {app.current_stage?.name || 'Interview'}
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>

                    {/* --- Contact & Location --- */}
                    <SectionRow title="Contact & Location" applications={applications} colClass={colClass}>
                        {(app: any) => (
                            <div className="space-y-2 text-sm">
                                <div className="flex items-center gap-2 text-slate-600">
                                    <Mail className="w-4 h-4 text-slate-400 flex-shrink-0" />
                                    <span className="truncate">{app.candidate.email}</span>
                                </div>
                                <div className="flex items-center gap-2 text-slate-600">
                                    <MapPin className="w-4 h-4 text-slate-400 flex-shrink-0" />
                                    <span className="truncate">{app.candidate.profile?.location || "Not specified"}</span>
                                </div>
                            </div>
                        )}
                    </SectionRow>

                    {/* --- Fit Breakdown --- */}
                    <SectionRow title="AI Fit Analysis" applications={applications} colClass={colClass} bg="bg-slate-50/30">
                        {(app: any) => {
                            const score = app.score;
                            if (!score) return <span className="text-slate-400 text-sm">No detailed analysis available</span>;

                            return (
                                <div className="space-y-2 text-sm">
                                    {score.technical_fit !== null && (
                                        <ScoreBar label="Technical" value={score.technical_fit} />
                                    )}
                                    {score.experience_fit !== null && (
                                        <ScoreBar label="Experience" value={score.experience_fit} />
                                    )}
                                    {score.education_fit !== null && (
                                        <ScoreBar label="Education" value={score.education_fit} />
                                    )}
                                </div>
                            );
                        }}
                    </SectionRow>

                    {/* --- Experience --- */}
                    <SectionRow title="Latest Experience" applications={applications} colClass={colClass}>
                        {(app: any) => {
                            const exp = app.candidate.experiences?.[0];
                            if (!exp) return <span className="text-slate-400 text-sm">No experience listed</span>;

                            return (
                                <div>
                                    <p className="font-semibold text-slate-800 text-sm">{exp.title}</p>
                                    <div className="flex items-center gap-1.5 text-sm text-slate-600 mt-1">
                                        <Building2 className="w-3.5 h-3.5" />
                                        <span>{exp.company}</span>
                                    </div>
                                    <div className="flex items-center gap-1.5 text-xs text-slate-500 mt-1">
                                        <Clock className="w-3.5 h-3.5" />
                                        <span>
                                            {new Date(exp.start_date).getFullYear()} - {exp.is_current ? 'Present' : (exp.end_date ? new Date(exp.end_date).getFullYear() : 'N/A')}
                                        </span>
                                    </div>
                                </div>
                            );
                        }}
                    </SectionRow>

                    {/* --- Education --- */}
                    <SectionRow title="Education" applications={applications} colClass={colClass} bg="bg-slate-50/30">
                        {(app: any) => {
                            const edu = app.candidate.education?.[0];
                            if (!edu) return <span className="text-slate-400 text-sm">No education listed</span>;

                            return (
                                <div>
                                    <p className="font-semibold text-slate-800 text-sm line-clamp-2">{edu.degree}</p>
                                    <div className="flex items-start gap-1.5 text-sm text-slate-600 mt-1">
                                        <GraduationCap className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
                                        <span className="line-clamp-2">{edu.institution}</span>
                                    </div>
                                </div>
                            );
                        }}
                    </SectionRow>

                    {/* --- Skills Validation --- */}
                    <SectionRow title="Required Job Skills" applications={applications} colClass={colClass}>
                        {(app: any) => {
                            const candidateSkills = (app.candidate.skills || []).map((s: any) => s.skill.name.toLowerCase());
                            return (
                                <div className="space-y-1.5">
                                    {jobSkills.length > 0 ? (
                                        jobSkills.map((js: string) => {
                                            const hasSkill = candidateSkills.includes(js.toLowerCase());
                                            return (
                                                <div key={js} className="flex items-center gap-2 text-sm">
                                                    {hasSkill ? (
                                                        <CheckCircle className="w-4 h-4 text-emerald-500 flex-shrink-0" />
                                                    ) : (
                                                        <XCircle className="w-4 h-4 text-red-400 flex-shrink-0" />
                                                    )}
                                                    <span className={hasSkill ? 'text-slate-700 font-medium' : 'text-slate-500'}>
                                                        {js}
                                                    </span>
                                                </div>
                                            );
                                        })
                                    ) : (
                                        <span className="text-sm text-slate-400">No skills required for this job.</span>
                                    )}
                                </div>
                            );
                        }}
                    </SectionRow>

                    {/* --- Screening Questions --- */}
                    {screeningQuestions.map((q: any, index: number) => (
                        <SectionRow
                            key={q.id || index}
                            title={`Q: ${q.question_text}`}
                            applications={applications}
                            colClass={colClass}
                            bg={index % 2 === 0 ? "bg-slate-50/30" : "bg-white"}
                        >
                            {(app: any) => {
                                const answerObj = app.answers ? (app.answers as Record<string, any>)[q.id] : null;
                                const answerText = answerObj ?
                                    (Array.isArray(answerObj) ? answerObj.join(', ') : String(answerObj)) :
                                    "No response";

                                return (
                                    <p className={`text-sm ${answerObj ? 'text-slate-700' : 'text-slate-400 italic'}`}>
                                        {answerText}
                                    </p>
                                );
                            }}
                        </SectionRow>
                    ))}

                </div>
            </div>
        </div>
    );
}

// Helper Components
function SectionRow({ title, applications, colClass, children, bg = "bg-white" }: any) {
    return (
        <div className={`border-b border-slate-100 last:border-0 ${bg}`}>
            <div className="px-6 py-3 border-b border-slate-100 bg-slate-50/50">
                <h4 className="text-xs font-bold text-slate-500 uppercase tracking-wider">{title}</h4>
            </div>
            <div className={`grid ${colClass} divide-x divide-slate-100`}>
                {applications.map((app: any) => (
                    <div key={app.id} className="p-6">
                        {children(app)}
                    </div>
                ))}
            </div>
        </div>
    );
}

function ScoreBar({ label, value }: { label: string, value: number }) {
    return (
        <div className="flex items-center justify-between gap-2">
            <span className="text-slate-600 flex-1">{label}</span>
            <div className="w-24 h-2 bg-slate-100 rounded-full overflow-hidden flex-shrink-0">
                <div
                    className={`h-full ${value >= 80 ? 'bg-emerald-500' : value >= 50 ? 'bg-amber-500' : 'bg-red-500'}`}
                    style={{ width: `${Math.max(0, Math.min(100, value))}%` }}
                />
            </div>
            <span className="text-xs font-bold text-slate-700 w-8 text-right">{Math.round(value)}%</span>
        </div>
    );
}
