defmodule CentralcloudOps.IncidentLive do
  use Phoenix.LiveView
  alias CentralcloudCore.OnCall

  def mount(%{"id" => id}, _session, socket) do
    socket = load(socket, id)
    {:ok, socket}
  end

  def handle_event("ack", _, socket) do
    id = socket.assigns.id
    case OnCall.acknowledge_alert_group(id) do
      {:ok, _} -> {:noreply, load(put_flash(socket, :info, "Acknowledged"), id)}
      _ -> {:noreply, put_flash(socket, :error, "Failed to acknowledge")}
    end
  end

  def handle_event("resolve", _, socket) do
    id = socket.assigns.id
    case OnCall.resolve_alert_group(id) do
      {:ok, _} -> {:noreply, load(put_flash(socket, :info, "Resolved"), id)}
      _ -> {:noreply, put_flash(socket, :error, "Failed to resolve")}
    end
  end

  def handle_event("silence", %{"duration" => dur}, socket) do
    id = socket.assigns.id
    seconds = String.to_integer(dur) * 60
    case OnCall.silence_alert_group(id, seconds) do
      {:ok, _} -> {:noreply, load(put_flash(socket, :info, "Silenced for #{dur} minutes"), id)}
      _ -> {:noreply, put_flash(socket, :error, "Failed to silence")}
    end
  end

  defp load(socket, id) do
    {ag, alerts} =
      case OnCall.get_alert_group(id) do
        {:ok, ag} ->
          alerts = ag["alerts"] || []
          {ag, alerts}
        _ ->
          {nil, []}
      end

    assign(socket,
      page_title: "Incident #{id}",
      id: id,
      alert_group: ag,
      alerts: alerts
    )
  end

  def render(assigns) do
    ~H"""
    <div style="margin-bottom:1rem;">
      <a href="/incidents" style="color:#64748b;font-size:0.875rem;">← Back to Incidents</a>
    </div>

    <div :if={is_nil(@alert_group)} class="card" style="color:#64748b;">
      Alert group not found.
    </div>

    <div :if={@alert_group}>
      <div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:1.5rem;gap:1rem;flex-wrap:wrap;">
        <div>
          <div style="display:flex;align-items:center;gap:0.75rem;margin-bottom:0.4rem;">
            <span class={"badge badge-#{@alert_group["status"]}"}>{@alert_group["status"]}</span>
            <h1 style="font-size:1.25rem;font-weight:700;">
              {@alert_group["render_for_web"]["title"] || @alert_group["id"]}
            </h1>
          </div>
          <div style="color:#64748b;font-size:0.8rem;">
            Source: {@alert_group["alert_receive_channel"]["verbal_name"]} &nbsp;·&nbsp;
            Started: {format_dt(@alert_group["started_at"])}
          </div>
        </div>

        <div style="display:flex;gap:0.5rem;flex-wrap:wrap;">
          <button :if={@alert_group["status"] == "firing"}
                  class="btn btn-warning" phx-click="ack">Acknowledge</button>
          <button :if={@alert_group["status"] in ["firing","acknowledged"]}
                  class="btn btn-success" phx-click="resolve">Resolve</button>
          <button :if={@alert_group["status"] == "firing"}
                  class="btn btn-ghost" phx-click="silence" phx-value-duration="30">
            Silence 30m
          </button>
          <button :if={@alert_group["status"] == "firing"}
                  class="btn btn-ghost" phx-click="silence" phx-value-duration="120">
            Silence 2h
          </button>
        </div>
      </div>

      <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1.5rem;">
        <div class="card">
          <div class="section-title" style="font-size:0.9rem;">Details</div>
          <table style="font-size:0.85rem;">
            <tr>
              <td style="color:#64748b;padding:0.3rem 1rem 0.3rem 0;">ID</td>
              <td style="font-family:monospace;">{@alert_group["id"]}</td>
            </tr>
            <tr>
              <td style="color:#64748b;padding:0.3rem 1rem 0.3rem 0;">Status</td>
              <td>{@alert_group["status"]}</td>
            </tr>
            <tr :if={@alert_group["acknowledged_at"]}>
              <td style="color:#64748b;padding:0.3rem 1rem 0.3rem 0;">Acknowledged</td>
              <td>{format_dt(@alert_group["acknowledged_at"])}</td>
            </tr>
            <tr :if={@alert_group["resolved_at"]}>
              <td style="color:#64748b;padding:0.3rem 1rem 0.3rem 0;">Resolved</td>
              <td>{format_dt(@alert_group["resolved_at"])}</td>
            </tr>
          </table>
        </div>

        <div class="card">
          <div class="section-title" style="font-size:0.9rem;">Render Preview</div>
          <div style="font-size:0.85rem;color:#94a3b8;white-space:pre-wrap;">
            {@alert_group["render_for_web"]["message"] || "No message"}
          </div>
        </div>
      </div>

      <div :if={@alerts != []} class="card" style="margin-bottom:1.5rem;padding:0;">
        <div style="padding:1rem 1.25rem;border-bottom:1px solid #1e3a5f;font-weight:600;">
          Raw Alerts ({length(@alerts)})
        </div>
        <table>
          <thead>
            <tr><th>Received</th><th>Title</th><th>Message</th></tr>
          </thead>
          <tbody>
            <tr :for={a <- @alerts}>
              <td style="color:#64748b;font-size:0.8rem;">{format_dt(a["created_at"])}</td>
              <td style="font-size:0.85rem;">{a["render_for_web"]["title"]}</td>
              <td style="color:#94a3b8;font-size:0.8rem;max-width:400px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                {a["render_for_web"]["message"]}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    """
  end

  defp format_dt(nil), do: "—"
  defp format_dt(iso) do
    case DateTime.from_iso8601(iso) do
      {:ok, dt, _} -> Calendar.strftime(dt, "%d %b %H:%M UTC")
      _ -> iso
    end
  end
end
