"use client";

import { useState, useEffect } from "react";
import Link from "next/link";

interface ReminderTree {
  id: string;
  name: string;
  description: string | null;
  triggerType: string;
  isActive: boolean;
  version: number;
  createdAt: string;
  _count: { nodes: number; userJourneys: number };
}

interface TreeNode {
  id: string;
  name: string;
  nodeType: string;
  parentId: string | null;
  sortOrder: number;
  children: TreeNode[];
}

const TRIGGER_META: Record<string, { icon: string; label: string; color: string; bg: string }> = {
  booking_created: { icon: "📋", label: "New Booking",       color: "#6366f1", bg: "#eef2ff" },
  no_show:         { icon: "😔", label: "No-Show",           color: "#dc2626", bg: "#fee2e2" },
  completed:       { icon: "✅", label: "Treatment Done",    color: "#059669", bg: "#d1fae5" },
  custom:          { icon: "⚡", label: "Custom Trigger",    color: "#d97706", bg: "#fef3c7" },
};

const NODE_META: Record<string, { icon: string; color: string; bg: string }> = {
  message:     { icon: "💬", color: "#0284c7", bg: "#e0f2fe" },
  buttons:     { icon: "🔘", color: "#059669", bg: "#d1fae5" },
  ai_response: { icon: "🤖", color: "#7c3aed", bg: "#ede9fe" },
  condition:   { icon: "🔀", color: "#d97706", bg: "#fef3c7" },
  wait:        { icon: "⏳", color: "#475569", bg: "#f1f5f9" },
  end:         { icon: "✅", color: "#dc2626", bg: "#fee2e2" },
  send_message:{ icon: "💬", color: "#0284c7", bg: "#e0f2fe" },
  send_buttons:{ icon: "🔘", color: "#059669", bg: "#d1fae5" },
  action:      { icon: "⚡", color: "#d97706", bg: "#fef3c7" },
  collect_input:{ icon:"📝", color: "#ec4899", bg: "#fdf2f8" },
};

