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

  @refresh_ms 60_000

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

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

  defp load(socket) do
    schedules =
      case OnCall.list_schedules() do
        {:ok, %{"results" => results}} ->
          Enum.map(results, fn s ->
            on_call =
              case OnCall.current_oncall(s["id"]) do
                {:ok, users} -> users
                _ -> []
              end
            Map.put(s, "current_oncall", on_call)
          end)

        _ ->
          []
      end

    assign(socket, page_title: "On-Call", schedules: schedules, last_updated: DateTime.utc_now())
  end

  def render(assigns) do
    ~H"""
    <h1 class="text-lg font-bold text-slate-100 mb-1 flex items-center gap-2">📅 On-Call Schedules</h1>
    <p class="text-slate-500 text-xs mb-5">
      Updated at {Calendar.strftime(@last_updated, "%H:%M:%S")} UTC — refreshes every 60s
    </p>

    <div :if={@schedules == []}
         class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-6 text-slate-500">
      No schedules found in Grafana OnCall.
    </div>

    <div class="grid grid-cols-[repeat(auto-fill,minmax(320px,1fr))] gap-4">
      <div :for={s <- @schedules} class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-5">
        <p class="font-bold text-base text-slate-100 mb-3">{s["name"]}</p>

        <p class="text-slate-500 text-[11px] font-semibold uppercase tracking-wider mb-2">
          Currently on-call
        </p>
        <div :if={s["current_oncall"] == []} class="text-slate-500 text-sm">
          Nobody on-call
        </div>
        <div :for={u <- s["current_oncall"]} class="flex items-center gap-2 mb-1.5">
          <span class="w-7 h-7 bg-[#1e3a5f] rounded-full flex items-center justify-center text-[11px] text-sky-400 flex-shrink-0 font-bold">
            {String.first(u["username"] || "?")}
          </span>
          <span class="font-semibold text-sm">{u["username"]}</span>
          <span :if={u["email"]} class="text-slate-500 text-xs">({u["email"]})</span>
        </div>

        <div class="mt-3 text-xs">
          <a href={"/oncall/schedules/#{s["id"]}"} class="text-sky-400 hover:text-sky-300 no-underline">
            View schedule →
          </a>
        </div>
      </div>
    </div>
    """
  end
end
