/**
 * ConnectionBar — connect form, session picker, player name
 *
 * Three states: disconnected → connecting → connected
 */

import { Component, createSignal, Show, For, onMount } from "solid-js";
import {
  connectStream,
  hydrateFromServer,
  useJournalStream,
  sessions,
  setMyName,
  createSession,
  deleteSession,
} from "../stores/journalStream";
import type { SessionMeta } from "../stores/journalStream";
import { createMemo } from "solid-js";

// Direct access to the store's setter for session switching
import { journalSetState } from "../stores/journalStream";

export const ConnectionBar: Component = () => {
  const stream = useJournalStream();
  const [brokerUrl, setBrokerUrl] = createSignal("");
  const [newSessionName, setNewSessionName] = createSignal("");
  const [playerName, setPlayerName] = createSignal("");
  const [connecting, setConnecting] = createSignal(false);
  const [error, setError] = createSignal<string | null>(null);
  const [showNewSession, setShowNewSession] = createSignal(false);

  onMount(() => {
    setBrokerUrl(stream.brokerUrl ?? "");
    setPlayerName(stream.myName);
  });

  const manifest = sessions;

  const handleConnect = async () => {
    const url = brokerUrl().trim();
    if (!url) return;

    setConnecting(true);
    setError(null);

    try {
      // Save name first
      if (playerName().trim()) {
        setMyName(playerName().trim());
      }

      // Connect
      const sessionId = stream.sessionId || "default";
      await hydrateFromServer(sessionId);
      await connectStream(sessionId, url);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Connection failed");
    } finally {
      setConnecting(false);
    }
  };

  const handleCreateSession = () => {
    const name = newSessionName().trim();
    if (!name) return;
    createSession(name);
    setNewSessionName("");
    setShowNewSession(false);
  };

  const handleDeleteSession = (id: string) => {
    if (confirm(`Delete session "${id}"? This cannot be undone.`)) {
      deleteSession(id);
    }
  };

  const handleSessionSelect = async (id: string) => {
    if (!stream.connected) return;
    try {
      await hydrateFromServer(id);
      journalSetState("sessionId", id);
    } catch (e) {
      setError("Failed to load session");
    }
  };

  const statusColor = () =>
    stream.connected
      ? "bg-green-500"
      : connecting()
        ? "bg-yellow-400"
        : "bg-gray-400";

  return (
    <div class="border-b border-gray-200 p-3 space-y-2 text-sm">
      {/* Status + session name */}
      <div class="flex items-center gap-2">
        <span class={`w-2 h-2 rounded-full ${statusColor()}`} />
        <span class="text-xs text-gray-500">
          {stream.connected
            ? "connected"
            : connecting()
              ? "connecting..."
              : "disconnected"}
        </span>
        <Show when={stream.sessionId}>
          <span class="text-xs font-mono bg-gray-100 px-1.5 py-0.5 rounded">
            {stream.sessionId}
          </span>
        </Show>
        <div class="flex-1" />
        <Show when={stream.connected}>
          <button
            onClick={() => {} /* disconnect */}
            class="text-xs text-gray-400 hover:text-red-500"
            title="Disconnect"
          >
            ⏻
          </button>
        </Show>
      </div>

      {/* Disconnected: connect form */}
      <Show when={!stream.connected}>
        <div class="space-y-2">
          <input
            type="text"
            value={brokerUrl()}
            onInput={(e) => setBrokerUrl(e.currentTarget.value)}
            placeholder="MQTT broker (e.g. tcp://192.168.1.5:1883)"
            class="w-full border border-gray-300 rounded px-2 py-1 text-xs"
          />
          <input
            type="text"
            value={playerName()}
            onInput={(e) => setPlayerName(e.currentTarget.value)}
            placeholder="Your name (GM or player)"
            class="w-full border border-gray-300 rounded px-2 py-1 text-xs"
          />
          <button
            onClick={handleConnect}
            disabled={connecting() || !brokerUrl().trim()}
            class="w-full bg-blue-600 text-white rounded px-3 py-1 text-xs hover:bg-blue-700 disabled:opacity-50"
          >
            {connecting() ? "Connecting..." : "Connect"}
          </button>
          <Show when={error()}>
            <p class="text-red-500 text-xs">{error()}</p>
          </Show>
        </div>
      </Show>

      {/* Connected: session management (GM only) */}
      <Show when={stream.connected && stream.myName === "gm"}>
        <div class="space-y-1">
          <div class="flex items-center gap-1">
            <span class="text-xs text-gray-500">Sessions:</span>
            <button
              onClick={() => setShowNewSession((v) => !v)}
              class="text-xs text-blue-600 hover:underline"
            >
              + new
            </button>
          </div>

          <Show when={showNewSession()}>
            <div class="flex gap-1">
              <input
                type="text"
                value={newSessionName()}
                onInput={(e) => setNewSessionName(e.currentTarget.value)}
                placeholder="Session name"
                class="flex-1 border border-gray-300 rounded px-2 py-0.5 text-xs"
                onKeyDown={(e) => e.key === "Enter" && handleCreateSession()}
              />
              <button
                onClick={handleCreateSession}
                class="bg-green-600 text-white rounded px-2 py-0.5 text-xs hover:bg-green-700"
              >
                Create
              </button>
            </div>
          </Show>

          <For each={Object.entries(manifest().sessions)}>
            {([id, meta]) => (
              <div
                class={`flex items-center gap-1 px-1 py-0.5 rounded cursor-pointer text-xs ${
                  id === stream.sessionId
                    ? "bg-blue-100 text-blue-800"
                    : "hover:bg-gray-100"
                }`}
              >
                <span
                  class="flex-1 truncate"
                  onClick={() => handleSessionSelect(id)}
                >
                  {meta.name || id}
                </span>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDeleteSession(id);
                  }}
                  class="text-gray-400 hover:text-red-500 text-xs"
                  title="Delete session"
                >
                  ✕
                </button>
              </div>
            )}
          </For>
        </div>
      </Show>

      {/* Connected: player info (player only) */}
      <Show when={stream.connected && stream.myName !== "gm"}>
        <div class="flex items-center gap-1 text-xs text-gray-500">
          <span>Playing as:</span>
          <span class="font-medium text-gray-700">{stream.myName}</span>
        </div>
      </Show>
    </div>
  );
};
