"use client";
import { useEffect, useState } from "react";

interface Template {
  id: string;
  name: string;
  description: string;
  category: string;
  icon: string;
  color: string;
  nodeCount: number;
  nodes: any[];
  edges: any[];
}

// Map template category → trigger type used by GenerateFlowModal
const CATEGORY_TO_TRIGGER: Record<string, string> = {
  "Booking":    "booking_created",
  "Recovery":   "no_show",
  "Feedback":   "completed",
  "Onboarding": "custom",
};

// Category badge colours
const CAT_STYLE: Record<string, { bg: string; text: string; border: string }> = {
  "Booking":    { bg: "bg-emerald-50",  text: "text-emerald-700", border: "border-emerald-200" },
  "Recovery":   { bg: "bg-amber-50",    text: "text-amber-700",   border: "border-amber-200"   },
  "Feedback":   { bg: "bg-blue-50",     text: "text-blue-700",    border: "border-blue-200"    },
  "Onboarding": { bg: "bg-violet-50",   text: "text-violet-700",  border: "border-violet-200"  },
};

export default function TemplatesModal({
  onLoad,
  onClose,
  onOpenAIGenerator,
}: {
  onLoad: (nodes: any[], edges: any[], name: string) => void;
  onClose: () => void;
  onOpenAIGenerator?: (templateType: string) => void;
}) {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [loading, setLoading]     = useState(true);
  const [loadingId, setLoadingId] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/chatbot-canvas/templates")
      .then(r => r.json())
      .then(setTemplates)
      .finally(() => setLoading(false));
  }, []);

  function handleLoad(t: Template) {
    setLoadingId(t.id);
    // slight delay so the button shows feedback
    setTimeout(() => {
      onLoad(t.nodes, t.edges, t.name);
    }, 150);
  }

  function handleGenerateAI(t: Template) {
    const triggerType = CATEGORY_TO_TRIGGER[t.category] ?? "custom";
    onOpenAIGenerator?.(triggerType);
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
      <div
        className="bg-white rounded-3xl shadow-2xl overflow-hidden flex flex-col modal-enter"
        style={{ width: 680, maxHeight: "88vh" }}
      >
        {/* Header */}
        <div className="bg-gradient-to-r from-indigo-600 to-violet-600 px-6 py-5 shrink-0 flex items-center gap-4">
          <div className="w-11 h-11 rounded-2xl bg-white/20 flex items-center justify-center text-2xl shrink-0">📋</div>
          <div className="flex-1">
            <h2 className="text-white font-bold text-[16px]">Choose a Template</h2>
            <p className="text-white/65 text-[11px] mt-0.5">
              Load instantly — or hit <span className="text-white font-bold">🪄 Generate with AI</span> to customise it your way
            </p>
          </div>
          <button onClick={onClose} className="text-white/60 hover:text-white text-xl p-1">✕</button>
        </div>

        {/* Grid */}
        <div className="flex-1 overflow-y-auto p-5">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-16 text-gray-400">
              <div className="text-4xl mb-3 animate-pulse">📋</div>
              <p className="text-[13px] font-semibold">Loading templates…</p>
            </div>
          ) : (
            <div className="grid grid-cols-2 gap-4">
              {templates.map(t => {
                const cat   = CAT_STYLE[t.category] ?? CAT_STYLE["Booking"];
                const busy  = loadingId === t.id;
                return (
                  <div
                    key={t.id}
                    className="flex flex-col rounded-2xl border border-gray-100 bg-white shadow-sm hover:shadow-md transition-shadow overflow-hidden"
                  >
                    {/* Card body */}
                    <div className="p-4 flex-1">
                      {/* Icon + name + badge */}
                      <div className="flex items-start gap-3 mb-3">
                        <div
                          className="w-11 h-11 rounded-xl flex items-center justify-center text-2xl shrink-0"
                          style={{ background: t.color + "15", border: `1.5px solid ${t.color}30` }}
                        >
                          {t.icon}
                        </div>
                        <div className="flex-1 min-w-0 pt-0.5">
                          <p className="text-[13px] font-bold text-gray-800 leading-tight">{t.name}</p>
                          <span className={`inline-block mt-1 text-[9px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full border ${cat.bg} ${cat.text} ${cat.border}`}>
                            {t.category}
                          </span>
                        </div>
                      </div>

                      <p className="text-[11px] text-gray-500 leading-relaxed mb-3">{t.description}</p>

                      <p className="text-[10px] text-gray-300 font-semibold">🔷 {t.nodeCount} blocks</p>
                    </div>

                    {/* Action row — always visible, no selection needed */}
                    <div className="flex border-t border-gray-100">
                      {/* Load */}
                      <button
                        onClick={() => handleLoad(t)}
                        disabled={busy}
                        className="flex-1 flex items-center justify-center gap-1.5 py-3 text-[11px] font-bold text-gray-600 hover:bg-gray-50 transition border-r border-gray-100 disabled:opacity-50"
                      >
                        {busy ? <span className="w-3.5 h-3.5 border-2 border-gray-400 border-t-transparent rounded-full animate-spin" /> : <span>📂</span>}
                        {busy ? "Loading…" : "Load"}
                      </button>

                      {/* Generate with AI */}
                      <button
                        onClick={() => handleGenerateAI(t)}
                        className="flex-1 flex items-center justify-center gap-1.5 py-3 text-[11px] font-bold text-white transition hover:opacity-90"
                        style={{ background: "linear-gradient(135deg, #7c3aed, #ec4899)" }}
                      >
                        <span>🪄</span> Generate with AI
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer — just a close */}
        <div className="px-5 py-3 border-t border-gray-100 shrink-0">
          <button
            onClick={onClose}
            className="w-full py-2.5 rounded-2xl text-[12px] font-semibold text-gray-400 hover:text-gray-600 hover:bg-gray-50 transition"
          >
            Cancel
          </button>
        </div>
      </div>
    </div>
  );
}
