"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
    Star, ThumbsUp, ThumbsDown, AlertCircle, Loader2,
    CheckCircle2, Shield, MessageSquare, Brain, Users, Sparkles
} from "lucide-react";
import { submitScorecard } from "@/app/actions/interviewActions";

interface ScorecardFormProps {
    interviewId: string;
    interviewTitle: string;
    existingScorecard?: {
        technical_score?: number;
        communication_score?: number;
        problem_solving_score?: number;
        culture_fit_score?: number;
        overall_score?: number;
        recommendation?: string;
        strengths?: string;
        concerns?: string;
        additional_notes?: string;
    };
    onClose: () => void;
}

const CATEGORIES = [
    { key: "technical_score", label: "Technical Skills", icon: Shield, description: "Depth of technical knowledge, problem approach" },
    { key: "communication_score", label: "Communication", icon: MessageSquare, description: "Clarity, listening, articulation" },
    { key: "problem_solving_score", label: "Problem Solving", icon: Brain, description: "Analytical thinking, methodology" },
    { key: "culture_fit_score", label: "Culture Fit", icon: Users, description: "Team alignment, values, collaboration" },
    { key: "overall_score", label: "Overall", icon: Sparkles, description: "Overall impression and potential" },
];

const RECOMMENDATIONS = [
    { value: "strong_yes", label: "Strong Yes", emoji: "🔥", color: "bg-emerald-100 border-emerald-300 text-emerald-800" },
    { value: "yes", label: "Yes", emoji: "👍", color: "bg-green-100 border-green-300 text-green-800" },
    { value: "maybe", label: "Maybe", emoji: "🤔", color: "bg-amber-100 border-amber-300 text-amber-800" },
    { value: "no", label: "No", emoji: "👎", color: "bg-orange-100 border-orange-300 text-orange-800" },
    { value: "strong_no", label: "Strong No", emoji: "🚫", color: "bg-red-100 border-red-300 text-red-800" },
];

