defmodule CentralcloudStaff.IncidentsLive do
  use CentralcloudStaffWeb, :live_view
  alias CentralcloudCore.OnCall

  def mount(_params, _session, socket) do
    {:ok, load(socket, "firing")}
  end

  def handle_event("filter", %{"status" => status}, socket) do
    {:noreply, load(socket, status)}
  end

  defp load(socket, status) do
    groups =
      case OnCall.list_alert_groups(status: status) do
        {:ok, %{"results" => r}} -> r
        _ -> []
      end

    assign(socket, page_title: "Incidents", groups: groups, status: status)
  end

  def render(assigns) do
    ~H"""
    <h1 class="text-lg font-bold text-slate-100 mb-4 flex items-center gap-2">🗂 Incidents</h1>

    <div class="flex gap-2 mb-5">
      <button class={filter_btn_class(@status == "firing", "red")}
              phx-click="filter" phx-value-status="firing">Firing</button>
      <button class={filter_btn_class(@status == "acknowledged", "orange")}
              phx-click="filter" phx-value-status="acknowledged">Acknowledged</button>
      <button class={filter_btn_class(@status == "resolved", "green")}
              phx-click="filter" phx-value-status="resolved">Resolved</button>
      <button class={filter_btn_class(@status == "silenced", "blue")}
              phx-click="filter" phx-value-status="silenced">Silenced</button>
    </div>

    <div :if={@groups == []}
         class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-8 text-center text-slate-500">
      No {@status} incidents.
    </div>

    <div :if={@groups != []} class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg overflow-hidden">
      <table class="w-full text-sm">
        <thead>
          <tr class="text-left border-b border-[#1e3a5f]">
            <th class="px-4 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Status</th>
            <th class="px-4 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Title</th>
            <th class="px-4 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Source</th>
            <th class="px-4 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Started</th>
            <th class="px-4 py-2.5"></th>
          </tr>
        </thead>
        <tbody>
          <tr :for={ag <- @groups} class="border-t border-[#0a0f1e] hover:bg-[#0f1a2e] transition-colors">
            <td class="px-4 py-3">
              <span class={status_badge(ag["status"])}>{ag["status"]}</span>
            </td>
            <td class="px-4 py-3 font-semibold text-slate-200">
              {ag["render_for_web"]["title"] || ag["id"]}
            </td>
            <td class="px-4 py-3 text-slate-500 text-xs">{ag["alert_receive_channel"]["verbal_name"]}</td>
            <td class="px-4 py-3 text-slate-500 text-xs">{format_dt(ag["started_at"])}</td>
            <td class="px-4 py-3">
              <a href={"/incidents/#{ag["id"]}"}
                 class="inline-flex items-center gap-1 px-3 py-1 rounded text-xs font-medium
                        text-slate-400 border border-slate-700 hover:border-slate-500 hover:text-slate-200
                        no-underline transition-colors">
                View →
              </a>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    """
  end

  defp filter_btn_class(true, "red"),
    do: "px-3.5 py-1.5 rounded-md text-sm font-semibold bg-red-700 text-white transition-colors"
  defp filter_btn_class(true, "orange"),
    do: "px-3.5 py-1.5 rounded-md text-sm font-semibold bg-amber-700 text-white transition-colors"
  defp filter_btn_class(true, "green"),
    do: "px-3.5 py-1.5 rounded-md text-sm font-semibold bg-green-700 text-white transition-colors"
  defp filter_btn_class(true, "blue"),
    do: "px-3.5 py-1.5 rounded-md text-sm font-semibold bg-blue-700 text-white transition-colors"
  defp filter_btn_class(false, _),
    do: "px-3.5 py-1.5 rounded-md text-sm font-medium text-slate-400 border border-slate-700 hover:border-slate-500 hover:text-slate-200 transition-colors"

  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
