defmodule ToweropsWeb.AlertLive.Index do
  @moduledoc false
  use ToweropsWeb, :live_view

  alias Towerops.Alerts

  @impl true
  def mount(_params, _session, socket) do
    organization = socket.assigns.current_organization

    # Subscribe to alert events
    _ =
      if connected?(socket) do
        _ = Phoenix.PubSub.subscribe(Towerops.PubSub, "alerts:new")
        Phoenix.PubSub.subscribe(Towerops.PubSub, "alerts:resolved")
      end

    {:ok,
     socket
     |> assign(:page_title, "Alerts")
     |> assign(:filter, "active")
     |> load_alerts(organization.id)}
  end

  @impl true
  def handle_params(params, _url, socket) do
    filter = Map.get(params, "filter", "active")

    {:noreply,
     socket
     |> assign(:filter, filter)
     |> load_alerts(socket.assigns.current_organization.id)}
  end

  @impl true
  def handle_event("acknowledge", %{"id" => id}, socket) do
    alert = Alerts.get_alert!(id)
    user_id = socket.assigns.current_scope.user.id

    case Alerts.acknowledge_alert(alert, user_id) do
      {:ok, _alert} ->
        {:noreply,
         socket
         |> put_flash(:info, "Alert acknowledged")
         |> load_alerts(socket.assigns.current_organization.id)}

      {:error, _changeset} ->
        {:noreply, put_flash(socket, :error, "Unable to acknowledge alert")}
    end
  end

  @impl true
  def handle_info({:new_alert, _device_id, _alert_type}, socket) do
    {:noreply, load_alerts(socket, socket.assigns.current_organization.id)}
  end

  @impl true
  def handle_info({:alert_resolved, _device_id, _alert_type}, socket) do
    {:noreply, load_alerts(socket, socket.assigns.current_organization.id)}
  end

  defp load_alerts(socket, organization_id) do
    alerts =
      case socket.assigns.filter do
        "active" ->
          Alerts.list_organization_active_alerts(organization_id)

        _ ->
          Alerts.list_organization_alerts(organization_id, 100)
      end

    assign(socket, :alerts, alerts)
  end
end
