defmodule CentralcloudOps.ChatLive do
  use Phoenix.LiveView

  def mount(_params, _session, socket) do
    {:ok,
     assign(socket,
       page_title: "AI Chat",
       messages: [],
       streaming: false,
       streaming_content: "",
       error: nil
     )}
  end

  # Form submit
  def handle_event("send", %{"message" => text}, socket), do: do_send(text, socket)
  # Suggestion button (phx-value-message)
  def handle_event("send", %{"value" => text}, socket), do: do_send(text, socket)

  def handle_event("clear", _params, socket) do
    {:noreply,
     assign(socket,
       messages: [],
       streaming: false,
       streaming_content: "",
       error: nil
     )}
  end

  defp do_send(text, socket) do
    text = String.trim(text)

    cond do
      text == "" ->
        {:noreply, socket}

      socket.assigns.streaming ->
        {:noreply, socket}

      true ->
        user_msg = %{role: "user", content: text}
        messages = socket.assigns.messages ++ [user_msg]

        caller = self()
        Task.start(fn -> CentralcloudOps.RouterAgent.stream_chat(messages, caller) end)

        {:noreply,
         assign(socket,
           messages: messages,
           streaming: true,
           streaming_content: "",
           error: nil
         )}
    end
  end

  def handle_info({:chunk, text}, socket) do
    {:noreply, assign(socket, streaming_content: socket.assigns.streaming_content <> text)}
  end

  def handle_info(:stream_done, socket) do
    content = socket.assigns.streaming_content

    if content != "" do
      assistant_msg = %{role: "assistant", content: content}

      {:noreply,
       assign(socket,
         messages: socket.assigns.messages ++ [assistant_msg],
         streaming: false,
         streaming_content: ""
       )}
    else
      {:noreply, assign(socket, streaming: false)}
    end
  end

  def handle_info({:stream_error, reason}, socket) do
    {:noreply,
     assign(socket,
       streaming: false,
       streaming_content: "",
       error: "Router agent error: #{reason}"
     )}
  end

  def render(assigns) do
    ~H"""
    <style>
      @keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
      .chat-input { background: #0a0f1e; border: 1px solid #1e3a5f; border-radius: 6px;
                    padding: 0.6rem 0.9rem; color: #e2e8f0; font-size: 0.875rem;
                    outline: none; flex: 1; }
      .chat-input:focus { border-color: #2563eb; }
      .chat-input:disabled { opacity: 0.5; cursor: not-allowed; }
      .chat-wrap { display: flex; flex-direction: column;
                   height: calc(100vh - 180px); min-height: 400px; }
      .chat-msgs { flex: 1; overflow-y: auto; padding: 1rem;
                   display: flex; flex-direction: column; gap: 0.75rem; }
      .msg-user { display: flex; justify-content: flex-end; }
      .msg-ai { display: flex; justify-content: flex-start; align-items: flex-start; gap: 0.5rem; }
      .bubble-user { max-width: 75%; padding: 0.65rem 0.9rem; border-radius: 14px;
                     border-bottom-right-radius: 4px; background: #2563eb; color: #fff;
                     font-size: 0.875rem; line-height: 1.6; white-space: pre-wrap; word-break: break-word; }
      .bubble-ai { max-width: 80%; padding: 0.65rem 0.9rem; border-radius: 14px;
                   border-bottom-left-radius: 4px; background: #0f1629; border: 1px solid #1e3a5f;
                   color: #e2e8f0; font-size: 0.875rem; line-height: 1.6;
                   white-space: pre-wrap; word-break: break-word; }
      .ai-icon { width: 28px; height: 28px; border-radius: 50%; background: #1e3a5f;
                 display: flex; align-items: center; justify-content: center;
                 font-size: 0.85rem; flex-shrink: 0; margin-top: 2px; }
      .cursor { display: inline-block; animation: blink 0.8s step-end infinite; }
      .chat-footer { border-top: 1px solid #1e3a5f; padding: 0.75rem 1rem; }
      .chat-form { display: flex; gap: 0.5rem; align-items: center; }
      .dot { width: 6px; height: 6px; border-radius: 50%; background: #60a5fa;
             display: inline-block; animation: bounce 1.2s infinite; }
      .dot:nth-child(2) { animation-delay: 0.2s; }
      .dot:nth-child(3) { animation-delay: 0.4s; }
      @keyframes bounce { 0%,80%,100%{transform:translateY(0)} 40%{transform:translateY(-6px)} }
      .suggestion { background: #0f1629; border: 1px solid #1e3a5f; border-radius: 8px;
                    padding: 0.5rem 0.8rem; font-size: 0.8rem; color: #94a3b8;
                    cursor: pointer; text-align: left; }
      .suggestion:hover { border-color: #2563eb; color: #e2e8f0; }
      .suggestions { display: flex; flex-wrap: wrap; gap: 0.5rem; justify-content: center;
                     margin-top: 1rem; max-width: 500px; }
    </style>

    <div class="section-title">🤖 AI Operations Chat</div>

    <div class="card" style="padding: 0; overflow: hidden;">
      <div class="chat-wrap">

        <div id="chat-messages" phx-hook="ScrollBottom" class="chat-msgs">

          <%!-- Empty / welcome state --%>
          <div :if={@messages == [] and not @streaming}
               style="flex:1;display:flex;flex-direction:column;align-items:center;
                      justify-content:center;color:#475569;gap:0.5rem;padding:3rem 1rem;text-align:center;">
            <div style="font-size: 2.5rem;">🔥</div>
            <div style="font-size: 1rem; font-weight: 600; color: #94a3b8;">
              Ask me anything about your infrastructure
            </div>
            <div style="font-size: 0.8rem; color: #64748b;">
              I route to the right specialist — incident commander, ops, or comms
            </div>
            <div class="suggestions">
              <button class="suggestion" phx-click="send" phx-value-value="What alerts are firing right now?">
                🚨 What's firing?
              </button>
              <button class="suggestion" phx-click="send" phx-value-value="Who is on-call right now?">
                📟 Who's on-call?
              </button>
              <button class="suggestion" phx-click="send" phx-value-value="Show me recent incidents">
                📋 Recent incidents
              </button>
              <button class="suggestion" phx-click="send" phx-value-value="Check cluster health">
                ☸️ Cluster health
              </button>
            </div>
          </div>

          <%!-- History --%>
          <div :for={msg <- @messages}>
            <div :if={msg.role == "user"} class="msg-user">
              <div class="bubble-user">{msg.content}</div>
            </div>
            <div :if={msg.role == "assistant"} class="msg-ai">
              <div class="ai-icon">🤖</div>
              <div class="bubble-ai">{msg.content}</div>
            </div>
          </div>

          <%!-- Streaming --%>
          <div :if={@streaming} class="msg-ai">
            <div class="ai-icon">🤖</div>
            <div class="bubble-ai">
              <span :if={@streaming_content == ""}>
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </span>
              <span :if={@streaming_content != ""}>{@streaming_content}<span class="cursor">▋</span></span>
            </div>
          </div>

        </div>

        <%!-- Error bar --%>
        <div :if={@error}
             style="padding:0.5rem 1rem;background:#4c0519;color:#fca5a5;font-size:0.8rem;border-top:1px solid #7f1d1d;">
          ⚠️ {@error}
        </div>

        <%!-- Input --%>
        <div class="chat-footer">
          <form phx-submit="send" class="chat-form">
            <input
              class="chat-input"
              type="text"
              name="message"
              placeholder={if @streaming, do: "Waiting for response…", else: "Ask the ops AI anything…"}
              autocomplete="off"
              disabled={@streaming}
              id="chat-input"
            />
            <button type="submit" class="btn btn-primary"
                    disabled={@streaming}
                    style={if @streaming, do: "opacity:0.5;cursor:not-allowed;", else: ""}>
              Send
            </button>
            <button :if={@messages != [] and not @streaming}
                    type="button" phx-click="clear" class="btn btn-ghost">
              Clear
            </button>
          </form>
        </div>

      </div>
    </div>
    """
  end
end
