"use client";

import { useState, useEffect, useTransition } from "react";
import {
    Plus, Trash2, Shield, Zap, Bell, CheckCircle2, GripVertical,
    Settings, ToggleLeft, ToggleRight, Loader2, Copy, ChevronDown,
    ChevronUp, ArrowRight, AlertTriangle, Layout
} from "lucide-react";
import {
    createTransitionRule,
    updateTransitionRule,
    deleteTransitionRule,
    getTransitionRules,
    toggleRuleActive,
    createRuleFromTemplate,
    getTransitionRuleTemplates,
} from "@/app/actions/transitionRuleActions";

// ─── Types ──────────────────────────────────────────────
interface Condition {
    field: string;
    operator: string;
    value: any;
}

interface RuleAction {
    type: string;
    params?: Record<string, any>;
}

interface Stage {
    id: string;
    name: string;
    order: number;
}

interface Rule {
    id: string;
    name: string;
    description: string | null;
    rule_type: string;
    from_stage_id: string | null;
    to_stage_id: string | null;
    conditions: Condition[];
    actions: RuleAction[] | null;
    is_active: boolean;
    allow_override: boolean;
    override_roles: string[];
    priority: number;
}

interface Props {
    pipelineId: string;
    stages: Stage[];
}

const RULE_TYPE_CONFIG = {
    requirement: { label: "Requirement", icon: Shield, color: "text-red-500", bg: "bg-red-50", border: "border-red-200" },
    auto_transition: { label: "Auto-Transition", icon: Zap, color: "text-violet-500", bg: "bg-violet-50", border: "border-violet-200" },
    notification: { label: "Notification", icon: Bell, color: "text-blue-500", bg: "bg-blue-50", border: "border-blue-200" },
    validation: { label: "Validation", icon: CheckCircle2, color: "text-amber-500", bg: "bg-amber-50", border: "border-amber-200" },
};

const CONDITION_FIELDS = [
    { value: "min_score", label: "Minimum Score", type: "number" },
    { value: "min_technical_score", label: "Min Technical Score", type: "number" },
    { value: "feedback_count", label: "Feedback Count", type: "number" },
    { value: "positive_feedback_count", label: "Positive Feedback Count", type: "number" },
    { value: "interview_completed", label: "Completed Interviews", type: "number" },
    { value: "min_time_in_stage", label: "Min Hours in Stage", type: "number" },
    { value: "has_notes", label: "Notes Required", type: "number" },
    { value: "has_rating", label: "Min Rating", type: "number" },
    { value: "tag_required", label: "Tag Required", type: "text" },
    { value: "approval_required", label: "Approval Required", type: "select", options: ["hiring_manager", "hr_admin", "recruiter", "interviewer"] },
    { value: "has_offer", label: "Offer Exists", type: "boolean" },
    { value: "offer_status", label: "Offer Status", type: "select", options: ["pending", "accepted", "declined", "expired"] },
];

