"use client";

import { useState, useCallback } from "react";
import {
    DndContext,
    closestCenter,
    PointerSensor,
    useSensor,
    useSensors,
    DragEndEvent,
} from "@dnd-kit/core";
import {
    SortableContext,
    horizontalListSortingStrategy,
    useSortable,
    arrayMove,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import {
    GripVertical, Plus, Trash2, Edit3, X, Check,
    ChevronDown, Copy, Loader2, Palette
} from "lucide-react";
import { createPipeline, updatePipeline } from "@/app/actions/pipelineBuilderActions";
import { StageInput } from "@/lib/pipelineConstants";
import { TransitionRuleBuilder } from "./TransitionRuleBuilder";
import { PipelineAutomationBuilder } from "./PipelineAutomationBuilder";

const STAGE_COLORS = [
    "#94a3b8", "#3b82f6", "#6366f1", "#8b5cf6", "#ec4899",
    "#f59e0b", "#10b981", "#059669", "#ef4444", "#0ea5e9",
    "#14b8a6", "#f97316", "#a855f7", "#84cc16", "#fb923c",
];

const STAGE_TYPES = [
    { value: "applied", label: "Applied / Submitted" },
    { value: "screening", label: "Screening / Review" },
    { value: "assessment", label: "Assessment / Task" },
    { value: "interview", label: "Interview" },
    { value: "offer", label: "Offer" },
    { value: "hired", label: "Hired / Accepted" },
    { value: "rejected", label: "Rejected" },
];

interface SortableStageProps {
    stage: StageInput & { tempId: string };
    index: number;
    onEdit: (id: string) => void;
    onDelete: (id: string) => void;
}

function SortableStage({ stage, onEdit, onDelete }: SortableStageProps) {
    const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: stage.tempId });
    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
        opacity: isDragging ? 0.5 : 1,
    };

    return (
        <div
            ref={setNodeRef}
            style={style}
            className="flex items-center gap-2 p-3 bg-white border border-slate-200 rounded-xl shadow-sm group"
        >
            <div {...attributes} {...listeners} className="cursor-grab active:cursor-grabbing text-slate-300 hover:text-slate-500">
                <GripVertical className="w-4 h-4" />
            </div>
            <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: stage.color }} />
            <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-slate-800 truncate">{stage.name}</p>
                <p className="text-xs text-slate-400 truncate">
                    {STAGE_TYPES.find(t => t.value === stage.stage_type)?.label || stage.stage_type}
                    {stage.expected_duration_days ? ` · ~${stage.expected_duration_days}d` : ""}
                </p>
            </div>
            <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                <button onClick={() => onEdit(stage.tempId)} className="p-1.5 text-slate-400 hover:text-blue-600 rounded-lg hover:bg-blue-50">
                    <Edit3 className="w-3.5 h-3.5" />
                </button>
                <button onClick={() => onDelete(stage.tempId)} className="p-1.5 text-slate-400 hover:text-red-500 rounded-lg hover:bg-red-50">
                    <Trash2 className="w-3.5 h-3.5" />
                </button>
            </div>
        </div>
    );
}

interface StageEditorModalProps {
    stage: StageInput & { tempId: string };
    onSave: (updated: StageInput & { tempId: string }) => void;
    onClose: () => void;
}