export function InterviewScorecardForm({
    interviewId,
    interviewTitle,
    existingScorecard,
    onClose,
}: ScorecardFormProps) {
    const router = useRouter();
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [success, setSuccess] = useState(false);

    const [scores, setScores] = useState<Record<string, number>>({
        technical_score: existingScorecard?.technical_score || 0,
        communication_score: existingScorecard?.communication_score || 0,
        problem_solving_score: existingScorecard?.problem_solving_score || 0,
        culture_fit_score: existingScorecard?.culture_fit_score || 0,
        overall_score: existingScorecard?.overall_score || 0,
    });
    const [recommendation, setRecommendation] = useState(existingScorecard?.recommendation || "");
    const [strengths, setStrengths] = useState(existingScorecard?.strengths || "");
    const [concerns, setConcerns] = useState(existingScorecard?.concerns || "");
    const [additionalNotes, setAdditionalNotes] = useState(existingScorecard?.additional_notes || "");

    const handleSubmit = async () => {
        setIsSubmitting(true);
        try {
            const result = await submitScorecard(interviewId, {
                technical_score: scores.technical_score || undefined,
                communication_score: scores.communication_score || undefined,
                problem_solving_score: scores.problem_solving_score || undefined,
                culture_fit_score: scores.culture_fit_score || undefined,
                overall_score: scores.overall_score || undefined,
                recommendation: recommendation || undefined,
                strengths: strengths || undefined,
                concerns: concerns || undefined,
                additional_notes: additionalNotes || undefined,
            });
            if (result.success) {
                setSuccess(true);
                setTimeout(() => {
                    router.refresh();
                    onClose();
                }, 1500);
            }
        } catch (error) {
            console.error("Scorecard submit failed:", error);
        } finally {
            setIsSubmitting(false);
        }
    };

    const avgScore = Object.values(scores).filter(Boolean).length > 0
        ? +(Object.values(scores).filter(Boolean).reduce((a, b) => a + b, 0) /
            Object.values(scores).filter(Boolean).length).toFixed(1)
        : 0;

    if (success) {
        return (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
                <div className="bg-white rounded-3xl p-10 max-w-md mx-4 shadow-2xl text-center space-y-4 animate-[fadeIn_0.3s_ease-out]">
                    <div className="w-16 h-16 mx-auto rounded-full bg-emerald-100 flex items-center justify-center">
                        <CheckCircle2 className="w-8 h-8 text-emerald-600" />
                    </div>
                    <h3 className="text-2xl font-extrabold text-slate-900">Scorecard Submitted!</h3>
                    <p className="text-sm text-slate-500">
                        Your evaluation has been saved successfully.
                    </p>
                </div>
            </div>
        );
    }

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
            <div className="bg-white rounded-3xl w-full max-w-2xl mx-4 shadow-2xl overflow-hidden max-h-[90vh] flex flex-col animate-[fadeIn_0.2s_ease-out]">
                {/* Header */}
                <div className="bg-gradient-to-r from-amber-500 to-orange-500 px-8 py-5">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-xs font-bold text-white/70 uppercase tracking-widest">
                                Interview Scorecard
                            </p>
                            <h2 className="text-lg font-extrabold text-white mt-0.5">
                                {interviewTitle}
                            </h2>
                        </div>
                        <button
                            onClick={onClose}
                            className="text-white/60 hover:text-white text-2xl font-bold transition-colors"
                        >
                            ×
                        </button>
                    </div>
                    {avgScore > 0 && (
                        <div className="mt-3 flex items-center gap-2">
                            <span className="text-white/60 text-xs font-bold">Average:</span>
                            <span className="text-white font-extrabold text-lg">{avgScore}</span>
                            <span className="text-white/40 text-sm">/5</span>
                        </div>
                    )}
                </div>

                {/* Body */}
                <div className="flex-1 overflow-y-auto p-6 md:p-8 space-y-6">
                    {/* Scoring Categories */}
                    {CATEGORIES.map((cat) => {
                        const CatIcon = cat.icon;
                        return (
                            <div key={cat.key}>
                                <div className="flex items-center gap-2 mb-2">
                                    <CatIcon className="w-4 h-4 text-slate-400" />
                                    <span className="text-sm font-bold text-slate-900">{cat.label}</span>
                                    <span className="text-xs text-slate-400">— {cat.description}</span>
                                </div>
                                <div className="flex gap-2">
                                    {[1, 2, 3, 4, 5].map((val) => (
                                        <button
                                            key={val}
                                            onClick={() => setScores({ ...scores, [cat.key]: val })}
                                            className={`flex-1 py-2.5 text-sm font-bold rounded-xl border-2 transition-all ${scores[cat.key] === val
                                                    ? "bg-amber-500 border-amber-500 text-white scale-105 shadow-md"
                                                    : scores[cat.key] >= val
                                                        ? "bg-amber-100 border-amber-200 text-amber-700"
                                                        : "bg-slate-50 border-slate-200 text-slate-400 hover:border-amber-300"
                                                }`}
                                        >
                                            {val}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        );
                    })}

                    {/* Recommendation */}
                    <div>
                        <p className="text-sm font-bold text-slate-900 mb-2">
                            <ThumbsUp className="w-4 h-4 inline mr-1" /> Recommendation
                        </p>
                        <div className="flex flex-wrap gap-2">
                            {RECOMMENDATIONS.map((rec) => (
                                <button
                                    key={rec.value}
                                    onClick={() => setRecommendation(rec.value)}
                                    className={`px-4 py-2 text-sm font-bold rounded-xl border-2 transition-all ${recommendation === rec.value
                                            ? `${rec.color} scale-105 shadow-sm`
                                            : "bg-white border-slate-200 text-slate-500 hover:border-slate-300"
                                        }`}
                                >
                                    {rec.emoji} {rec.label}
                                </button>
                            ))}
                        </div>
                    </div>

                    {/* Strengths */}
                    <div>
                        <label className="block text-sm font-bold text-slate-900 mb-1.5">
                            <CheckCircle2 className="w-4 h-4 inline mr-1 text-emerald-500" /> Key Strengths
                        </label>
                        <textarea
                            value={strengths}
                            onChange={(e) => setStrengths(e.target.value)}
                            rows={2}
                            placeholder="What stood out positively..."
                            className="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-300 focus:border-amber-400 outline-none resize-none"
                        />
                    </div>

                    {/* Concerns */}
                    <div>
                        <label className="block text-sm font-bold text-slate-900 mb-1.5">
                            <AlertCircle className="w-4 h-4 inline mr-1 text-amber-500" /> Concerns
                        </label>
                        <textarea
                            value={concerns}
                            onChange={(e) => setConcerns(e.target.value)}
                            rows={2}
                            placeholder="Areas of concern or improvement..."
                            className="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-300 focus:border-amber-400 outline-none resize-none"
                        />
                    </div>

                    {/* Additional Notes */}
                    <div>
                        <label className="block text-sm font-bold text-slate-900 mb-1.5">
                            Additional Notes
                        </label>
                        <textarea
                            value={additionalNotes}
                            onChange={(e) => setAdditionalNotes(e.target.value)}
                            rows={2}
                            placeholder="Any other observations..."
                            className="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-300 focus:border-amber-400 outline-none resize-none"
                        />
                    </div>
                </div>

                {/* Footer */}
                <div className="border-t border-slate-100 px-8 py-4 flex items-center justify-between bg-slate-50/50">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 text-sm font-semibold text-slate-600 hover:text-slate-900 transition-colors"
                    >
                        Cancel
                    </button>
                    <button
                        onClick={handleSubmit}
                        disabled={isSubmitting}
                        className="inline-flex items-center gap-1.5 px-6 py-2.5 bg-amber-500 text-white text-sm font-semibold rounded-xl hover:bg-amber-600 transition-colors disabled:opacity-50 shadow-sm"
                    >
                        {isSubmitting ? (
                            <><Loader2 className="w-4 h-4 animate-spin" /> Submitting...</>
                        ) : (
                            <><Star className="w-4 h-4" /> Submit Scorecard</>
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
}
