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

  @refresh_ms 30_000

  def mount(_params, _session, socket) do
    if connected?(socket), do: Process.send_after(self(), :refresh, @refresh_ms)

    try do
      {:ok, load(socket)}
    rescue
      e ->
        require Logger
        Logger.error("DashboardLive.mount crashed: #{Exception.format(:error, e, __STACKTRACE__)}")

        {:ok,
         assign(socket,
           page_title: "Dashboard",
           firing: [],
           acked: [],
           recent_resolved: [],
           firing_count: 0,
           acked_count: 0,
           last_updated: DateTime.utc_now()
         )}
    end
  end

  def handle_info(:refresh, socket) do
    Process.send_after(self(), :refresh, @refresh_ms)
    {:noreply, load(socket)}
  end

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

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

  defp load(socket) do
    if oncall_configured?() do
      [firing, acked, resolved] =
        ["firing", "acknowledged", "resolved"]
        |> Enum.map(fn s -> Task.async(fn -> fetch_groups(s) end) end)
        |> Task.await_many(2_000)

      assign(socket,
        page_title: "Dashboard",
        firing: firing,
        acked: acked,
        recent_resolved: resolved,
        firing_count: length(firing),
        acked_count: length(acked),
        last_updated: DateTime.utc_now()
      )
    else
      assign(socket,
        page_title: "Dashboard",
        firing: [],
        acked: [],
        recent_resolved: [],
        firing_count: 0,
        acked_count: 0,
        last_updated: DateTime.utc_now()
      )
    end
  end

  defp oncall_configured? do
    case Application.get_env(:centralcloud_core, :oncall) do
      nil -> false
      cfg -> is_binary(cfg[:token]) and cfg[:token] != ""
    end
  end

  defp fetch_groups(status, _opts \\ []) do
    case OnCall.list_alert_groups(status: status) do
      {:ok, %{"results" => results}} -> results
      _ -> []
    end
  end

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

    <div class="grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-4 mb-6">
      <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-5">
        <p class="text-slate-500 text-[11px] font-semibold uppercase tracking-wider mb-1">Firing</p>
        <p class={["text-3xl font-extrabold leading-none", if(@firing_count > 0, do: "text-red-400", else: "text-green-400")]}>
          {@firing_count}
        </p>
      </div>
      <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-5">
        <p class="text-slate-500 text-[11px] font-semibold uppercase tracking-wider mb-1">Acknowledged</p>
        <p class={["text-3xl font-extrabold leading-none", if(@acked_count > 0, do: "text-orange-400", else: "text-green-400")]}>
          {@acked_count}
        </p>
      </div>
      <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-5">
        <p class="text-slate-500 text-[11px] font-semibold uppercase tracking-wider mb-1">Recent Resolved</p>
        <p class="text-3xl font-extrabold leading-none text-sky-400">{length(@recent_resolved)}</p>
      </div>
      <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-5">
        <p class="text-slate-500 text-[11px] font-semibold uppercase tracking-wider mb-1">Last Updated</p>
        <p class="text-slate-500 text-sm mt-2">{Calendar.strftime(@last_updated, "%H:%M:%S")} UTC</p>
      </div>
    </div>

    <div :if={@firing != []} class="mb-6">
      <h2 class="text-base font-bold text-red-400 mb-3 flex items-center gap-2">🚨 Firing Alerts</h2>
      <div 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">Alert</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 text-slate-500 text-xs font-semibold uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr :for={ag <- @firing} class="border-t border-[#0a0f1e] hover:bg-[#0f1a2e] transition-colors">
              <td class="px-4 py-3">
                <a href={"/incidents/#{ag["id"]}"} class="text-red-400 font-semibold no-underline hover:text-red-300">
                  {ag["render_for_web"]["title"] || ag["id"]}
                </a>
              </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 flex items-center gap-1.5">
                <.button size="sm" color="warning" phx-click="ack" phx-value-id={ag["id"]}>Ack</.button>
                <.button size="sm" color="success" phx-click="resolve" phx-value-id={ag["id"]}>Resolve</.button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div :if={@acked != []} class="mb-6">
      <h2 class="text-base font-bold text-orange-400 mb-3 flex items-center gap-2">⏳ Acknowledged</h2>
      <div 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">Alert</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">Acked At</th>
              <th class="px-4 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr :for={ag <- @acked} class="border-t border-[#0a0f1e] hover:bg-[#0f1a2e] transition-colors">
              <td class="px-4 py-3">
                <a href={"/incidents/#{ag["id"]}"} class="text-orange-400 font-semibold no-underline hover:text-orange-300">
                  {ag["render_for_web"]["title"] || ag["id"]}
                </a>
              </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["acknowledged_at"])}</td>
              <td class="px-4 py-3">
                <.button size="sm" color="success" phx-click="resolve" phx-value-id={ag["id"]}>Resolve</.button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div
      :if={@firing == [] and @acked == []}
      class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-12 text-center text-green-400"
    >
      <div class="text-3xl mb-2">✅</div>
      <div class="font-semibold">All clear — no active alerts</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
