"use client";

import { useState, useEffect, useTransition } from "react";
import { Plus, Trash2, Mail, Zap, Loader2, ChevronDown, ChevronUp, ArrowRight, Layout } from "lucide-react";
import {
    createTransitionRule,
    deleteTransitionRule,
    getTransitionRules,
    toggleRuleActive,
} from "@/app/actions/transitionRuleActions";
import { getMessageTemplates, MessageTemplateData } from "@/app/actions/messageActions";

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

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

interface Rule {
    id: string;
    name: string;
    rule_type: string;
    from_stage_id: string | null;
    to_stage_id: string | null;
    actions: RuleAction[] | null;
    is_active: boolean;
}

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

export function PipelineAutomationBuilder({ pipelineId, stages }: Props) {
    const [automations, setAutomations] = useState<Rule[]>([]);
    const [templates, setTemplates] = useState<MessageTemplateData[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [showCreate, setShowCreate] = useState(false);
    const [expandedRule, setExpandedRule] = useState<string | null>(null);
    const [isPending, startTransition] = useTransition();

    // Create form state
    const [newAutomation, setNewAutomation] = useState({
        name: "",
        rule_type: "notification", // Default to sending an email
        to_stage_id: "", // Triggered when candidate enters this stage
        action_type: "send_email",
        template_id: "",
    });

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

    const loadData = async () => {
        setIsLoading(true);
        const [rulesRes, templatesRes] = await Promise.all([
            getTransitionRules(pipelineId),
            getMessageTemplates()
        ]);

        if (rulesRes.success && rulesRes.rules) {
            // Filter only rules that are actually automations (e.g., notification or auto_transition with actions)
            const autoRules = (rulesRes.rules as unknown as Rule[]).filter(r =>
                r.rule_type === "notification" || r.rule_type === "auto_transition"
            );
            setAutomations(autoRules);
        }

        if (templatesRes.success && templatesRes.templates) {
            setTemplates(templatesRes.templates as MessageTemplateData[]);
        }
        setIsLoading(false);
    };

    const handleCreate = () => {
        startTransition(async () => {
            const actions = [{
                type: newAutomation.action_type,
                params: {
                    template_id: newAutomation.template_id
                }
            }];

            const r = await createTransitionRule(pipelineId, {
                name: newAutomation.name,
                rule_type: newAutomation.rule_type,
                to_stage_id: newAutomation.to_stage_id || null,
                conditions: [], // Automations trigger purely on stage entry for now
                actions,
                allow_override: true,
            });

            if (r.success) {
                setShowCreate(false);
                setNewAutomation({
                    name: "", rule_type: "notification", to_stage_id: "", action_type: "send_email", template_id: ""
                });
                loadData();
            }
        });
    };

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

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

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

    const getTemplateName = (id: string) => {
        return templates.find(t => t.id === id)?.title || "Unknown Template";
    };

    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 automations...
            </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">Pipeline Automations</h3>
                    <p className="text-xs text-slate-500 mt-0.5">{automations.length} active automation{automations.length !== 1 ? "s" : ""}</p>
                </div>
                <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 Automation
                </button>
            </div>

            {/* Create 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 Automation</p>

                    <div className="grid grid-cols-2 gap-3">
                        <div>
                            <label className="text-xs font-medium text-slate-600">Name</label>
                            <input
                                value={newAutomation.name}
                                onChange={e => setNewAutomation(p => ({ ...p, name: e.target.value }))}
                                placeholder="e.g. Auto-Reject Email"
                                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">When candidate enters</label>
                            <select
                                value={newAutomation.to_stage_id}
                                onChange={e => setNewAutomation(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="" disabled>Select a stage...</option>
                                {stages.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                            </select>
                        </div>
                    </div>

                    <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 space-y-3">
                        <p className="text-xs font-bold text-slate-600 uppercase tracking-wider">Then Do This</p>
                        <div className="flex items-center gap-3">
                            <select
                                value={newAutomation.action_type}
                                onChange={e => setNewAutomation(p => ({ ...p, action_type: e.target.value }))}
                                className="w-40 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="send_email">Send Email Template</option>
                            </select>

                            {newAutomation.action_type === "send_email" && (
                                <select
                                    value={newAutomation.template_id}
                                    onChange={e => setNewAutomation(p => ({ ...p, template_id: e.target.value }))}
                                    className="flex-1 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="" disabled>Select a template...</option>
                                    {templates.map(t => <option key={t.id} value={t.id}>{t.title}</option>)}
                                </select>
                            )}
                        </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={!newAutomation.name || !newAutomation.to_stage_id || !newAutomation.template_id || 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 Automation
                        </button>
                    </div>
                </div>
            )}

            {/* List */}
            {automations.length === 0 && !showCreate && (
                <div className="text-center py-12 border border-dashed border-slate-200 rounded-2xl">
                    <Zap className="w-10 h-10 text-violet-300 mx-auto mb-3" />
                    <p className="text-sm font-medium text-slate-600">No automations configured</p>
                    <p className="text-xs text-slate-400 mt-1">Automatically send emails or update records when candidates move stages.</p>
                </div>
            )}

            {automations.map((auto) => {
                const isExpanded = expandedRule === auto.id;

                return (
                    <div
                        key={auto.id}
                        className={`border rounded-xl overflow-hidden transition-all ${auto.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 bg-violet-50">
                                <Zap className="w-4 h-4 text-violet-500" />
                            </div>
                            <div className="flex-1 min-w-0">
                                <h4 className="text-sm font-semibold text-slate-800 truncate">{auto.name}</h4>
                                <p className="text-xs text-slate-500 mt-0.5 flex items-center gap-1">
                                    When entering <span className="font-semibold text-slate-700">{getStageLabel(auto.to_stage_id)}</span>
                                </p>
                            </div>

                            <div className="flex items-center gap-2">
                                <button
                                    onClick={() => handleToggle(auto.id)}
                                    className={`px-3 py-1 text-xs font-medium rounded-full ${auto.is_active ? 'bg-emerald-50 text-emerald-600' : 'bg-slate-100 text-slate-500'}`}
                                >
                                    {auto.is_active ? 'Active' : 'Inactive'}
                                </button>
                                <button
                                    onClick={() => handleDelete(auto.id)}
                                    disabled={isPending}
                                    className="p-1.5 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                >
                                    <Trash2 className="w-4 h-4" />
                                </button>
                                <button
                                    onClick={() => setExpandedRule(isExpanded ? null : auto.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>
                        </div>

                        {isExpanded && auto.actions && auto.actions.length > 0 && (
                            <div className="px-4 pb-4 pt-0 border-t border-slate-100 bg-slate-50/50">
                                <div className="mt-3 space-y-2">
                                    <p className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Actions</p>
                                    {auto.actions.map((action, idx) => (
                                        <div key={idx} className="flex items-center gap-2 p-3 bg-white border border-slate-200 rounded-lg text-sm text-slate-700 shadow-sm">
                                            {action.type === "send_email" && (
                                                <>
                                                    <Mail className="w-4 h-4 text-slate-400" />
                                                    <span className="font-medium">Send Template:</span>
                                                    <span className="text-blue-600 bg-blue-50 px-2 py-0.5 rounded-md text-xs font-medium">
                                                        {getTemplateName(action.params?.template_id)}
                                                    </span>
                                                </>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                );
            })}
        </div>
    );
}
