"use client";
import { useState } from "react";
import { Node } from "reactflow";
import { NodeData, NodeKind, KIND_META } from "./nodes/nodeTypes";
import { nanoid } from "nanoid";

interface NodePanelProps {
  node: Node<NodeData> | null;
  onChange: (id: string, data: Partial<NodeData>) => void;
  onDelete: (id: string) => void;
  onAIGenerate: (id: string, field: string) => void;
  generating: boolean;
}

const VARS = [
  { key: "name",      label: "Patient name",      example: "Sarah" },
  { key: "treatment", label: "Treatment type",     example: "Cleaning" },
  { key: "clinic",    label: "Clinic name",        example: "Smile Clinic" },
  { key: "date",      label: "Appointment date",   example: "Monday, Mar 10" },
  { key: "time",      label: "Appointment time",   example: "2:30 PM" },
  { key: "phone",     label: "Patient phone",      example: "+96178…" },
];

export default function NodePanel({ node, onChange, onDelete, onAIGenerate, generating }: NodePanelProps) {
  const [activeTab, setActiveTab] = useState<"edit" | "ai">("edit");

  if (!node) {
    return (
      <div className="h-full flex flex-col bg-gray-50 border-l border-gray-200">
        {/* Header */}
        <div className="px-5 py-4 border-b border-gray-100 bg-white">
          <h3 className="text-[13px] font-bold text-gray-800">Node Settings</h3>
          <p className="text-[11px] text-gray-400 mt-0.5">Click any node on the canvas to edit it</p>
        </div>
        {/* Empty state */}
        <div className="flex-1 flex flex-col items-center justify-center px-6 gap-4">
          <div className="w-16 h-16 rounded-2xl bg-white border-2 border-dashed border-gray-200 flex items-center justify-center text-3xl shadow-sm">
            👆
          </div>
          <div className="text-center">
            <p className="text-[13px] font-semibold text-gray-600">Select a node to edit</p>
            <p className="text-[11px] text-gray-400 mt-1 leading-relaxed">
              Click any block on the canvas.<br />
              You can change its content here.
            </p>
          </div>
          {/* Tips */}
          <div className="w-full space-y-2 mt-2">
            {[
              { icon: "🖱️", tip: "Click a block to select it" },
              { icon: "↔️", tip: "Drag between handles to connect blocks" },
              { icon: "🗑️", tip: "Press Delete key to remove selected" },
              { icon: "🤖", tip: "Use AI to generate content" },
            ].map(({ icon, tip }) => (
              <div key={tip} className="flex items-start gap-2.5 px-3 py-2 rounded-xl bg-white border border-gray-100 shadow-sm">
                <span className="text-base leading-none mt-0.5">{icon}</span>
                <p className="text-[11px] text-gray-600">{tip}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  const d = node.data;
  const m = KIND_META[d.kind];
  const set = (patch: Partial<NodeData>) => onChange(node.id, patch);
  const canAI = ["message", "buttons", "condition", "retry", "save_var"].includes(d.kind);

  return (
    <div className="h-full flex flex-col bg-gray-50 border-l border-gray-200 overflow-hidden">
      {/* Node header */}
      <div className="border-b border-gray-100 bg-white">
        <div
          className="px-4 py-3 flex items-center gap-3"
          style={{ borderBottom: `3px solid ${m.color}` }}
        >
          <div
            className="w-9 h-9 rounded-xl flex items-center justify-center text-xl flex-shrink-0 shadow-sm"
            style={{ background: m.light, border: `1.5px solid ${m.border}` }}
          >
            {m.icon}
          </div>
          <div className="flex-1 min-w-0">
            <input
              className="w-full text-[13px] font-bold text-gray-800 bg-transparent border-none outline-none truncate"
              value={d.label}
              onChange={(e) => set({ label: e.target.value })}
              placeholder="Node name…"
            />
            <p className="text-[10px] font-semibold uppercase tracking-wider" style={{ color: m.color }}>
              {m.label}
            </p>
          </div>
          <button
            onClick={() => { if (confirm("Delete this node?")) onDelete(node.id); }}
            className="flex-shrink-0 p-1.5 rounded-lg text-gray-300 hover:text-red-500 hover:bg-red-50 transition"
            title="Delete node"
          >
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="3 6 5 6 21 6" /><path d="M19 6l-1 14H6L5 6" /><path d="M10 11v6M14 11v6" /><path d="M9 6V4h6v2" />
            </svg>
          </button>
        </div>

        {/* Tabs — only if AI is available */}
        {canAI && (
          <div className="flex px-4 gap-1 pb-2 pt-1">
            {[
              { id: "edit", label: "✏️ Edit Content" },
              { id: "ai",   label: "🤖 AI Generate" },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`flex-1 py-1.5 text-[11px] font-semibold rounded-lg transition ${
                  activeTab === tab.id
                    ? "bg-gray-900 text-white shadow-sm"
                    : "text-gray-500 hover:bg-gray-100"
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Scrollable body */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">

        {/* ══ START ══ */}
        {d.kind === "start" && (
          <Section title="When does this flow start?">
            <p className="text-[11px] text-gray-500 mb-2">Pick the event that triggers this chatbot sequence.</p>
            {[
              ["booking_created", "📋", "New Booking Created", "When a patient books an appointment"],
              ["no_show",         "😔", "Patient No-Show",     "When a patient misses their appointment"],
              ["completed",       "✅", "Treatment Completed", "When a treatment session is done"],
              ["custom",          "⚡", "Custom Trigger",      "Trigger manually or from your system"],
            ].map(([val, icon, label, desc]) => (
              <button
                key={val}
                onClick={() => set({ content: val })}
                className={`w-full flex items-center gap-3 p-3 rounded-xl border-2 text-left transition mb-1.5 ${
                  (d.content || "booking_created") === val
                    ? "border-indigo-500 bg-indigo-50"
                    : "border-gray-100 bg-white hover:border-indigo-200"
                }`}
              >
                <span className="text-xl">{icon}</span>
                <div>
                  <p className="text-[12px] font-semibold text-gray-800">{label}</p>
                  <p className="text-[10px] text-gray-400">{desc}</p>
                </div>
                {(d.content || "booking_created") === val && (
                  <span className="ml-auto text-indigo-500">✓</span>
                )}
              </button>
            ))}
          </Section>
        )}

        {/* ══ MESSAGE — Edit tab ══ */}
        {d.kind === "message" && activeTab === "edit" && (
          <>
            <Section title="📝 Message Content" hint="This exact text will be sent to the patient on WhatsApp">
              <textarea
                className="w-full px-3 py-2.5 text-[12px] rounded-xl border border-gray-200 bg-white text-gray-800
                           focus:outline-none focus:ring-2 focus:ring-sky-400 focus:border-transparent
                           transition resize-none min-h-[120px] leading-relaxed"
                value={d.content || ""}
                onChange={(e) => set({ content: e.target.value })}
                placeholder={"Hi {{name}}! 👋\n\nYour {{treatment}} appointment is on {{date}} at {{time}}.\n\nSee you at {{clinic}}! 💙"}
              />
              <p className="text-[10px] text-gray-400 mt-1">{(d.content || "").length} characters</p>
            </Section>
            <VarPicker onInsert={(v) => set({ content: (d.content || "") + `{{${v}}}` })} />
          </>
        )}

        {/* ══ BUTTONS — Edit tab ══ */}
        {d.kind === "buttons" && activeTab === "edit" && (
          <>
            <Section title="📝 Question to Patient" hint="The message shown above the buttons">
              <textarea
                className="field min-h-[80px]"
                value={d.content || ""}
                onChange={(e) => set({ content: e.target.value })}
                placeholder="Would you like to confirm your appointment, {{name}}?"
              />
            </Section>
            <VarPicker onInsert={(v) => set({ content: (d.content || "") + `{{${v}}}` })} />

            <Section title="🔘 Answer Buttons" hint="Patient taps one. Each button leads to a different path.">
              <div className="space-y-2">
                {(d.buttons || []).map((btn: any, i: number) => (
                  <div key={btn.id} className="flex items-center gap-2">
                    <div
                      className="w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold text-white flex-shrink-0"
                      style={{ background: KIND_META.buttons.color }}
                    >
                      {i + 1}
                    </div>
                    <input
                      className="field flex-1 text-[12px]"
                      value={btn.text}
                      maxLength={20}
                      placeholder="Button text (max 20 chars)"
                      onChange={(e) => {
                        const btns = [...(d.buttons || [])];
                        btns[i] = { ...btn, text: e.target.value, label: e.target.value };
                        set({ buttons: btns });
                      }}
                    />
                    <button
                      onClick={() => set({ buttons: (d.buttons || []).filter((_: any, j: number) => j !== i) })}
                      className="text-gray-300 hover:text-red-500 transition text-sm"
                    >✕</button>
                  </div>
                ))}
                {(d.buttons || []).length < 3 && (
                  <button
                    onClick={() => set({ buttons: [...(d.buttons || []), { id: nanoid(6), label: "New option", text: "" }] })}
                    className="w-full py-2 text-[11px] font-semibold text-emerald-600 border-2 border-dashed border-emerald-200 rounded-xl hover:bg-emerald-50 transition"
                  >
                    + Add button {(d.buttons || []).length + 1} of 3
                  </button>
                )}
              </div>
              <p className="text-[10px] text-gray-400 mt-2">
                💡 Each button gets its own arrow on the canvas — connect them to different next steps.
              </p>
            </Section>
          </>
        )}

        {/* ══ CONDITION — Edit tab ══ */}
        {d.kind === "condition" && activeTab === "edit" && (
          <>
            <Section title="🔀 Branches" hint="Add one branch per possible patient answer">
              <div className="space-y-3">
                {(d.branches || []).map((br: any, i: number) => (
                  <div key={br.id} className="bg-white rounded-xl border border-amber-100 p-3 shadow-sm space-y-2">
                    <div className="flex items-center gap-2">
                      <span className="w-5 h-5 rounded-full bg-amber-500 text-white text-[10px] font-bold flex items-center justify-center flex-shrink-0">
                        {i + 1}
                      </span>
                      <input
                        className="field flex-1 font-semibold text-[12px]"
                        value={br.label}
                        placeholder="e.g. Patient confirms"
                        onChange={(e) => {
                          const brs = [...(d.branches || [])];
                          brs[i] = { ...br, label: e.target.value };
                          set({ branches: brs });
                        }}
                      />
                      <button
                        onClick={() => set({ branches: (d.branches || []).filter((_: any, j: number) => j !== i) })}
                        className="text-gray-300 hover:text-red-500 transition text-sm"
                      >✕</button>
                    </div>
                    <input
                      className="field text-[11px]"
                      value={br.aiHint}
                      placeholder="Hint: e.g. patient says yes / confirm / ok"
                      onChange={(e) => {
                        const brs = [...(d.branches || [])];
                        brs[i] = { ...br, aiHint: e.target.value };
                        set({ branches: brs });
                      }}
                    />
                    <input
                      className="field text-[11px]"
                      value={(br.keywords || []).join(", ")}
                      placeholder="Backup keywords: yes, ok, confirm, نعم"
                      onChange={(e) => {
                        const brs = [...(d.branches || [])];
                        brs[i] = { ...br, keywords: e.target.value.split(",").map((s: string) => s.trim()).filter(Boolean) };
                        set({ branches: brs });
                      }}
                    />
                  </div>
                ))}
                <button
                  onClick={() => set({ branches: [...(d.branches || []), { id: nanoid(6), label: "", keywords: [], aiHint: "" }] })}
                  className="w-full py-2 text-[11px] font-semibold text-amber-600 border-2 border-dashed border-amber-200 rounded-xl hover:bg-amber-50 transition"
                >
                  + Add branch
                </button>
              </div>
              <p className="text-[10px] text-gray-400 mt-2">
                💡 There's always a hidden "Else" branch at the bottom as fallback.
              </p>
            </Section>
          </>
        )}

        {/* ══ WAIT ══ */}
        {d.kind === "wait" && (
          <Section title="⏳ How long to wait?" hint="The bot will pause this many minutes before the next step">
            <div className="grid grid-cols-3 gap-2 mb-3">
              {[
                [30, "30 min"],
                [60, "1 hour"],
                [120, "2 hours"],
                [1440, "1 day"],
                [4320, "3 days"],
                [10080, "1 week"],
              ].map(([mins, label]) => (
                <button
                  key={mins}
                  onClick={() => set({ delayMinutes: mins as number, label: `Wait ${label}` })}
                  className={`py-2.5 text-[11px] font-semibold rounded-xl border-2 transition ${
                    d.delayMinutes === mins
                      ? "bg-slate-800 text-white border-slate-800 shadow-sm"
                      : "border-gray-100 bg-white text-gray-600 hover:border-gray-300"
                  }`}
                >
                  {label}
                </button>
              ))}
            </div>
            <div>
              <label className="text-[11px] font-semibold text-gray-500 block mb-1">Custom (in minutes)</label>
              <input
                type="number"
                className="field"
                value={d.delayMinutes || ""}
                min={1}
                placeholder="e.g. 90"
                onChange={(e) => set({ delayMinutes: Number(e.target.value) })}
              />
            </div>
          </Section>
        )}

        {/* ══ SENTIMENT ══ */}
        {d.kind === "sentiment" && (
          <Section title="❤️‍🔥 Mood Router" hint="Claude automatically detects the patient's mood from their message and routes them to the right path">
            <div className="space-y-2">
              {[
                { id:"positive", emoji:"😊", label:"Happy / Positive", color:"#059669", desc:"Patient is satisfied or enthusiastic" },
                { id:"neutral",  emoji:"😐", label:"Neutral",           color:"#d97706", desc:"Patient is uncertain or just OK" },
                { id:"negative", emoji:"😟", label:"Frustrated",        color:"#dc2626", desc:"Patient is unhappy or in pain" },
              ].map(b => (
                <div key={b.id} className="flex items-center gap-3 p-3 rounded-xl border" style={{ borderColor: b.color+"30", background: b.color+"08" }}>
                  <span className="text-xl">{b.emoji}</span>
                  <div>
                    <p className="text-[12px] font-bold" style={{ color: b.color }}>{b.label}</p>
                    <p className="text-[10px] text-gray-400">{b.desc}</p>
                  </div>
                </div>
              ))}
            </div>
            <p className="text-[10px] text-gray-400 mt-3">💡 Connect each mood to a different next step — e.g. happy → ask for review, frustrated → AI care response.</p>
          </Section>
        )}

        {/* ══ SAVE_VAR ══ */}
        {d.kind === "save_var" && activeTab === "edit" && (
          <>
            <Section title="🧠 What to Ask" hint="Ask the patient a question and save their answer">
              <textarea
                className="field min-h-[80px]"
                value={d.varPrompt || ""}
                onChange={(e) => set({ varPrompt: e.target.value })}
                placeholder="e.g. What's your preferred appointment time? Morning or afternoon?"
              />
            </Section>
            <Section title="📌 Save Answer As" hint="Give this a name — use it later as {{memory.your_name}}">
              <div className="flex items-center gap-2">
                <code className="text-[12px] text-cyan-600 font-bold bg-cyan-50 px-2 py-1 rounded-lg">{"{{memory."}</code>
                <input
                  className="field flex-1 font-mono text-[12px]"
                  value={d.varName || ""}
                  onChange={(e) => set({ varName: e.target.value.replace(/\s+/g, "_").toLowerCase() })}
                  placeholder="preferred_time"
                />
                <code className="text-[12px] text-cyan-600 font-bold bg-cyan-50 px-2 py-1 rounded-lg">{"}}"}</code>
              </div>
              {d.varName && (
                <div className="mt-2 flex items-center gap-1.5 px-3 py-2 bg-cyan-50 border border-cyan-100 rounded-xl">
                  <span className="text-[11px]">📌</span>
                  <code className="text-[12px] font-bold text-cyan-700">{`{{memory.${d.varName}}}`}</code>
                  <span className="text-[10px] text-cyan-500 ml-1">— use this in later messages</span>
                </div>
              )}
            </Section>
          </>
        )}

        {/* ══ RETRY ══ */}
        {d.kind === "retry" && activeTab === "edit" && (
          <>
            <Section title="⏱️ How long to wait before retrying?" hint="If patient doesn't reply, wait this long then send the follow-up">
              <div className="grid grid-cols-3 gap-2 mb-3">
                {[[60,"1h"],[1440,"1d"],[2880,"2d"],[4320,"3d"],[7200,"5d"],[10080,"1w"]].map(([m,l]) => (
                  <button key={m} onClick={() => set({ retryDelayMinutes: m as number })}
                    className={`py-2 text-[11px] font-bold rounded-xl border-2 transition ${d.retryDelayMinutes===m?"bg-purple-700 text-white border-purple-700":"border-gray-100 bg-white text-gray-600 hover:border-gray-300"}`}>
                    {l}
                  </button>
                ))}
              </div>
            </Section>
            <Section title="🔁 Max Retries" hint="After this many failed attempts, route to the escalation path">
              <div className="flex gap-2">
                {[1,2,3].map(n => (
                  <button key={n} onClick={() => set({ maxRetries: n })}
                    className={`flex-1 py-2 text-[13px] font-black rounded-xl border-2 transition ${d.maxRetries===n?"bg-purple-700 text-white border-purple-700":"border-gray-100 bg-white text-gray-600 hover:border-gray-300"}`}>
                    {n}×
                  </button>
                ))}
              </div>
            </Section>
            <Section title="💬 Follow-up Message" hint="What to send if patient still hasn't replied">
              <textarea
                className="field min-h-[80px]"
                value={d.retryMessage || ""}
                onChange={(e) => set({ retryMessage: e.target.value })}
                placeholder="Hey {{name}}, just checking in! We still have slots available for your {{treatment}}. Would you like to book? 😊"
              />
              <VarPicker onInsert={(v) => set({ retryMessage: (d.retryMessage||"") + `{{${v}}}` })} />
            </Section>
          </>
        )}

        {/* ══ END ══ */}
        {d.kind === "end" && (
          <Section title="✅ End of Flow" hint="The patient journey is complete at this point">
            <div className="bg-white rounded-xl border border-gray-100 p-4 text-center">
              <div className="text-3xl mb-2">🎉</div>
              <p className="text-[12px] font-semibold text-gray-700">Journey Complete</p>
              <p className="text-[11px] text-gray-400 mt-1">
                You can optionally customise the label shown on the card.
              </p>
              <input
                className="field mt-3 text-center"
                value={d.label}
                onChange={(e) => set({ label: e.target.value })}
                placeholder="Journey Complete"
              />
            </div>
          </Section>
        )}

        {/* ══ AI Generate Tab ══ */}
        {canAI && activeTab === "ai" && (
          <AITab node={node} onGenerate={onAIGenerate} generating={generating} />
        )}
      </div>
    </div>
  );
}

/* ─── Sub-components ─── */

function Section({ title, hint, children }: { title: string; hint?: string; children: React.ReactNode }) {
  return (
    <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
      <div className="px-4 pt-3.5 pb-2 border-b border-gray-50">
        <p className="text-[12px] font-bold text-gray-800">{title}</p>
        {hint && <p className="text-[10px] text-gray-400 mt-0.5">{hint}</p>}
      </div>
      <div className="p-4">{children}</div>
    </div>
  );
}

function VarPicker({ onInsert }: { onInsert: (v: string) => void }) {
  return (
    <div className="bg-white rounded-2xl border border-gray-100 shadow-sm px-4 py-3">
      <p className="text-[11px] font-bold text-gray-600 mb-2">📌 Insert patient info</p>
      <div className="flex flex-wrap gap-1.5">
        {VARS.map(({ key, label, example }) => (
          <button
            key={key}
            onClick={() => onInsert(key)}
            title={`Example: ${example}`}
            className="text-[10px] px-2 py-1 rounded-lg bg-gray-50 text-gray-600 hover:bg-indigo-50 hover:text-indigo-600 border border-gray-100 hover:border-indigo-200 font-mono transition"
          >
            {`{{${key}}}`}
          </button>
        ))}
      </div>
      <p className="text-[10px] text-gray-400 mt-2">
        These are automatically filled with real patient data when sent.
      </p>
    </div>
  );
}

function AITab({ node, onGenerate, generating }: any) {
  const d = node.data as NodeData;

  const actions: { field: string; icon: string; title: string; desc: string }[] = [];
  if (d.kind === "message") {
    actions.push({ field: "content", icon: "✍️", title: "Write the message for me", desc: "Claude drafts the perfect WhatsApp message for this step" });
  }
  if (d.kind === "buttons") {
    actions.push({ field: "content", icon: "✍️", title: "Write the question for me", desc: "Claude writes a clear, friendly question with button options" });
  }
  if (d.kind === "condition") {
    actions.push({ field: "content", icon: "🔀", title: "Write branch labels for me", desc: "Suggests clear labels for each branch option" });
  }

  return (
    <div className="space-y-3">
      <div className="bg-gradient-to-br from-violet-50 to-indigo-50 rounded-2xl border border-violet-100 p-4">
        <div className="flex items-start gap-3">
          <div className="w-10 h-10 rounded-xl bg-violet-600 flex items-center justify-center text-xl flex-shrink-0 shadow">
            🤖
          </div>
          <div>
            <p className="text-[13px] font-bold text-violet-800">Claude AI Assistant</p>
            <p className="text-[11px] text-violet-600 mt-0.5 leading-relaxed">
              Claude will read this node's purpose and automatically write the content for you in seconds.
            </p>
          </div>
        </div>
      </div>

      {actions.map(({ field, icon, title, desc }) => (
        <button
          key={field}
          disabled={generating}
          onClick={() => onGenerate(node.id, field)}
          className={`w-full flex items-start gap-3 p-4 rounded-2xl border-2 text-left transition group
            ${generating
              ? "border-gray-100 bg-gray-50 opacity-60 cursor-not-allowed"
              : "border-violet-100 bg-white hover:border-violet-400 hover:shadow-md hover:shadow-violet-100"
            }`}
        >
          <span className="text-2xl mt-0.5">{generating ? "⏳" : icon}</span>
          <div>
            <p className="text-[12px] font-bold text-gray-800 group-hover:text-violet-700 transition">{title}</p>
            <p className="text-[11px] text-gray-400 mt-0.5 leading-relaxed">{desc}</p>
          </div>
          {!generating && (
            <span className="ml-auto text-[11px] font-semibold text-violet-500 bg-violet-50 px-2 py-0.5 rounded-lg self-center whitespace-nowrap group-hover:bg-violet-500 group-hover:text-white transition">
              Generate ✨
            </span>
          )}
        </button>
      ))}

      {generating && (
        <div className="text-center py-3">
          <div className="inline-flex items-center gap-2 text-[12px] text-violet-600 font-semibold bg-violet-50 px-4 py-2 rounded-full border border-violet-100">
            <span className="w-2 h-2 rounded-full bg-violet-500 animate-ping" />
            Claude is writing…
          </div>
        </div>
      )}
    </div>
  );
}
