"use client";

import { useState } from "react";
import { Sparkles, CheckCircle, AlertTriangle, TrendingUp, XCircle, Minus, Loader2 } from "lucide-react";
import { generateCandidateAIScore } from "@/app/actions/aiScoring";

interface AIRecommendationProps {
    application: any;
    job: any;
    candidateSkills?: string[];
    jobSkills?: string[];
}

function getRecommendation(matchScore: number | null | undefined) {
    if (!matchScore) return null;

    if (matchScore >= 85) {
        return {
            title: "STRONG HIRE",
            confidence: Math.min(98, matchScore + 5),
            color: "from-emerald-500 to-green-600",
            borderColor: "border-emerald-200",
            bgColor: "bg-emerald-50",
            textColor: "text-emerald-900",
            description: "This candidate is an exceptional fit for the role.",
            action: "Extend offer quickly. High-quality candidates typically have multiple offers.",
        };
    }
    if (matchScore >= 70) {
        return {
            title: "RECOMMEND HIRE",
            confidence: matchScore,
            color: "from-blue-500 to-indigo-600",
            borderColor: "border-blue-200",
            bgColor: "bg-blue-50",
            textColor: "text-blue-900",
            description: "This candidate is a strong match with minor gaps that are trainable.",
            action: "Schedule final interview to assess cultural alignment.",
        };
    }
    if (matchScore >= 50) {
        return {
            title: "CONSIDER",
            confidence: matchScore,
            color: "from-amber-500 to-orange-500",
            borderColor: "border-amber-200",
            bgColor: "bg-amber-50",
            textColor: "text-amber-900",
            description: "This candidate shows potential but has notable gaps in key requirements.",
            action: "Review alongside stronger candidates before proceeding.",
        };
    }
    return {
        title: "NOT RECOMMENDED",
        confidence: 100 - matchScore,
        color: "from-red-500 to-rose-600",
        borderColor: "border-red-200",
        bgColor: "bg-red-50",
        textColor: "text-red-900",
        description: "This candidate doesn't meet the minimum requirements for this role.",
        action: "Consider for other open positions or reject with constructive feedback.",
    };
}

