"use client";

import { useState } from "react";
import {
    Plus, GitBranch, Trash2, Copy, Edit3, ChevronRight,
    Zap, Users, Clock, Layers, X, ArrowLeft
} from "lucide-react";
import { PipelineBuilder } from "./PipelineBuilder";
import { deletePipeline, duplicatePipeline, createPipelineFromTemplate } from "@/app/actions/pipelineBuilderActions";
import { PipelineTemplate } from "@/lib/pipelineConstants";

interface Stage {
    id: string;
    name: string;
    color: string;
    stage_type?: string;
    order: number;
}

interface Pipeline {
    id: string;
    name: string;
    stages: Stage[];
    _count?: { stages: number };
    created_at: string;
}

interface Template {
    key: string;
    name: string;
    stageCount: number;
}

interface Props {
    initialPipelines: Pipeline[];
    templates: Template[];
}

export function PipelineManagementClient({ initialPipelines, templates }: Props) {
    const [pipelines, setPipelines] = useState<Pipeline[]>(initialPipelines);
    const [view, setView] = useState<"list" | "create" | "edit">("list");
    const [editingPipeline, setEditingPipeline] = useState<Pipeline | null>(null);
    const [showTemplates, setShowTemplates] = useState(false);
    const [loadingId, setLoadingId] = useState<string | null>(null);

    const handleDelete = async (id: string) => {
        if (!confirm("Delete this pipeline? This cannot be undone.")) return;
        setLoadingId(id);
        const result = await deletePipeline(id);
        if (result.success) {
            setPipelines(prev => prev.filter(p => p.id !== id));
        } else {
            alert(result.error || "Cannot delete pipeline.");
        }
        setLoadingId(null);
    };

    const handleDuplicate = async (id: string) => {
        setLoadingId(id);
        const result = await duplicatePipeline(id);
        if (result.success && result.pipeline) {
            setPipelines(prev => [result.pipeline as any, ...prev]);
        }
        setLoadingId(null);
    };

    const handleFromTemplate = async (key: string) => {
        setLoadingId(key);
        const result = await createPipelineFromTemplate(key as PipelineTemplate);
        if (result.success && result.pipeline) {
            setPipelines(prev => [result.pipeline as any, ...prev]);
        }
        setShowTemplates(false);
        setLoadingId(null);
    };

    if (view === "create" || view === "edit") {
        return (
            <div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden" style={{ minHeight: "70vh" }}>
                <div className="flex items-center gap-3 p-6 border-b border-slate-100">
                    <button onClick={() => { setView("list"); setEditingPipeline(null); }} className="p-2 hover:bg-slate-100 rounded-xl text-slate-500 transition-colors">
                        <ArrowLeft className="w-4 h-4" />
                    </button>
                    <div>
                        <h2 className="text-lg font-bold text-slate-800">{view === "edit" ? "Edit Pipeline" : "Create New Pipeline"}</h2>
                        <p className="text-sm text-slate-500">Drag to reorder stages, click to edit details</p>
                    </div>
                </div>
                <PipelineBuilder
                    pipelineId={editingPipeline?.id}
                    initialName={editingPipeline?.name}
                    initialStages={editingPipeline?.stages.map(s => ({ ...s, stage_type: s.stage_type || 'interview', tempId: s.id }))}
                    onSuccess={() => { setView("list"); window.location.reload(); }}
                    onCancel={() => { setView("list"); setEditingPipeline(null); }}
                />
            </div>
        );
    }

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-2xl font-extrabold text-slate-900">Hiring Pipelines</h1>
                    <p className="text-sm text-slate-500 mt-1">Create and manage custom hiring stages for your jobs.</p>
                </div>
                <div className="flex gap-2">
                    <button
                        onClick={() => setShowTemplates(!showTemplates)}
                        className="flex items-center gap-2 px-4 py-2.5 text-sm font-bold text-primary bg-primary/10 rounded-xl hover:bg-primary/20 transition-colors"
                    >
                        <Zap className="w-4 h-4" /> Use Template
                    </button>
                    <button
                        onClick={() => setView("create")}
                        className="flex items-center gap-2 px-4 py-2.5 text-sm font-bold text-white bg-primary rounded-xl hover:bg-primary/90 transition-colors"
                    >
                        <Plus className="w-4 h-4" /> Create Pipeline
                    </button>
                </div>
            </div>

            {/* Templates */}
            {showTemplates && (
                <div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm">
                    <div className="flex items-center justify-between mb-4">
                        <h2 className="text-sm font-bold text-slate-700">Choose a Template</h2>
                        <button onClick={() => setShowTemplates(false)} className="text-slate-400 hover:text-slate-600"><X className="w-4 h-4" /></button>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                        {templates.map(t => (
                            <button
                                key={t.key}
                                onClick={() => handleFromTemplate(t.key)}
                                disabled={loadingId === t.key}
                                className="p-4 text-left border border-slate-200 rounded-xl hover:border-primary hover:bg-primary/5 transition-all group disabled:opacity-50"
                            >
                                <Layers className="w-5 h-5 text-primary mb-2" />
                                <p className="text-sm font-bold text-slate-800">{t.name}</p>
                                <p className="text-xs text-slate-400 mt-0.5">{t.stageCount} stages</p>
                            </button>
                        ))}
                    </div>
                </div>
            )}

            {/* Pipeline Cards */}
            {pipelines.length === 0 ? (
                <div className="bg-white border-2 border-dashed border-slate-200 rounded-2xl p-12 text-center">
                    <GitBranch className="w-10 h-10 text-slate-300 mx-auto mb-3" />
                    <h3 className="text-base font-bold text-slate-600 mb-1">No pipelines yet</h3>
                    <p className="text-sm text-slate-400 mb-4">Create a custom pipeline or start from a template.</p>
                    <button onClick={() => setView("create")} className="px-6 py-2.5 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" /> Create your first pipeline
                    </button>
                </div>
            ) : (
                <div className="grid grid-cols-1 gap-4">
                    {pipelines.map(pipeline => (
                        <div key={pipeline.id} className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm hover:shadow-md transition-shadow">
                            <div className="flex items-start justify-between">
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-2 mb-1">
                                        <GitBranch className="w-4 h-4 text-primary flex-shrink-0" />
                                        <h3 className="text-base font-bold text-slate-800 truncate">{pipeline.name}</h3>
                                    </div>
                                    <div className="flex items-center gap-4 text-xs text-slate-400 mb-4">
                                        <span className="flex items-center gap-1"><Layers className="w-3 h-3" /> {pipeline.stages.length} stages</span>
                                    </div>
                                    {/* Stage preview pills */}
                                    <div className="flex flex-wrap gap-1.5">
                                        {pipeline.stages.sort((a, b) => a.order - b.order).slice(0, 8).map((s, i) => (
                                            <span key={s.id} className="flex items-center gap-1 text-xs px-2.5 py-1 rounded-full font-medium text-white" style={{ backgroundColor: s.color }}>
                                                {i + 1}. {s.name}
                                            </span>
                                        ))}
                                        {pipeline.stages.length > 8 && (
                                            <span className="text-xs px-2.5 py-1 rounded-full bg-slate-100 text-slate-500 font-medium">
                                                +{pipeline.stages.length - 8} more
                                            </span>
                                        )}
                                    </div>
                                </div>
                                <div className="flex items-center gap-1.5 ml-4">
                                    <button
                                        onClick={() => { setEditingPipeline(pipeline); setView("edit"); }}
                                        className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                                        title="Edit"
                                    >
                                        <Edit3 className="w-4 h-4" />
                                    </button>
                                    <button
                                        onClick={() => handleDuplicate(pipeline.id)}
                                        disabled={loadingId === pipeline.id}
                                        className="p-2 text-slate-400 hover:text-violet-600 hover:bg-violet-50 rounded-lg transition-colors"
                                        title="Duplicate"
                                    >
                                        <Copy className="w-4 h-4" />
                                    </button>
                                    <button
                                        onClick={() => handleDelete(pipeline.id)}
                                        disabled={loadingId === pipeline.id}
                                        className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                        title="Delete"
                                    >
                                        <Trash2 className="w-4 h-4" />
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
