defmodule CentralcloudOps.OnCallLive do
  use Phoenix.LiveView
  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"""
    <div class="section-title">📅 On-Call Schedules</div>

    <p style="color:#64748b;font-size:0.8rem;margin-bottom:1.5rem;">
      Updated at {Calendar.strftime(@last_updated, "%H:%M:%S")} UTC — refreshes every 60s
    </p>

    <div :if={@schedules == []} class="card" style="color:#64748b;">
      No schedules found in Grafana OnCall.
    </div>

    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:1rem;">
      <div :for={s <- @schedules} class="card">
        <div style="font-weight:700;font-size:1rem;margin-bottom:0.75rem;color:#f1f5f9;">
          {s["name"]}
        </div>

        <div style="margin-bottom:0.75rem;">
          <div style="font-size:0.7rem;color:#64748b;text-transform:uppercase;font-weight:600;margin-bottom:0.4rem;">
            Currently on-call
          </div>
          <div :if={s["current_oncall"] == []} style="color:#64748b;font-size:0.875rem;">
            Nobody on-call
          </div>
          <div :for={u <- s["current_oncall"]} style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.3rem;">
            <span style="width:28px;height:28px;background:#1e3a5f;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:0.7rem;color:#60a5fa;">
              {String.first(u["username"] || "?")}
            </span>
            <span style="font-weight:600;">{u["username"]}</span>
            <span :if={u["email"]} style="color:#64748b;font-size:0.8rem;">({u["email"]})</span>
          </div>
        </div>

        <div style="font-size:0.75rem;color:#475569;">
          <a href={"/oncall/schedules/#{s["id"]}"} style="color:#60a5fa;">View schedule →</a>
        </div>
      </div>
    </div>
    """
  end
end