function StageEditorModal({ stage, onSave, onClose }: StageEditorModalProps) {
    const [name, setName] = useState(stage.name);
    const [color, setColor] = useState(stage.color);
    const [description, setDescription] = useState(stage.description || "");
    const [stageType, setStageType] = useState(stage.stage_type);
    const [duration, setDuration] = useState(stage.expected_duration_days?.toString() || "");

    return (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
            <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
                <div className="flex items-center justify-between p-5 border-b border-slate-100">
                    <h3 className="font-bold text-slate-800">Edit Stage</h3>
                    <button onClick={onClose} className="p-2 hover:bg-slate-100 rounded-lg"><X className="w-4 h-4" /></button>
                </div>
                <div className="p-5 space-y-4">
                    <div>
                        <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5 block">Stage Name *</label>
                        <input
                            value={name}
                            onChange={e => setName(e.target.value)}
                            className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none"
                            placeholder="e.g. Technical Interview"
                        />
                    </div>
                    <div>
                        <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5 block">Stage Type</label>
                        <select
                            value={stageType}
                            onChange={e => setStageType(e.target.value)}
                            className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none bg-white"
                        >
                            {STAGE_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
                        </select>
                    </div>
                    <div>
                        <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5 block">Description</label>
                        <textarea
                            value={description}
                            onChange={e => setDescription(e.target.value)}
                            rows={2}
                            className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none resize-none"
                            placeholder="What happens in this stage?"
                        />
                    </div>
                    <div className="flex gap-3">
                        <div className="flex-1">
                            <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5 block">Expected Duration (days)</label>
                            <input
                                type="number"
                                min="1"
                                max="90"
                                value={duration}
                                onChange={e => setDuration(e.target.value)}
                                className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none"
                                placeholder="e.g. 7"
                            />
                        </div>
                        <div className="flex-1">
                            <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5 flex items-center gap-1.5">
                                <Palette className="w-3 h-3" /> Color
                            </label>
                            <div className="flex flex-wrap gap-1.5 mt-1">
                                {STAGE_COLORS.map(c => (
                                    <button
                                        key={c}
                                        onClick={() => setColor(c)}
                                        className="w-6 h-6 rounded-full border-2 transition-transform hover:scale-110"
                                        style={{ backgroundColor: c, borderColor: color === c ? "#1e293b" : "transparent" }}
                                    />
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
                <div className="flex gap-2 p-5 border-t border-slate-100">
                    <button onClick={onClose} 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={() => onSave({ ...stage, name: name.trim(), color, description, stage_type: stageType, expected_duration_days: duration ? parseInt(duration) : null })}
                        disabled={!name.trim()}
                        className="flex-1 px-4 py-2.5 text-sm font-bold text-white bg-primary rounded-xl hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                    >
                        <Check className="w-4 h-4" /> Save Stage
                    </button>
                </div>
            </div>
        </div>
    );
}

interface PipelineBuilderProps {
    pipelineId?: string;
    initialName?: string;
    initialStages?: (StageInput & { tempId?: string })[];
    onSuccess?: () => void;
    onCancel?: () => void;
}

let idCounter = 0;
const makeTempId = () => `temp-${++idCounter}`;

export function PipelineBuilder({ pipelineId, initialName = "", initialStages = [], onSuccess, onCancel }: PipelineBuilderProps) {
    const [pipelineName, setPipelineName] = useState(initialName);
    const [stages, setStages] = useState<(StageInput & { tempId: string })[]>(
        initialStages.map(s => ({ ...s, tempId: s.tempId || makeTempId() }))
    );
    const [editingId, setEditingId] = useState<string | null>(null);
    const [isSaving, setIsSaving] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const sensors = useSensors(useSensor(PointerSensor));

    const handleDragEnd = useCallback((event: DragEndEvent) => {
        const { active, over } = event;
        if (over && active.id !== over.id) {
            setStages(prev => {
                const oldIdx = prev.findIndex(s => s.tempId === active.id);
                const newIdx = prev.findIndex(s => s.tempId === over.id);
                return arrayMove(prev, oldIdx, newIdx).map((s, i) => ({ ...s, order: i }));
            });
        }
    }, []);

    const handleAddStage = () => {
        const newStage: StageInput & { tempId: string } = {
            tempId: makeTempId(),
            name: "New Stage",
            color: STAGE_COLORS[stages.length % STAGE_COLORS.length],
            stage_type: "interview",
            order: stages.length,
            description: "",
            expected_duration_days: 7,
        };
        setStages(prev => [...prev, newStage]);
        setEditingId(newStage.tempId);
    };

    const handleSaveStage = (updated: StageInput & { tempId: string }) => {
        setStages(prev => prev.map(s => s.tempId === updated.tempId ? updated : s));
        setEditingId(null);
    };

    const handleDeleteStage = (id: string) => {
        setStages(prev => prev.filter(s => s.tempId !== id).map((s, i) => ({ ...s, order: i })));
    };

    const handleSave = async () => {
        if (!pipelineName.trim()) { setError("Please enter a pipeline name."); return; }
        if (stages.length < 2) { setError("Please add at least 2 stages."); return; }

        setIsSaving(true);
        setError(null);
        try {
            const result = pipelineId
                ? await updatePipeline(pipelineId, pipelineName, stages)
                : await createPipeline(pipelineName, stages);
            if (!result.success) { setError(result.error || "Failed to save"); return; }
            onSuccess?.();
        } catch (error) {
            console.error("Failed to save pipeline:", error);
            setError("An unexpected error occurred.");
        } finally {
            setIsSaving(false);
        }
    };

    const editingStage = editingId ? stages.find(s => s.tempId === editingId) : null;

    return (
        <div className="flex flex-col h-full">
            {editingStage && (
                <StageEditorModal
                    stage={editingStage}
                    onSave={handleSaveStage}
                    onClose={() => setEditingId(null)}
                />
            )}
            <div className="p-6 space-y-6 flex-1 overflow-y-auto">
                {/* Pipeline Name */}
                <div>
                    <label className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 block">Pipeline Name *</label>
                    <input
                        value={pipelineName}
                        onChange={e => setPipelineName(e.target.value)}
                        className="w-full px-4 py-3 border border-slate-200 rounded-xl text-base font-medium focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none"
                        placeholder="e.g. Standard Engineering Hire"
                    />
                </div>

                {/* Stages */}
                <div>
                    <div className="flex items-center justify-between mb-3">
                        <label className="text-xs font-bold text-slate-500 uppercase tracking-wider">
                            Stages ({stages.length}/12)
                        </label>
                        <button onClick={handleAddStage} className="flex items-center gap-1.5 text-xs font-bold text-primary hover:text-primary/80 transition-colors">
                            <Plus className="w-3.5 h-3.5" /> Add Stage
                        </button>
                    </div>

                    {stages.length === 0 ? (
                        <div className="border-2 border-dashed border-slate-200 rounded-xl p-8 text-center">
                            <p className="text-sm text-slate-400 mb-3">No stages yet. Add your first stage to get started.</p>
                            <button onClick={handleAddStage} className="px-4 py-2 bg-primary text-white text-sm font-bold rounded-xl hover:bg-primary/90 transition-colors">
                                <Plus className="w-4 h-4 inline mr-1.5" /> Add First Stage
                            </button>
                        </div>
                    ) : (
                        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
                            <SortableContext items={stages.map(s => s.tempId)} strategy={horizontalListSortingStrategy}>
                                <div className="space-y-2">
                                    {stages.map((stage, index) => (
                                        <SortableStage
                                            key={stage.tempId}
                                            stage={stage}
                                            index={index}
                                            onEdit={setEditingId}
                                            onDelete={handleDeleteStage}
                                        />
                                    ))}
                                </div>
                            </SortableContext>
                        </DndContext>
                    )}
                </div>

                {error && (
                    <div className="p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700">
                        {error}
                    </div>
                )}

                {/* Automations and Rules (Only when editing an existing pipeline) */}
                {pipelineId && (
                    <div className="mt-8 space-y-8 border-t border-slate-100 pt-8">
                        <div>
                            <PipelineAutomationBuilder
                                pipelineId={pipelineId}
                                stages={stages.map(s => ({ id: s.tempId, name: s.name, order: s.order }))}
                            />
                        </div>
                        <div className="border-t border-slate-100 pt-8">
                            <TransitionRuleBuilder
                                pipelineId={pipelineId}
                                stages={stages.map(s => ({ id: s.tempId, name: s.name, order: s.order }))}
                            />
                        </div>
                    </div>
                )}
            </div>

            {/* Footer */}
            <div className="p-6 border-t border-slate-100 flex gap-3">
                <button onClick={onCancel} className="flex-1 px-4 py-3 text-sm font-medium text-slate-600 bg-slate-100 rounded-xl hover:bg-slate-200 transition-colors">
                    Cancel
                </button>
                <button
                    onClick={handleSave}
                    disabled={isSaving}
                    className="flex-1 px-4 py-3 text-sm font-bold text-white bg-primary rounded-xl hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                >
                    {isSaving ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</> : <><Check className="w-4 h-4" /> Save Pipeline</>}
                </button>
            </div>
        </div>
    );
}