// ─── Component ──────────────────────────────────────────
export function TransitionRuleBuilder({ pipelineId, stages }: Props) {
    const [rules, setRules] = useState<Rule[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [showCreate, setShowCreate] = useState(false);
    const [showTemplates, setShowTemplates] = useState(false);
    const [expandedRule, setExpandedRule] = useState<string | null>(null);
    const [isPending, startTransition] = useTransition();

    // Create form state
    const [newRule, setNewRule] = useState({
        name: "",
        description: "",
        rule_type: "requirement",
        from_stage_id: "" as string,
        to_stage_id: "" as string,
        conditions: [{ field: "min_score", operator: "gte", value: 70 }] as Condition[],
        allow_override: true,
        override_roles: ["hiring_manager", "hr_admin"],
        priority: 5,
    });

    useEffect(() => { loadRules(); }, [pipelineId]);

    const loadRules = async () => {
        setIsLoading(true);
        const r = await getTransitionRules(pipelineId);
        if (r.success && r.rules) setRules(r.rules as unknown as Rule[]);
        setIsLoading(false);
    };

    const handleCreate = () => {
        startTransition(async () => {
            const r = await createTransitionRule(pipelineId, {
                name: newRule.name,
                description: newRule.description || undefined,
                rule_type: newRule.rule_type,
                from_stage_id: newRule.from_stage_id || null,
                to_stage_id: newRule.to_stage_id || null,
                conditions: newRule.conditions,
                allow_override: newRule.allow_override,
                override_roles: newRule.override_roles,
                priority: newRule.priority,
            });
            if (r.success) {
                setShowCreate(false);
                setNewRule({
                    name: "", description: "", rule_type: "requirement",
                    from_stage_id: "", to_stage_id: "",
                    conditions: [{ field: "min_score", operator: "gte", value: 70 }],
                    allow_override: true, override_roles: ["hiring_manager", "hr_admin"], priority: 5,
                });
                loadRules();
            }
        });
    };

    const handleDelete = (ruleId: string) => {
        startTransition(async () => {
            await deleteTransitionRule(ruleId);
            loadRules();
        });
    };

    const handleToggle = (ruleId: string) => {
        startTransition(async () => {
            await toggleRuleActive(ruleId);
            loadRules();
        });
    };

    const handleCreateFromTemplate = (index: number) => {
        startTransition(async () => {
            await createRuleFromTemplate(pipelineId, index);
            setShowTemplates(false);
            loadRules();
        });
    };

    const addCondition = () => {
        setNewRule(prev => ({
            ...prev,
            conditions: [...prev.conditions, { field: "min_score", operator: "gte", value: 70 }],
        }));
    };

    const updateCondition = (idx: number, key: string, value: any) => {
        setNewRule(prev => {
            const updated = [...prev.conditions];
            updated[idx] = { ...updated[idx], [key]: value };
            return { ...prev, conditions: updated };
        });
    };

    const removeCondition = (idx: number) => {
        setNewRule(prev => ({ ...prev, conditions: prev.conditions.filter((_, i) => i !== idx) }));
    };

    const getStageLabel = (id: string | null) => {
        if (!id) return "Any Stage";
        return stages.find(s => s.id === id)?.name || "Unknown";
    };

    if (isLoading) {
        return (
            <div className="flex items-center justify-center py-12 text-slate-400">
                <Loader2 className="w-5 h-5 animate-spin mr-2" />
                Loading rules...
            </div>
        );
    }

    return (
        <div className="space-y-4">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h3 className="text-lg font-bold text-slate-900">Transition Rules</h3>
                    <p className="text-xs text-slate-500 mt-0.5">{rules.length} rule{rules.length !== 1 ? "s" : ""} configured</p>
                </div>
                <div className="flex gap-2">
                    <button
                        onClick={() => setShowTemplates(!showTemplates)}
                        className="flex items-center gap-1.5 px-3 py-2 text-xs font-medium text-violet-600 bg-violet-50 border border-violet-200 rounded-xl hover:bg-violet-100 transition-colors"
                    >
                        <Copy className="w-3.5 h-3.5" />
                        Templates
                    </button>
                    <button
                        onClick={() => setShowCreate(!showCreate)}
                        className="flex items-center gap-1.5 px-3 py-2 text-xs font-bold text-white bg-slate-900 rounded-xl hover:bg-slate-800 transition-colors"
                    >
                        <Plus className="w-3.5 h-3.5" />
                        New Rule
                    </button>
                </div>
            </div>

            {/* Templates Dropdown */}
            {showTemplates && (
                <div className="bg-violet-50/50 rounded-xl border border-violet-200 p-4 space-y-2">
                    <p className="text-xs font-bold text-violet-900 uppercase tracking-wider">Quick-Add Templates</p>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                        {[
                            { idx: 0, name: "Min Score Requirement", desc: "Score ≥ 70" },
                            { idx: 1, name: "Interview Feedback Required", desc: "1+ completed interview + feedback" },
                            { idx: 2, name: "Multiple Feedback Required", desc: "3+ positive feedback" },
                            { idx: 3, name: "Min Time in Stage", desc: "48+ hours in stage" },
                            { idx: 5, name: "Notes Before Rejection", desc: "Must add notes before rejecting" },
                            { idx: 6, name: "Rating Required", desc: "Must rate candidate first" },
                            { idx: 7, name: "Approval for Offer", desc: "Hiring manager must approve" },
                        ].map(t => (
                            <button
                                key={t.idx}
                                onClick={() => handleCreateFromTemplate(t.idx)}
                                disabled={isPending}
                                className="text-left p-3 bg-white rounded-xl border border-violet-200 hover:border-violet-400 hover:shadow-sm transition-all"
                            >
                                <p className="text-sm font-medium text-slate-800">{t.name}</p>
                                <p className="text-[10px] text-slate-500 mt-0.5">{t.desc}</p>
                            </button>
                        ))}
                    </div>
                </div>
            )}

            {/* Create Rule Form */}
            {showCreate && (
                <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-5 space-y-4">
                    <p className="text-sm font-bold text-slate-900">Create New Rule</p>

                    {/* Name + Type */}
                    <div className="grid grid-cols-2 gap-3">
                        <div>
                            <label className="text-xs font-medium text-slate-600">Rule Name</label>
                            <input
                                value={newRule.name}
                                onChange={e => setNewRule(p => ({ ...p, name: e.target.value }))}
                                placeholder="e.g. Min Score for Final Interview"
                                className="mt-1 w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-200 focus:border-blue-400 outline-none"
                            />
                        </div>
                        <div>
                            <label className="text-xs font-medium text-slate-600">Rule Type</label>
                            <select
                                value={newRule.rule_type}
                                onChange={e => setNewRule(p => ({ ...p, rule_type: e.target.value }))}
                                className="mt-1 w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-200 focus:border-blue-400 outline-none"
                            >
                                <option value="requirement">⛔ Requirement (Blocks)</option>
                                <option value="validation">✅ Validation (Warns)</option>
                                <option value="notification">📧 Notification</option>
                                <option value="auto_transition">⚡ Auto-Transition</option>
                            </select>
                        </div>
                    </div>

                    {/* Stages */}
                    <div className="grid grid-cols-2 gap-3">
                        <div>
                            <label className="text-xs font-medium text-slate-600">From Stage</label>
                            <select
                                value={newRule.from_stage_id}
                                onChange={e => setNewRule(p => ({ ...p, from_stage_id: e.target.value }))}
                                className="mt-1 w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-200 focus:border-blue-400 outline-none"
                            >
                                <option value="">Any Stage</option>
                                {stages.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                            </select>
                        </div>
                        <div>
                            <label className="text-xs font-medium text-slate-600">To Stage</label>
                            <select
                                value={newRule.to_stage_id}
                                onChange={e => setNewRule(p => ({ ...p, to_stage_id: e.target.value }))}
                                className="mt-1 w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-200 focus:border-blue-400 outline-none"
                            >
                                <option value="">Any Stage</option>
                                {stages.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                            </select>
                        </div>
                    </div>

                    {/* Description */}
                    <div>
                        <label className="text-xs font-medium text-slate-600">Description</label>
                        <input
                            value={newRule.description}
                            onChange={e => setNewRule(p => ({ ...p, description: e.target.value }))}
                            placeholder="Optional description..."
                            className="mt-1 w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-200 focus:border-blue-400 outline-none"
                        />
                    </div>

                    {/* Conditions */}
                    <div>
                        <div className="flex items-center justify-between mb-2">
                            <label className="text-xs font-bold text-slate-600 uppercase tracking-wider">Conditions</label>
                            <button onClick={addCondition} className="text-xs text-blue-600 hover:text-blue-800">
                                + Add Condition
                            </button>
                        </div>
                        <div className="space-y-2">
                            {newRule.conditions.map((cond, idx) => {
                                const fieldDef = CONDITION_FIELDS.find(f => f.value === cond.field);
                                return (
                                    <div key={idx} className="flex items-center gap-2 p-2 bg-slate-50 rounded-xl">
                                        <select
                                            value={cond.field}
                                            onChange={e => updateCondition(idx, "field", e.target.value)}
                                            className="flex-1 px-2 py-1.5 border border-slate-200 rounded-lg text-xs bg-white"
                                        >
                                            {CONDITION_FIELDS.map(f => (
                                                <option key={f.value} value={f.value}>{f.label}</option>
                                            ))}
                                        </select>
                                        {fieldDef?.type === "select" ? (
                                            <select
                                                value={cond.value}
                                                onChange={e => updateCondition(idx, "value", e.target.value)}
                                                className="w-32 px-2 py-1.5 border border-slate-200 rounded-lg text-xs bg-white"
                                            >
                                                {fieldDef.options?.map(o => (
                                                    <option key={o} value={o}>{o.replace(/_/g, " ")}</option>
                                                ))}
                                            </select>
                                        ) : fieldDef?.type === "boolean" ? (
                                            <select
                                                value={String(cond.value)}
                                                onChange={e => updateCondition(idx, "value", e.target.value === "true")}
                                                className="w-20 px-2 py-1.5 border border-slate-200 rounded-lg text-xs bg-white"
                                            >
                                                <option value="true">Yes</option>
                                                <option value="false">No</option>
                                            </select>
                                        ) : (
                                            <input
                                                type={fieldDef?.type || "text"}
                                                value={cond.value}
                                                onChange={e => updateCondition(idx, "value", fieldDef?.type === "number" ? Number(e.target.value) : e.target.value)}
                                                className="w-20 px-2 py-1.5 border border-slate-200 rounded-lg text-xs bg-white"
                                            />
                                        )}
                                        {newRule.conditions.length > 1 && (
                                            <button onClick={() => removeCondition(idx)} className="p-1 text-red-400 hover:text-red-600">
                                                <Trash2 className="w-3.5 h-3.5" />
                                            </button>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>

                    {/* Override Settings */}
                    <div className="flex items-center gap-4 p-3 bg-slate-50 rounded-xl">
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={newRule.allow_override}
                                onChange={e => setNewRule(p => ({ ...p, allow_override: e.target.checked }))}
                                className="rounded border-slate-300"
                            />
                            <span className="text-xs text-slate-700">Allow Override</span>
                        </label>
                        <div className="flex items-center gap-2">
                            <span className="text-xs text-slate-500">Priority:</span>
                            <input
                                type="number"
                                min={0}
                                max={10}
                                value={newRule.priority}
                                onChange={e => setNewRule(p => ({ ...p, priority: Number(e.target.value) }))}
                                className="w-14 px-2 py-1 border border-slate-200 rounded-lg text-xs bg-white"
                            />
                        </div>
                    </div>

                    {/* Actions */}
                    <div className="flex gap-2 pt-2">
                        <button onClick={() => setShowCreate(false)} 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={handleCreate}
                            disabled={!newRule.name || isPending}
                            className="flex-1 flex items-center justify-center gap-2 px-4 py-2 text-sm font-bold text-white bg-blue-600 rounded-xl hover:bg-blue-700 transition-colors disabled:opacity-50"
                        >
                            {isPending && <Loader2 className="w-4 h-4 animate-spin" />}
                            Create Rule
                        </button>
                    </div>
                </div>
            )}

            {/* Rules List */}
            {rules.length === 0 && !showCreate && (
                <div className="text-center py-12 border border-dashed border-slate-200 rounded-2xl">
                    <Layout className="w-10 h-10 text-slate-300 mx-auto mb-3" />
                    <p className="text-sm font-medium text-slate-600">No transition rules configured</p>
                    <p className="text-xs text-slate-400 mt-1">Add rules to control how candidates move between stages</p>
                    <button
                        onClick={() => setShowTemplates(true)}
                        className="mt-3 text-xs text-violet-600 hover:text-violet-800 font-medium"
                    >
                        Start with a template →
                    </button>
                </div>
            )}

            {rules.map((rule) => {
                const typeConfig = RULE_TYPE_CONFIG[rule.rule_type as keyof typeof RULE_TYPE_CONFIG]
                    || RULE_TYPE_CONFIG.requirement;
                const TypeIcon = typeConfig.icon;
                const isExpanded = expandedRule === rule.id;

                return (
                    <div
                        key={rule.id}
                        className={`border rounded-xl overflow-hidden transition-all ${rule.is_active ? "border-slate-200 bg-white" : "border-slate-100 bg-slate-50/50 opacity-60"
                            }`}
                    >
                        <div className="flex items-center gap-3 p-3.5">
                            <div className={`p-1.5 rounded-lg ${typeConfig.bg}`}>
                                <TypeIcon className={`w-4 h-4 ${typeConfig.color}`} />
                            </div>
                            <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2">
                                    <p className="text-sm font-semibold text-slate-800 truncate">{rule.name}</p>
                                    <span className={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${typeConfig.bg} ${typeConfig.color}`}>
                                        {typeConfig.label}
                                    </span>
                                </div>
                                <p className="text-xs text-slate-500 mt-0.5">
                                    {getStageLabel(rule.from_stage_id)} → {getStageLabel(rule.to_stage_id)}
                                    {" · "}{(rule.conditions as Condition[]).length} condition{(rule.conditions as Condition[]).length !== 1 ? "s" : ""}
                                </p>
                            </div>
                            <button
                                onClick={() => handleToggle(rule.id)}
                                className="p-1 text-slate-400 hover:text-slate-600"
                                title={rule.is_active ? "Disable" : "Enable"}
                            >
                                {rule.is_active ? (
                                    <ToggleRight className="w-5 h-5 text-emerald-500" />
                                ) : (
                                    <ToggleLeft className="w-5 h-5 text-slate-300" />
                                )}
                            </button>
                            <button
                                onClick={() => setExpandedRule(isExpanded ? null : rule.id)}
                                className="p-1 text-slate-400 hover:text-slate-600"
                            >
                                {isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                            </button>
                        </div>

                        {isExpanded && (
                            <div className="px-4 pb-4 pt-0 border-t border-slate-100">
                                {rule.description && (
                                    <p className="text-xs text-slate-500 mb-3 mt-3">{rule.description}</p>
                                )}
                                <div className="space-y-1.5 mb-3">
                                    <p className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Conditions</p>
                                    {(rule.conditions as Condition[]).map((c, i) => {
                                        const fieldDef = CONDITION_FIELDS.find(f => f.value === c.field);
                                        return (
                                            <div key={i} className="flex items-center gap-2 p-2 bg-slate-50 rounded-lg text-xs text-slate-700">
                                                <span className="font-medium">{fieldDef?.label || c.field}</span>
                                                <ArrowRight className="w-3 h-3 text-slate-300" />
                                                <span>{String(c.value)}</span>
                                            </div>
                                        );
                                    })}
                                </div>
                                <div className="flex items-center gap-3 text-[10px] text-slate-500">
                                    <span>Priority: {rule.priority}</span>
                                    <span>·</span>
                                    <span>Override: {rule.allow_override ? "Yes" : "No"}</span>
                                    {rule.allow_override && rule.override_roles.length > 0 && (
                                        <>
                                            <span>·</span>
                                            <span>By: {rule.override_roles.join(", ")}</span>
                                        </>
                                    )}
                                </div>
                                <div className="flex justify-end mt-3">
                                    <button
                                        onClick={() => handleDelete(rule.id)}
                                        disabled={isPending}
                                        className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
                                    >
                                        <Trash2 className="w-3 h-3" />
                                        Delete Rule
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                );
            })}
        </div>
    );
}