export default function ReminderTreesPage() {
  const [trees, setTrees]           = useState<ReminderTree[]>([]);
  const [selected, setSelected]     = useState<ReminderTree | null>(null);
  const [nodes, setNodes]           = useState<TreeNode[]>([]);
  const [loading, setLoading]       = useState(true);
  const [nodesLoading, setNodesLoading] = useState(false);
  const [creating, setCreating]     = useState(false);
  const [toggling, setToggling]     = useState<string | null>(null);
  const [toast, setToast]           = useState<{ msg: string; ok: boolean } | null>(null);

  const showToast = (msg: string, ok = true) => {
    setToast({ msg, ok });
    setTimeout(() => setToast(null), 3000);
  };

  const loadTrees = async () => {
    setLoading(true);
    try {
      const r = await fetch("/api/admin/reminder-trees");
      const d = await r.json();
      setTrees(Array.isArray(d) ? d : []);
    } catch { showToast("Failed to load trees", false); }
    finally { setLoading(false); }
  };

  const loadNodes = async (tree: ReminderTree) => {
    setSelected(tree);
    setNodesLoading(true);
    try {
      const r = await fetch(`/api/admin/reminder-trees/${tree.id}/nodes`);
      const d = await r.json();
      setNodes(Array.isArray(d) ? d : []);
    } catch { showToast("Failed to load nodes", false); }
    finally { setNodesLoading(false); }
  };

  const toggle = async (tree: ReminderTree) => {
    setToggling(tree.id);
    try {
      const r = await fetch(`/api/admin/reminder-trees/${tree.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isActive: !tree.isActive }),
      });
      if (!r.ok) throw new Error("Failed");
      showToast(tree.isActive ? "Tree deactivated" : "Tree activated ✅");
      await loadTrees();
      if (selected?.id === tree.id) setSelected(prev => prev ? {...prev, isActive: !prev.isActive} : null);
    } catch { showToast("Toggle failed", false); }
    finally { setToggling(null); }
  };

  const createDemo = async () => {
    setCreating(true);
    try {
      const r = await fetch("/api/admin/reminder-trees/create-demo", { method: "POST" });
      if (!r.ok) throw new Error("Failed");
      showToast("🎉 Demo trees created!");
      await loadTrees();
    } catch { showToast("Failed to create demo trees", false); }
    finally { setCreating(false); }
  };

  useEffect(() => { loadTrees(); }, []);

  const rootNodes = nodes.filter(n => !n.parentId);

  return (
    <div className="min-h-screen" style={{ background: "linear-gradient(135deg,#f0f4ff 0%,#fafafa 50%,#f5f0ff 100%)" }}>
      <div className="max-w-7xl mx-auto px-6 py-8">

        {/* ── Header ── */}
        <div className="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 className="text-2xl font-black text-gray-900 flex items-center gap-2">
              🌳 Reminder Trees
            </h1>
            <p className="text-[13px] text-gray-500 mt-1">
              Manage WhatsApp conversation trees that run automatically for patients
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href="/chatbot-canvas"
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-[13px] font-bold text-white shadow-lg transition hover:scale-105 active:scale-95"
              style={{ background: "linear-gradient(135deg,#6366f1,#8b5cf6)" }}>
              <span>🎨</span> Visual Canvas Builder
            </Link>
            <button onClick={createDemo} disabled={creating}
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-[13px] font-bold text-white shadow transition hover:opacity-90 disabled:opacity-60"
              style={{ background: "linear-gradient(135deg,#ec4899,#f43f5e)" }}>
              {creating
                ? <><span className="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"/>Creating…</>
                : <><span>🎬</span> Create Demo Trees</>}
            </button>
          </div>
        </div>

        {/* ── Stats strip ── */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
          {[
            { label: "Total Trees",    value: trees.length,                   icon: "🌳", color: "#6366f1" },
            { label: "Active",         value: trees.filter(t => t.isActive).length, icon: "✅", color: "#059669" },
            { label: "Total Nodes",    value: trees.reduce((a,t) => a+(t._count?.nodes||0),0), icon: "📦", color: "#0284c7" },
            { label: "Journeys Run",   value: trees.reduce((a,t) => a+(t._count?.userJourneys||0),0), icon: "🚀", color: "#d97706" },
          ].map(s => (
            <div key={s.label} className="bg-white rounded-2xl border border-gray-100 shadow-sm px-4 py-3 flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center text-xl flex-shrink-0"
                style={{ background: s.color + "18" }}>
                {s.icon}
              </div>
              <div>
                <p className="text-xl font-black text-gray-900">{s.value}</p>
                <p className="text-[11px] text-gray-500 font-semibold">{s.label}</p>
              </div>
            </div>
          ))}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
          {/* ── Trees list ── */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
              <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
                <div>
                  <p className="font-bold text-gray-900 text-[14px]">All Trees</p>
                  <p className="text-[11px] text-gray-400">{trees.length} flow{trees.length !== 1 ? "s" : ""}</p>
                </div>
                {loading && <span className="w-4 h-4 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />}
              </div>

              <div className="divide-y divide-gray-50 max-h-[540px] overflow-y-auto">
                {!loading && trees.length === 0 ? (
                  <div className="flex flex-col items-center py-16 px-6 text-center">
                    <div className="text-5xl mb-3">🌱</div>
                    <p className="font-bold text-gray-700 text-[14px]">No trees yet</p>
                    <p className="text-[12px] text-gray-400 mt-1 mb-4">
                      Create demo trees or build one in the Visual Canvas Builder
                    </p>
                    <button onClick={createDemo} disabled={creating}
                      className="px-4 py-2 rounded-xl text-[12px] font-bold text-white transition"
                      style={{ background: "linear-gradient(135deg,#6366f1,#8b5cf6)" }}>
                      🎬 Create Demo Trees
                    </button>
                  </div>
                ) : (
                  trees.map(tree => {
                    const meta = TRIGGER_META[tree.triggerType] ?? TRIGGER_META.custom;
                    const isSelected = selected?.id === tree.id;
                    return (
                      <div key={tree.id}
                        onClick={() => loadNodes(tree)}
                        className={`px-5 py-4 cursor-pointer transition-all hover:bg-gray-50 ${isSelected ? "bg-indigo-50 border-l-4 border-indigo-500" : "border-l-4 border-transparent"}`}
                      >
                        <div className="flex items-start gap-3">
                          <div className="w-9 h-9 rounded-xl flex items-center justify-center text-lg flex-shrink-0"
                            style={{ background: meta.bg }}>
                            {meta.icon}
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-0.5">
                              <p className="font-bold text-gray-800 text-[13px] truncate">{tree.name}</p>
                              <span className={`flex-shrink-0 w-2 h-2 rounded-full ${tree.isActive ? "bg-emerald-400" : "bg-gray-300"}`} />
                            </div>
                            <div className="flex items-center gap-1.5 flex-wrap mb-2">
                              <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full"
                                style={{ background: meta.bg, color: meta.color }}>
                                {meta.label}
                              </span>
                              <span className="text-[10px] text-gray-400">v{tree.version}</span>
                            </div>
                            <div className="flex items-center justify-between">
                              <div className="flex gap-3 text-[10px] text-gray-400 font-semibold">
                                <span>📦 {tree._count?.nodes || 0} nodes</span>
                                <span>🚀 {tree._count?.userJourneys || 0} runs</span>
                              </div>
                              <button
                                disabled={toggling === tree.id}
                                onClick={e => { e.stopPropagation(); toggle(tree); }}
                                className={`text-[10px] font-bold px-2.5 py-1 rounded-lg border transition ${
                                  tree.isActive
                                    ? "border-emerald-200 text-emerald-700 bg-emerald-50 hover:bg-emerald-100"
                                    : "border-gray-200 text-gray-500 bg-gray-50 hover:bg-gray-100"
                                }`}
                              >
                                {toggling === tree.id
                                  ? "…"
                                  : tree.isActive ? "✅ Active" : "⏸ Inactive"}
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </div>
          </div>

          {/* ── Tree detail ── */}
          <div className="lg:col-span-3 space-y-4">
            {!selected ? (
              <div className="bg-white rounded-2xl border border-gray-100 shadow-sm flex flex-col items-center justify-center py-24 text-center">
                <div className="text-6xl mb-4">🌳</div>
                <p className="font-bold text-gray-700 text-[15px]">Select a tree to inspect it</p>
                <p className="text-[12px] text-gray-400 mt-1">Click any tree on the left to see its structure and stats</p>
              </div>
            ) : (
              <>
                {/* Detail header */}
                <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                  <div className="px-5 py-4 border-b border-gray-50 flex items-center gap-3">
                    <div className="w-10 h-10 rounded-xl flex items-center justify-center text-xl"
                      style={{ background: (TRIGGER_META[selected.triggerType] ?? TRIGGER_META.custom).bg }}>
                      {(TRIGGER_META[selected.triggerType] ?? TRIGGER_META.custom).icon}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-black text-gray-900 text-[15px]">{selected.name}</p>
                      <p className="text-[11px] text-gray-500">{selected.description || "No description"}</p>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className={`text-[11px] font-bold px-2.5 py-1 rounded-full ${selected.isActive ? "bg-emerald-100 text-emerald-700" : "bg-gray-100 text-gray-500"}`}>
                        {selected.isActive ? "✅ Live" : "⏸ Paused"}
                      </span>
                      <Link href="/chatbot-canvas"
                        className="text-[11px] font-bold px-2.5 py-1.5 rounded-xl text-white transition hover:opacity-90"
                        style={{ background: "linear-gradient(135deg,#6366f1,#8b5cf6)" }}>
                        ✏️ Edit in Canvas
                      </Link>
                    </div>
                  </div>

                  {/* Node stats */}
                  <div className="grid grid-cols-4 divide-x divide-gray-50">
                    {[
                      { label: "Messages",    count: nodes.filter(n => ["message","send_message"].includes(n.nodeType)).length, icon:"💬", color:"#0284c7" },
                      { label: "Interactive", count: nodes.filter(n => ["buttons","send_buttons"].includes(n.nodeType)).length, icon:"🔘", color:"#059669" },
                      { label: "AI Replies",  count: nodes.filter(n => n.nodeType==="ai_response").length, icon:"🤖", color:"#7c3aed" },
                      { label: "Branches",    count: nodes.filter(n => n.nodeType==="condition").length, icon:"🔀", color:"#d97706" },
                    ].map(s => (
                      <div key={s.label} className="px-4 py-3 text-center">
                        <p className="text-xl font-black" style={{ color: s.color }}>{s.count}</p>
                        <p className="text-[10px] text-gray-400 font-semibold">{s.label}</p>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Node tree */}
                <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                  <div className="px-5 py-3.5 border-b border-gray-50 flex items-center gap-2">
                    <p className="font-bold text-gray-800 text-[13px]">Flow Structure</p>
                    {nodesLoading && <span className="w-3.5 h-3.5 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin ml-1" />}
                    <span className="ml-auto text-[11px] text-gray-400">{nodes.length} total blocks</span>
                  </div>
                  <div className="p-4 max-h-96 overflow-y-auto">
                    {nodes.length === 0 && !nodesLoading ? (
                      <div className="text-center py-8 text-gray-400">
                        <div className="text-3xl mb-2">📭</div>
                        <p className="text-[12px] font-semibold">No nodes in this tree yet</p>
                        <p className="text-[11px] mt-1">Build one in the <Link href="/chatbot-canvas" className="text-indigo-600 underline">Canvas Builder</Link></p>
                      </div>
                    ) : (
                      <NodeTree nodes={rootNodes} allNodes={nodes} depth={0} />
                    )}
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Toast */}
      {toast && (
        <div className={`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-5 py-3 rounded-2xl text-[13px] font-bold text-white shadow-xl ${toast.ok ? "bg-gray-900" : "bg-red-500"}`}>
          {toast.msg}
        </div>
      )}
    </div>
  );
}

function NodeTree({ nodes, allNodes, depth }: { nodes: TreeNode[]; allNodes: TreeNode[]; depth: number }) {
  return (
    <div className={depth > 0 ? "ml-5 border-l-2 border-dashed border-gray-100 pl-3 mt-1 space-y-1" : "space-y-1.5"}>
      {nodes.map(node => {
        const meta = NODE_META[node.nodeType] ?? { icon: "📦", color: "#6b7280", bg: "#f3f4f6" };
        const children = allNodes.filter(n => n.parentId === node.id);
        return (
          <div key={node.id}>
            <div className="flex items-center gap-2.5 px-3 py-2 rounded-xl border"
              style={{ background: meta.bg, borderColor: meta.color + "30" }}>
              <span className="text-[15px] flex-shrink-0">{meta.icon}</span>
              <div className="flex-1 min-w-0">
                <p className="text-[12px] font-bold truncate" style={{ color: meta.color }}>{node.name}</p>
                <p className="text-[10px] text-gray-400">{node.nodeType} · order {node.sortOrder}</p>
              </div>
              {children.length > 0 && (
                <span className="text-[10px] font-bold px-1.5 py-0.5 rounded-full text-white"
                  style={{ background: meta.color }}>
                  {children.length}↓
                </span>
              )}
            </div>
            {children.length > 0 && <NodeTree nodes={children} allNodes={allNodes} depth={depth + 1} />}
          </div>
        );
      })}
    </div>
  );
}
