defmodule CentralcloudStaff.IncidentLive do
  use CentralcloudStaffWeb, :live_view
  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} -> {ag, ag["alerts"] || []}
        _ -> {nil, []}
      end

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

  def render(assigns) do
    ~H"""
    <div class="mb-4">
      <a href="/incidents" class="text-slate-500 text-sm hover:text-slate-300 no-underline">
        ← Back to Incidents
      </a>
    </div>

    <div :if={is_nil(@alert_group)}
         class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-8 text-slate-500">
      Alert group not found.
    </div>

    <div :if={@alert_group}>
      <div class="flex items-start justify-between mb-6 gap-4 flex-wrap">
        <div>
          <div class="flex items-center gap-3 mb-1.5">
            <span class={status_badge(@alert_group["status"])}>{@alert_group["status"]}</span>
            <h1 class="text-xl font-bold text-slate-100">
              {@alert_group["render_for_web"]["title"] || @alert_group["id"]}
            </h1>
          </div>
          <p class="text-slate-500 text-sm">
            Source: {@alert_group["alert_receive_channel"]["verbal_name"]}
            &nbsp;·&nbsp;
            Started: {format_dt(@alert_group["started_at"])}
          </p>
        </div>

        <div class="flex gap-2 flex-wrap">
          <.button
            :if={@alert_group["status"] == "firing"}
            size="sm" color="warning" phx-click="ack"
          >
            Acknowledge
          </.button>
          <.button
            :if={@alert_group["status"] in ["firing", "acknowledged"]}
            size="sm" color="success" phx-click="resolve"
          >
            Resolve
          </.button>
          <.button
            :if={@alert_group["status"] == "firing"}
            size="sm" color="gray" variant="outline" phx-click="silence" phx-value-duration="30"
          >
            Silence 30m
          </.button>
          <.button
            :if={@alert_group["status"] == "firing"}
            size="sm" color="gray" variant="outline" phx-click="silence" phx-value-duration="120"
          >
            Silence 2h
          </.button>
        </div>
      </div>

      <div class="grid grid-cols-2 gap-4 mb-5">
        <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-5">
          <h2 class="text-sm font-semibold text-slate-300 mb-3">Details</h2>
          <dl class="text-sm space-y-1.5">
            <div class="flex gap-3">
              <dt class="text-slate-500 w-28 flex-shrink-0">ID</dt>
              <dd class="font-mono text-slate-300">{@alert_group["id"]}</dd>
            </div>
            <div class="flex gap-3">
              <dt class="text-slate-500 w-28 flex-shrink-0">Status</dt>
              <dd class="text-slate-300">{@alert_group["status"]}</dd>
            </div>
            <div :if={@alert_group["acknowledged_at"]} class="flex gap-3">
              <dt class="text-slate-500 w-28 flex-shrink-0">Acknowledged</dt>
              <dd class="text-slate-300">{format_dt(@alert_group["acknowledged_at"])}</dd>
            </div>
            <div :if={@alert_group["resolved_at"]} class="flex gap-3">
              <dt class="text-slate-500 w-28 flex-shrink-0">Resolved</dt>
              <dd class="text-slate-300">{format_dt(@alert_group["resolved_at"])}</dd>
            </div>
          </dl>
        </div>

        <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-5">
          <h2 class="text-sm font-semibold text-slate-300 mb-3">Message</h2>
          <p class="text-slate-400 text-sm whitespace-pre-wrap leading-relaxed">
            {@alert_group["render_for_web"]["message"] || "No message"}
          </p>
        </div>
      </div>

      <div :if={@alerts != []} class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg overflow-hidden">
        <div class="px-5 py-3 border-b border-[#1e3a5f] font-semibold text-sm text-slate-200">
          Raw Alerts ({length(@alerts)})
        </div>
        <table class="w-full text-sm">
          <thead>
            <tr class="text-left border-b border-[#1e3a5f]">
              <th class="px-5 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Received</th>
              <th class="px-5 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Title</th>
              <th class="px-5 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Message</th>
            </tr>
          </thead>
          <tbody>
            <tr :for={a <- @alerts} class="border-t border-[#0a0f1e]">
              <td class="px-5 py-3 text-slate-500 text-xs">{format_dt(a["created_at"])}</td>
              <td class="px-5 py-3 text-slate-200 text-sm">{a["render_for_web"]["title"]}</td>
              <td class="px-5 py-3 text-slate-500 text-xs max-w-xs overflow-hidden text-ellipsis whitespace-nowrap">
                {a["render_for_web"]["message"]}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    """
  end

  defp status_badge("firing"),
    do: "inline-block px-2 py-0.5 rounded text-[11px] font-semibold uppercase bg-red-950 text-red-300 border border-red-700"
  defp status_badge("acknowledged"),
    do: "inline-block px-2 py-0.5 rounded text-[11px] font-semibold uppercase bg-amber-950 text-amber-300 border border-amber-700"
  defp status_badge("resolved"),
    do: "inline-block px-2 py-0.5 rounded text-[11px] font-semibold uppercase bg-green-950 text-green-300 border border-green-700"
  defp status_badge("silenced"),
    do: "inline-block px-2 py-0.5 rounded text-[11px] font-semibold uppercase bg-indigo-950 text-indigo-300 border border-indigo-700"
  defp status_badge(_),
    do: "inline-block px-2 py-0.5 rounded text-[11px] font-semibold uppercase bg-slate-700 text-slate-300"

  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
