defmodule CentralcloudOps.DashboardLive do
  use Phoenix.LiveView
  alias CentralcloudCore.OnCall

  @refresh_ms 30_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

  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
    firing   = fetch_groups("firing")
    acked    = fetch_groups("acknowledged")
    resolved = fetch_groups("resolved", limit: 5)

    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()
    )
  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"""
    <div class="section-title">🔥 Operations Dashboard</div>

    <div class="stat-grid">
      <div class="stat-card">
        <div class="stat-label">Firing</div>
        <div class={"stat-value #{if @firing_count > 0, do: "red", else: "green"}"}>{@firing_count}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Acknowledged</div>
        <div class={"stat-value #{if @acked_count > 0, do: "orange", else: "green"}"}>{@acked_count}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Recent Resolved</div>
        <div class="stat-value blue">{length(@recent_resolved)}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Last Updated</div>
        <div style="font-size:0.8rem;color:#64748b;margin-top:0.5rem;">
          {Calendar.strftime(@last_updated, "%H:%M:%S")} UTC
        </div>
      </div>
    </div>

    <div :if={@firing != []} style="margin-bottom:1.5rem;">
      <div class="section-title" style="color:#f87171;">🚨 Firing Alerts</div>
      <div class="card" style="padding:0;">
        <table>
          <thead>
            <tr>
              <th>Alert</th>
              <th>Source</th>
              <th>Started</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr :for={ag <- @firing}>
              <td>
                <a href={"/incidents/#{ag["id"]}"} style="color:#f87171;font-weight:600;">
                  {ag["render_for_web"]["title"] || ag["id"]}
                </a>
              </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>
                <button class="btn btn-warning" phx-click="ack" phx-value-id={ag["id"]}>Ack</button>
                <button class="btn btn-success" phx-click="resolve" phx-value-id={ag["id"]} style="margin-left:0.4rem;">Resolve</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div :if={@acked != []} style="margin-bottom:1.5rem;">
      <div class="section-title" style="color:#fb923c;">⏳ Acknowledged</div>
      <div class="card" style="padding:0;">
        <table>
          <thead>
            <tr><th>Alert</th><th>Source</th><th>Acked At</th><th>Actions</th></tr>
          </thead>
          <tbody>
            <tr :for={ag <- @acked}>
              <td>
                <a href={"/incidents/#{ag["id"]}"} style="color:#fb923c;font-weight:600;">
                  {ag["render_for_web"]["title"] || ag["id"]}
                </a>
              </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["acknowledged_at"])}</td>
              <td>
                <button class="btn btn-success" phx-click="resolve" phx-value-id={ag["id"]}>Resolve</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div :if={@firing == [] and @acked == []} class="card" style="text-align:center;padding:3rem;color:#4ade80;">
      <div style="font-size:2rem;margin-bottom:0.5rem;">✅</div>
      <div style="font-weight:600;">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
