"use client";

import { useState, useEffect, useCallback } from "react";
import {
    BookTemplate, Plus, Trash2, Download, Upload, Check,
    ChevronRight, Edit3, Copy, Loader2, X, Save, FileJson
} from "lucide-react";
import { clsx } from "clsx";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";

interface JobTemplate {
    id: string;
    name: string;
    description: string;
    config: Record<string, any>;
    createdAt: string;
    updatedAt: string;
}

interface TemplateSelectorProps {
    currentConfig?: Record<string, any>;
    onApply?: (config: Record<string, any>) => void;
    compact?: boolean;
}

export default function TemplateSelector({ currentConfig, onApply, compact = false }: TemplateSelectorProps) {
    const [templates, setTemplates] = useState<JobTemplate[]>([]);
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [showSaveModal, setShowSaveModal] = useState(false);
    const [newName, setNewName] = useState("");
    const [newDesc, setNewDesc] = useState("");
    const [selectedId, setSelectedId] = useState<string | null>(null);

    const authHeaders = useCallback(() => {
        const token = typeof window !== "undefined" ? localStorage.getItem("mhb_token") : "";
        return { "Content-Type": "application/json", Authorization: `Bearer ${token}` };
    }, []);

    async function loadTemplates() {
        setLoading(true);
        try {
            const res = await fetch(`${API}/api/templates`, { headers: authHeaders() });
            const data = await res.json();
            setTemplates(data.templates || []);
        } finally { setLoading(false); }
    }

    useEffect(() => { loadTemplates(); }, []);

    async function handleSaveAsTemplate() {
        if (!newName.trim()) return;
        setSaving(true);
        try {
            const res = await fetch(`${API}/api/templates`, {
                method: "POST", headers: authHeaders(),
                body: JSON.stringify({ name: newName, description: newDesc, config: currentConfig || {} }),
            });
            const data = await res.json();
            if (data.success) {
                setShowSaveModal(false);
                setNewName(""); setNewDesc("");
                loadTemplates();
            }
        } finally { setSaving(false); }
    }

    async function handleDelete(id: string, e: React.MouseEvent) {
        e.stopPropagation();
        await fetch(`${API}/api/templates/${id}`, { method: "DELETE", headers: authHeaders() });
        setTemplates(prev => prev.filter(t => t.id !== id));
    }

    async function handleExport() {
        const res = await fetch(`${API}/api/templates/export`, { method: "POST", headers: authHeaders() });
        const blob = await res.blob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a"); a.href = url; a.download = "mhbd-templates.json"; a.click();
        URL.revokeObjectURL(url);
    }

    async function handleImport(e: React.ChangeEvent<HTMLInputElement>) {
        const file = e.target.files?.[0];
        if (!file) return;
        const json = JSON.parse(await file.text());
        await fetch(`${API}/api/templates/import`, {
            method: "POST", headers: authHeaders(),
            body: JSON.stringify({ templates: json.templates || [], merge: true }),
        });
        loadTemplates();
        e.target.value = "";
    }

    if (compact) {
        return (
            <div className="space-y-2">
                <div className="flex items-center justify-between">
                    <p className="text-[10px] font-black uppercase tracking-widest text-white/30">Templates</p>
                    {currentConfig && (
                        <button onClick={() => setShowSaveModal(true)} className="text-[9px] font-black text-accent-cyan hover:text-cyan-300 transition-colors flex items-center gap-1">
                            <Plus className="w-2.5 h-2.5" /> Save Current
                        </button>
                    )}
                </div>
                {loading ? <Loader2 className="w-4 h-4 animate-spin text-white/30" /> : (
                    <div className="space-y-1 max-h-48 overflow-y-auto custom-scrollbar">
                        {templates.length === 0 && <p className="text-xs text-white/20">No templates yet</p>}
                        {templates.map(t => (
                            <div
                                key={t.id}
                                onClick={() => { setSelectedId(t.id); onApply?.(t.config); }}
                                className={clsx(
                                    "flex items-center justify-between p-2.5 rounded-lg cursor-pointer transition-all group",
                                    selectedId === t.id ? "bg-accent-cyan/10 border border-accent-cyan/20" : "hover:bg-white/5"
                                )}
                            >
                                <div className="flex-1 min-w-0">
                                    <p className="text-xs font-bold text-white truncate">{t.name}</p>
                                    {t.description && <p className="text-[9px] text-white/30 truncate">{t.description}</p>}
                                </div>
                                <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-all">
                                    <button onClick={(e) => handleDelete(t.id, e)} className="p-1 rounded text-red-400/60 hover:text-red-400">
                                        <Trash2 className="w-3 h-3" />
                                    </button>
                                </div>
                                {selectedId === t.id && <Check className="w-3 h-3 text-accent-cyan ml-1 shrink-0" />}
                            </div>
                        ))}
                    </div>
                )}

                {/* Save Modal */}
                {showSaveModal && (
                    <div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/80 backdrop-blur-sm">
                        <div className="bg-[#0f1117] border border-white/10 rounded-2xl p-6 w-full max-w-sm shadow-2xl">
                            <h3 className="font-black text-white mb-4">Save as Template</h3>
                            <input value={newName} onChange={e => setNewName(e.target.value)} placeholder="Template name..." className="input w-full mb-3" />
                            <input value={newDesc} onChange={e => setNewDesc(e.target.value)} placeholder="Description (optional)" className="input w-full mb-4" />
                            <div className="flex gap-2">
                                <button onClick={() => setShowSaveModal(false)} className="flex-1 btn-ghost py-2.5 text-sm">Cancel</button>
                                <button onClick={handleSaveAsTemplate} disabled={!newName || saving} className="flex-1 btn-primary py-2.5 text-sm">
                                    {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />} Save
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        );
    }

    // Full page view
    return (
        <div className="space-y-6 max-w-3xl mx-auto pb-20">
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-violet-500/10 flex items-center justify-center">
                        <BookTemplate className="w-6 h-6 text-violet-400" />
                    </div>
                    <div>
                        <h1 className="text-2xl font-extrabold text-white">Job Templates</h1>
                        <p className="text-white/40 text-sm">Save and reapply full job configurations in one click.</p>
                    </div>
                </div>
                <div className="flex items-center gap-2">
                    <label className="btn-ghost py-2 px-4 flex items-center gap-2 text-sm cursor-pointer">
                        <Upload className="w-4 h-4" /> Import
                        <input type="file" accept=".json" onChange={handleImport} className="hidden" />
                    </label>
                    <button onClick={handleExport} className="btn-ghost py-2 px-4 flex items-center gap-2 text-sm">
                        <Download className="w-4 h-4" /> Export
                    </button>
                    <button onClick={() => setShowSaveModal(true)} className="btn-primary py-2 px-4 flex items-center gap-2 text-sm">
                        <Plus className="w-4 h-4" /> New Template
                    </button>
                </div>
            </div>

            {loading ? (
                <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-accent-cyan" /></div>
            ) : templates.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-20 text-white/20">
                    <FileJson className="w-12 h-12 mb-4" />
                    <p className="text-lg font-bold">No templates yet</p>
                    <p className="text-sm mt-1">Create a template from the File Downloader while configuring a job.</p>
                </div>
            ) : (
                <div className="space-y-3">
                    {templates.map(t => (
                        <div key={t.id} className="card p-5 bg-black/40 border-white/10 flex items-center gap-4 hover:border-white/20 transition-all group">
                            <div className="w-10 h-10 rounded-xl bg-violet-500/10 flex items-center justify-center shrink-0">
                                <BookTemplate className="w-5 h-5 text-violet-400" />
                            </div>
                            <div className="flex-1 min-w-0">
                                <p className="font-black text-white text-sm">{t.name}</p>
                                {t.description && <p className="text-xs text-white/40 mt-0.5">{t.description}</p>}
                                <p className="text-[10px] text-white/20 mt-1">Updated {new Date(t.updatedAt).toLocaleDateString()}</p>
                            </div>
                            <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-all">
                                <button onClick={() => onApply?.(t.config)} className="px-4 py-2 rounded-xl bg-accent-cyan/10 text-accent-cyan text-xs font-black hover:bg-accent-cyan/20 border border-accent-cyan/20 transition-all flex items-center gap-1.5">
                                    <ChevronRight className="w-3 h-3" /> Apply
                                </button>
                                <button onClick={(e) => handleDelete(t.id, e)} className="px-3 py-2 rounded-xl bg-red-500/10 text-red-400 text-xs font-black hover:bg-red-500/20 transition-all">
                                    <Trash2 className="w-3.5 h-3.5" />
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {showSaveModal && (
                <div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/80 backdrop-blur-sm">
                    <div className="bg-[#0f1117] border border-white/10 rounded-2xl p-6 w-full max-w-sm shadow-2xl">
                        <h3 className="font-black text-white mb-4">New Template</h3>
                        <input value={newName} onChange={e => setNewName(e.target.value)} placeholder="Template name..." className="input w-full mb-3" />
                        <input value={newDesc} onChange={e => setNewDesc(e.target.value)} placeholder="Description (optional)" className="input w-full mb-4" />
                        <div className="flex gap-2">
                            <button onClick={() => setShowSaveModal(false)} className="flex-1 btn-ghost py-2.5 text-sm">Cancel</button>
                            <button onClick={handleSaveAsTemplate} disabled={!newName || saving} className="flex-1 btn-primary py-2.5 text-sm">
                                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />} Save
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
