"use client";

import { useState } from "react";
import { AlertTriangle, X, Check, Loader2, ChevronDown } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

export interface ConfirmMoveData {
    rejectionReason?: string;
    sendEmail: boolean;
    note: string;
    keepInTalentPool?: boolean;
}

interface ConfirmMoveModalProps {
    candidateName: string;
    fromStage: string;
    toStage: string;
    toStageType: string; // "rejected" | "offer" | "hired" | etc.
    isBackwardMove?: boolean;
    blockers?: string[];
    onConfirm: (data: ConfirmMoveData) => void;
    onCancel: () => void;
}

const REJECTION_REASONS = [
    "Not qualified for this role",
    "Position has been filled",
    "Candidate withdrew",
    "Failed interview",
    "Compensation mismatch",
    "Location or availability issue",
    "Culture fit concerns",
    "Other",
];

export function ConfirmMoveModal({
    candidateName,
    fromStage,
    toStage,
    toStageType,
    isBackwardMove = false,
    blockers = [],
    onConfirm,
    onCancel,
}: ConfirmMoveModalProps) {
    const [rejectionReason, setRejectionReason] = useState("");
    const [sendEmail, setSendEmail] = useState(true);
    const [note, setNote] = useState("");
    const [keepInPool, setKeepInPool] = useState(false);
    const [loading, setLoading] = useState(false);
    const [confirmed, setConfirmed] = useState(false);

    const isRejection = toStageType === "rejected";
    const isOffer = toStageType === "offer";
    const hasBlockers = blockers.length > 0;

    const handleConfirm = async () => {
        if (isRejection && !rejectionReason) return;
        if (isBackwardMove && !confirmed) return;
        setLoading(true);
        await onConfirm({ rejectionReason, sendEmail, note, keepInTalentPool: keepInPool });
        setLoading(false);
    };

    const headerColor = isRejection
        ? "from-red-500 to-rose-600"
        : isOffer
            ? "from-emerald-500 to-green-600"
            : isBackwardMove
                ? "from-amber-500 to-orange-500"
                : "from-primary to-blue-600";

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="absolute inset-0 bg-black/50 backdrop-blur-sm"
                onClick={onCancel}
            />
            <motion.div
                initial={{ opacity: 0, scale: 0.95, y: 10 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95, y: 10 }}
                transition={{ type: "spring", damping: 25, stiffness: 300 }}
                className="relative bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden"
            >
                {/* Header gradient */}
                <div className={`bg-gradient-to-r ${headerColor} px-6 py-5`}>
                    <div className="flex items-start justify-between">
                        <div>
                            <p className="text-xs text-white/70 font-bold uppercase tracking-widest mb-1">
                                {isRejection ? "Reject Candidate" : isOffer ? "Move to Offer" : isBackwardMove ? "⚠️ Backward Move" : "Confirm Move"}
                            </p>
                            <p className="text-lg font-extrabold text-white">{candidateName}</p>
                            <p className="text-sm text-white/70 mt-0.5">
                                {fromStage} → <span className="text-white font-bold">{toStage}</span>
                            </p>
                        </div>
                        <button onClick={onCancel} className="p-2 bg-white/20 hover:bg-white/30 rounded-lg transition-colors">
                            <X className="w-4 h-4 text-white" />
                        </button>
                    </div>
                </div>

                <div className="p-5 space-y-4">
                    {/* Blockers */}
                    {hasBlockers && (
                        <div className="p-3 bg-red-50 border border-red-200 rounded-xl">
                            <div className="flex items-start gap-2">
                                <AlertTriangle className="w-4 h-4 text-red-500 flex-shrink-0 mt-0.5" />
                                <div>
                                    <p className="text-sm font-bold text-red-800 mb-1">Requirements not met:</p>
                                    <ul className="text-xs text-red-700 space-y-0.5">
                                        {blockers.map((b, i) => <li key={i}>• {b}</li>)}
                                    </ul>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* Backward move confirmation */}
                    {isBackwardMove && !hasBlockers && (
                        <div className="p-3 bg-amber-50 border border-amber-200 rounded-xl">
                            <p className="text-sm text-amber-800">
                                <AlertTriangle className="w-4 h-4 inline mr-1.5 text-amber-600" />
                                You're moving this candidate backward. This is unusual — please confirm it's intentional.
                            </p>
                            <label className="flex items-center gap-2 mt-3 cursor-pointer">
                                <input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)} className="w-4 h-4 rounded accent-primary" />
                                <span className="text-sm text-amber-900 font-semibold">I confirm this is intentional</span>
                            </label>
                        </div>
                    )}

                    {/* Rejection reason */}
                    {isRejection && (
                        <div>
                            <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5 block">Rejection Reason *</label>
                            <select
                                value={rejectionReason}
                                onChange={e => setRejectionReason(e.target.value)}
                                className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-xl outline-none bg-white focus:ring-2 focus:ring-red-200 focus:border-red-400"
                            >
                                <option value="">Select a reason...</option>
                                {REJECTION_REASONS.map(r => <option key={r} value={r}>{r}</option>)}
                            </select>
                        </div>
                    )}

                    {/* Send email toggle */}
                    {(isRejection || isOffer) && (
                        <label className="flex items-center gap-3 cursor-pointer p-3 bg-slate-50 rounded-xl">
                            <input type="checkbox" checked={sendEmail} onChange={e => setSendEmail(e.target.checked)} className="w-4 h-4 rounded accent-primary" />
                            <div>
                                <p className="text-sm font-semibold text-slate-700">
                                    {isRejection ? "Send rejection email to candidate" : "Send offer email to candidate"}
                                </p>
                                <p className="text-xs text-slate-400">Uses the default {isRejection ? "rejection" : "offer"} email template</p>
                            </div>
                        </label>
                    )}

                    {/* Keep in talent pool */}
                    {isRejection && (
                        <label className="flex items-center gap-3 cursor-pointer p-3 bg-slate-50 rounded-xl">
                            <input type="checkbox" checked={keepInPool} onChange={e => setKeepInPool(e.target.checked)} className="w-4 h-4 rounded accent-primary" />
                            <div>
                                <p className="text-sm font-semibold text-slate-700">Keep in talent pool</p>
                                <p className="text-xs text-slate-400">Save for future opportunities</p>
                            </div>
                        </label>
                    )}

                    {/* Note */}
                    <div>
                        <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5 block">Internal Note (optional)</label>
                        <textarea
                            value={note}
                            onChange={e => setNote(e.target.value)}
                            rows={2}
                            className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-xl outline-none resize-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                            placeholder="Add context for your team..."
                        />
                    </div>
                </div>

                {/* Footer */}
                <div className="flex gap-2 p-5 border-t border-slate-100">
                    <button onClick={onCancel} className="flex-1 px-4 py-2.5 text-sm font-medium text-slate-600 bg-slate-100 rounded-xl hover:bg-slate-200 transition-colors">
                        Cancel
                    </button>
                    <button
                        onClick={handleConfirm}
                        disabled={
                            loading ||
                            hasBlockers ||
                            (isRejection && !rejectionReason) ||
                            (isBackwardMove && !confirmed)
                        }
                        className={`flex-1 px-4 py-2.5 text-sm font-bold text-white rounded-xl transition-colors disabled:opacity-40 flex items-center justify-center gap-2 ${isRejection ? "bg-red-500 hover:bg-red-600" : "bg-primary hover:bg-primary/90"}`}
                    >
                        {loading ? <><Loader2 className="w-4 h-4 animate-spin" /> Moving...</> : <><Check className="w-4 h-4" /> {isRejection ? "Confirm Rejection" : isOffer ? "Send to Offer" : "Confirm Move"}</>}
                    </button>
                </div>
            </motion.div>
        </div>
    );
}