export function AIRecommendation({ application, job, candidateSkills = [], jobSkills = [] }: AIRecommendationProps) {
    const [isGenerating, setIsGenerating] = useState(false);

    const handleGenerateScore = async () => {
        setIsGenerating(true);
        try {
            await generateCandidateAIScore(application.id);
        } catch (error) {
            console.error(error);
        } finally {
            setIsGenerating(false);
        }
    };

    const matchScore = application.match_score;
    const recommendation = getRecommendation(matchScore);

    if (!recommendation) {
        return (
            <div className="rounded-2xl border-2 border-slate-200 bg-white overflow-hidden p-6 text-center">
                <div className="mx-auto w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mb-3">
                    <Sparkles className="w-6 h-6 text-slate-400" />
                </div>
                <h3 className="font-bold text-slate-800 mb-2">AI Match Score</h3>
                <p className="text-sm text-slate-500 mb-4 text-balance">
                    Generate an AI-powered analysis of the candidate's skills, experience, and overall fit for this role.
                </p>
                <button
                    onClick={handleGenerateScore}
                    disabled={isGenerating}
                    className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-primary text-white rounded-xl font-bold hover:bg-primary/90 transition-colors disabled:opacity-50"
                >
                    {isGenerating ? (
                        <><Loader2 className="w-4 h-4 animate-spin" /> Analyzing Profile...</>
                    ) : (
                        <><Sparkles className="w-4 h-4" /> Generate Score</>
                    )}
                </button>
            </div>
        );
    }

    // ─── Skill Gap Analysis ───
    const candidateSkillsLower = candidateSkills.map((s) => s.toLowerCase());
    const skillAnalysis = jobSkills.map((jobSkill) => {
        const lower = jobSkill.toLowerCase();
        const exactMatch = candidateSkillsLower.includes(lower);
        // Partial: check if any candidate skill contains this or vice versa
        const partialMatch = !exactMatch && candidateSkillsLower.some(
            (cs) => cs.includes(lower) || lower.includes(cs)
        );
        return {
            name: jobSkill,
            status: exactMatch ? "match" : partialMatch ? "partial" : "missing" as "match" | "partial" | "missing",
        };
    });

    const matchedCount = skillAnalysis.filter((s) => s.status === "match").length;
    const partialCount = skillAnalysis.filter((s) => s.status === "partial").length;
    const missingCount = skillAnalysis.filter((s) => s.status === "missing").length;
    const skillFitPercent = jobSkills.length > 0
        ? Math.round(((matchedCount + partialCount * 0.5) / jobSkills.length) * 100)
        : null;

    // Build strengths/considerations
    const strengths: string[] = [];
    const considerations: string[] = [];

    if (skillFitPercent !== null && skillFitPercent >= 70) {
        strengths.push(`${matchedCount}/${jobSkills.length} required skills matched`);
    } else if (matchScore && matchScore >= 70) {
        strengths.push("Skills align with job requirements");
    }
    if (application.cover_letter) strengths.push("Detailed cover letter submitted");
    if (application.resume_url) strengths.push("Resume provided");
    if (application.years_of_experience && application.years_of_experience >= 3) {
        strengths.push(`${application.years_of_experience} years of experience`);
    }

    if (missingCount > 0) considerations.push(`${missingCount} required skill${missingCount > 1 ? "s" : ""} missing`);
    if (!application.cover_letter) considerations.push("No cover letter submitted");
    if (skillFitPercent !== null && skillFitPercent < 50) {
        considerations.push("Low overall skill fit");
    }

    return (
        <div className={`rounded-2xl border-2 ${recommendation.borderColor} ${recommendation.bgColor} overflow-hidden`}>
            {/* Header */}
            <div className={`bg-gradient-to-r ${recommendation.color} px-6 py-4`}>
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center">
                            <Sparkles className="w-5 h-5 text-white" />
                        </div>
                        <div>
                            <p className="text-xs font-bold text-white/80 uppercase tracking-widest">
                                AI Recommendation
                            </p>
                            <p className="text-xl font-extrabold text-white mt-0.5">
                                {recommendation.title}
                            </p>
                        </div>
                    </div>
                    <div className="text-right">
                        <p className="text-xs text-white/70">Confidence</p>
                        <p className="text-2xl font-extrabold text-white">
                            {Math.round(recommendation.confidence)}%
                        </p>
                    </div>
                </div>
            </div>

            {/* Body */}
            <div className="p-5 space-y-4">
                <p className={`text-sm ${recommendation.textColor} leading-relaxed`}>
                    {recommendation.description}
                </p>

                {/* Skill Gap Grid */}
                {skillAnalysis.length > 0 && (
                    <div>
                        <div className="flex items-center justify-between mb-2">
                            <p className="text-xs font-bold text-slate-500 uppercase tracking-wider">
                                Skill Match
                            </p>
                            {skillFitPercent !== null && (
                                <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${skillFitPercent >= 70
                                    ? "bg-emerald-100 text-emerald-700"
                                    : skillFitPercent >= 40
                                        ? "bg-amber-100 text-amber-700"
                                        : "bg-red-100 text-red-700"
                                    }`}>
                                    {skillFitPercent}% fit
                                </span>
                            )}
                        </div>
                        <div className="space-y-1">
                            {skillAnalysis.map((skill, i) => (
                                <div
                                    key={i}
                                    className="flex items-center gap-2 py-1 px-2 rounded-lg text-xs"
                                >
                                    {skill.status === "match" ? (
                                        <CheckCircle className="w-3.5 h-3.5 text-emerald-500 flex-shrink-0" />
                                    ) : skill.status === "partial" ? (
                                        <Minus className="w-3.5 h-3.5 text-amber-500 flex-shrink-0" />
                                    ) : (
                                        <XCircle className="w-3.5 h-3.5 text-red-400 flex-shrink-0" />
                                    )}
                                    <span className={`font-medium ${skill.status === "match"
                                        ? "text-emerald-700"
                                        : skill.status === "partial"
                                            ? "text-amber-700"
                                            : "text-red-500"
                                        }`}>
                                        {skill.name}
                                    </span>
                                    <span className="text-[10px] text-slate-400 ml-auto">
                                        {skill.status === "match"
                                            ? "Matched"
                                            : skill.status === "partial"
                                                ? "Partial"
                                                : "Missing"}
                                    </span>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Strengths */}
                {strengths.length > 0 && (
                    <div>
                        <p className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">
                            Key Strengths
                        </p>
                        <div className="space-y-1.5">
                            {strengths.map((s, i) => (
                                <div key={i} className="flex items-center gap-2 text-sm text-emerald-700">
                                    <CheckCircle className="w-3.5 h-3.5 flex-shrink-0" />
                                    {s}
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Considerations */}
                {considerations.length > 0 && (
                    <div>
                        <p className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">
                            Considerations
                        </p>
                        <div className="space-y-1.5">
                            {considerations.map((c, i) => (
                                <div key={i} className="flex items-center gap-2 text-sm text-amber-700">
                                    <AlertTriangle className="w-3.5 h-3.5 flex-shrink-0" />
                                    {c}
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Action */}
                <div className="p-3 bg-white rounded-xl border border-slate-100">
                    <div className="flex items-start gap-2">
                        <TrendingUp className={`w-4 h-4 mt-0.5 flex-shrink-0 ${recommendation.textColor}`} />
                        <p className="text-sm text-slate-700">
                            <strong>Action:</strong> {recommendation.action}
                        </p>
                    </div>
                </div>

                <p className="text-[10px] text-slate-400 italic">
                    AI recommendation is one input. Final decisions should involve human judgment.
                </p>
            </div>
        </div>
    );
}
