defmodule CentralcloudOps.IncidentsLive do
  use Phoenix.LiveView
  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"""
    <div class="section-title">🗂 Incidents</div>

    <div style="display:flex;gap:0.5rem;margin-bottom:1.25rem;">
      <button class={"btn #{if @status == "firing", do: "btn-danger", else: "btn-ghost"}"}
              phx-click="filter" phx-value-status="firing">Firing</button>
      <button class={"btn #{if @status == "acknowledged", do: "btn-warning", else: "btn-ghost"}"}
              phx-click="filter" phx-value-status="acknowledged">Acknowledged</button>
      <button class={"btn #{if @status == "resolved", do: "btn-success", else: "btn-ghost"}"}
              phx-click="filter" phx-value-status="resolved">Resolved</button>
      <button class={"btn #{if @status == "silenced", do: "btn-primary", else: "btn-ghost"}"}
              phx-click="filter" phx-value-status="silenced">Silenced</button>
    </div>

    <div :if={@groups == []} class="card" style="color:#64748b;text-align:center;padding:2rem;">
      No {@status} incidents.
    </div>

    <div :if={@groups != []} class="card" style="padding:0;">
      <table>
        <thead>
          <tr>
            <th>Status</th>
            <th>Title</th>
            <th>Source</th>
            <th>Started</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr :for={ag <- @groups}>
            <td><span class={"badge badge-#{ag["status"]}"}>{ag["status"]}</span></td>
            <td style="font-weight:600;">{ag["render_for_web"]["title"] || ag["id"]}</td>
            <td style="color:#64748b;font-size:0.8rem;">{ag["alert_receive_channel"]["verbal_name"]}</td>
            <td style="color:#64748b;font-size:0.8rem;">{format_dt(ag["started_at"])}</td>
            <td><a href={"/incidents/#{ag["id"]}"} class="btn btn-ghost">View →</a></td>
          </tr>
        </tbody>
      </table>
    </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
