"use client";

import { useState, useTransition } from "react";
import {
    AlertTriangle, CheckCircle2, XCircle, ShieldAlert,
    Loader2, X, Send, ChevronDown, ChevronUp
} from "lucide-react";
import { overrideTransitionRule } from "@/app/actions/transitionRuleActions";

interface RuleViolation {
    ruleId: string;
    ruleName: string;
    description?: string | null;
    condition: { field: string; operator: string; value: any };
    message: string;
    allowOverride: boolean;
    overrideRoles: string[];
}

interface Props {
    isOpen: boolean;
    onClose: () => void;
    onOverrideSuccess: () => void;
    applicationId: string;
    candidateName: string;
    fromStageName: string;
    toStageName: string;
    violations: RuleViolation[];
    warnings: string[];
}

export function TransitionBlockedModal({
    isOpen,
    onClose,
    onOverrideSuccess,
    applicationId,
    candidateName,
    fromStageName,
    toStageName,
    violations,
    warnings,
}: Props) {
    const [showOverride, setShowOverride] = useState(false);
    const [overrideReason, setOverrideReason] = useState("");
    const [isPending, startTransition] = useTransition();
    const [expandedRule, setExpandedRule] = useState<string | null>(null);

    if (!isOpen) return null;

    const overridableViolations = violations.filter(v => v.allowOverride);
    const nonOverridableViolations = violations.filter(v => !v.allowOverride);
    const canOverride = nonOverridableViolations.length === 0 && overridableViolations.length > 0;

    const handleOverride = () => {
        if (!overrideReason.trim() || overrideReason.length < 10) return;
        startTransition(async () => {
            // Override all violating rules
            const results = await Promise.allSettled(
                overridableViolations.map(v =>
                    overrideTransitionRule(applicationId, v.ruleId, overrideReason, fromStageName, toStageName)
                )
            );
            const allSuccess = results.every(r => r.status === "fulfilled" && (r.value as any).success);
            if (allSuccess) {
                onOverrideSuccess();
                onClose();
            }
        });
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
            <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={onClose} />
            <div className="relative bg-white rounded-2xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden animate-in fade-in slide-in-from-bottom-4">
                {/* Header */}
                <div className="flex items-center gap-3 p-5 border-b border-slate-100 bg-red-50">
                    <div className="p-2.5 bg-red-100 rounded-xl">
                        <XCircle className="w-6 h-6 text-red-600" />
                    </div>
                    <div className="flex-1">
                        <h2 className="text-base font-bold text-slate-900">Cannot Move {candidateName}</h2>
                        <p className="text-sm text-slate-500">
                            {fromStageName} → {toStageName}
                        </p>
                    </div>
                    <button onClick={onClose} className="p-2 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-white/60 transition-colors">
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {/* Violations */}
                <div className="p-5 max-h-[400px] overflow-y-auto space-y-3">
                    <p className="text-xs font-bold text-slate-500 uppercase tracking-wider">Requirements Not Met</p>

                    {violations.map((v) => (
                        <div
                            key={v.ruleId}
                            className="border border-slate-200 rounded-xl overflow-hidden"
                        >
                            <button
                                onClick={() => setExpandedRule(expandedRule === v.ruleId ? null : v.ruleId)}
                                className="flex items-center gap-3 w-full p-3 text-left hover:bg-slate-50 transition-colors"
                            >
                                <div className={`p-1 rounded-lg ${v.allowOverride ? "bg-amber-50" : "bg-red-50"}`}>
                                    {v.allowOverride ? (
                                        <AlertTriangle className="w-4 h-4 text-amber-500" />
                                    ) : (
                                        <ShieldAlert className="w-4 h-4 text-red-500" />
                                    )}
                                </div>
                                <div className="flex-1 min-w-0">
                                    <p className="text-sm font-semibold text-slate-800">{v.ruleName}</p>
                                    <p className="text-xs text-red-500 mt-0.5">{v.message}</p>
                                </div>
                                {v.allowOverride ? (
                                    <span className="text-[10px] px-2 py-0.5 bg-amber-100 text-amber-700 rounded-full font-medium flex-shrink-0">
                                        Overridable
                                    </span>
                                ) : (
                                    <span className="text-[10px] px-2 py-0.5 bg-red-100 text-red-700 rounded-full font-medium flex-shrink-0">
                                        Required
                                    </span>
                                )}
                                {expandedRule === v.ruleId ? (
                                    <ChevronUp className="w-4 h-4 text-slate-300" />
                                ) : (
                                    <ChevronDown className="w-4 h-4 text-slate-300" />
                                )}
                            </button>
                            {expandedRule === v.ruleId && (
                                <div className="px-3 pb-3 pt-0">
                                    {v.description && (
                                        <p className="text-xs text-slate-500 mb-2">{v.description}</p>
                                    )}
                                    <div className="text-xs bg-slate-50 rounded-lg p-2 text-slate-600">
                                        <span className="font-medium">Condition:</span>{" "}
                                        {v.condition.field.replace(/_/g, " ")} {v.condition.operator} {String(v.condition.value)}
                                    </div>
                                    {v.allowOverride && v.overrideRoles.length > 0 && (
                                        <p className="text-[10px] text-slate-400 mt-1">
                                            Can be overridden by: {v.overrideRoles.map(r => r.replace(/_/g, " ")).join(", ")}
                                        </p>
                                    )}
                                </div>
                            )}
                        </div>
                    ))}

                    {/* Warnings */}
                    {warnings.length > 0 && (
                        <div className="mt-4 space-y-2">
                            <p className="text-xs font-bold text-slate-500 uppercase tracking-wider">Warnings</p>
                            {warnings.map((w, i) => (
                                <div key={i} className="flex items-center gap-2 p-2.5 bg-amber-50 border border-amber-200 rounded-xl">
                                    <AlertTriangle className="w-3.5 h-3.5 text-amber-500 flex-shrink-0" />
                                    <p className="text-xs text-amber-700">{w}</p>
                                </div>
                            ))}
                        </div>
                    )}

                    {/* Override Section */}
                    {canOverride && (
                        <div className="mt-4 pt-4 border-t border-slate-100">
                            {!showOverride ? (
                                <button
                                    onClick={() => setShowOverride(true)}
                                    className="flex items-center gap-2 px-4 py-2.5 text-sm font-medium text-amber-700 bg-amber-50 border border-amber-200 rounded-xl hover:bg-amber-100 transition-colors w-full justify-center"
                                >
                                    <ShieldAlert className="w-4 h-4" />
                                    Override {overridableViolations.length} Requirement{overridableViolations.length > 1 ? "s" : ""}
                                </button>
                            ) : (
                                <div className="space-y-3">
                                    <div className="p-3 bg-amber-50 border border-amber-200 rounded-xl">
                                        <p className="text-xs font-bold text-amber-800 mb-1">Override Justification Required</p>
                                        <p className="text-[10px] text-amber-600">
                                            This action will be logged in the audit trail. Minimum 10 characters.
                                        </p>
                                    </div>
                                    <textarea
                                        value={overrideReason}
                                        onChange={(e) => setOverrideReason(e.target.value)}
                                        placeholder="Explain why you're overriding this requirement..."
                                        rows={3}
                                        className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm resize-none focus:ring-2 focus:ring-amber-200 focus:border-amber-400 outline-none"
                                        autoFocus
                                    />
                                    <div className="flex gap-2">
                                        <button
                                            onClick={() => { setShowOverride(false); setOverrideReason(""); }}
                                            className="flex-1 px-4 py-2 text-sm text-slate-600 bg-slate-100 rounded-xl hover:bg-slate-200 transition-colors"
                                        >
                                            Cancel
                                        </button>
                                        <button
                                            onClick={handleOverride}
                                            disabled={isPending || overrideReason.length < 10}
                                            className="flex-1 flex items-center justify-center gap-2 px-4 py-2 text-sm font-bold text-white bg-amber-600 rounded-xl hover:bg-amber-700 transition-colors disabled:opacity-50"
                                        >
                                            {isPending ? (
                                                <Loader2 className="w-4 h-4 animate-spin" />
                                            ) : (
                                                <Send className="w-4 h-4" />
                                            )}
                                            Confirm Override
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {!canOverride && nonOverridableViolations.length > 0 && (
                        <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-xl">
                            <p className="text-xs text-red-700 font-medium">
                                {nonOverridableViolations.length} requirement(s) cannot be overridden. These must be fulfilled before this candidate can advance.
                            </p>
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div className="p-4 border-t border-slate-100 bg-slate-50">
                    <button
                        onClick={onClose}
                        className="w-full px-4 py-2.5 text-sm font-medium text-slate-700 bg-white border border-slate-200 rounded-xl hover:bg-slate-50 transition-colors"
                    >
                        Close
                    </button>
                </div>
            </div>
        </div>
    );
}
