defmodule CentralcloudOps.StakeholdersLive do
  use Phoenix.LiveView
  alias CentralcloudCore.{HostBill, OnCall}

  def mount(_params, _session, socket) do
    {:ok, load(socket)}
  end

  def handle_event("search", %{"q" => q}, socket) do
    filtered =
      socket.assigns.clients
      |> Enum.filter(fn c ->
        name = String.downcase(c["firstname"] <> " " <> c["lastname"] <> " " <> (c["companyname"] || ""))
        String.contains?(name, String.downcase(q))
      end)

    {:noreply, assign(socket, filtered_clients: filtered, query: q)}
  end

  def handle_event("select_client", %{"id" => id}, socket) do
    client_id = String.to_integer(id)

    services =
      case HostBill.get_client_services(client_id) do
        {:ok, %{"products" => p}} -> p
        _ -> []
      end

    client = Enum.find(socket.assigns.clients, &(&1["id"] == id))

    {:noreply, assign(socket, selected_client: client, client_services: services)}
  end

  defp load(socket) do
    clients =
      case HostBill.get_clients() do
        {:ok, %{"clients" => c}} -> c
        _ -> []
      end

    firing =
      case OnCall.list_alert_groups(status: "firing") do
        {:ok, %{"results" => r}} -> r
        _ -> []
      end

    assign(socket,
      page_title: "Stakeholders",
      clients: clients,
      filtered_clients: clients,
      selected_client: nil,
      client_services: [],
      active_incidents: firing,
      query: ""
    )
  end

  def render(assigns) do
    ~H"""
    <div class="section-title">👥 Stakeholder Management</div>

    <div style="display:grid;grid-template-columns:320px 1fr;gap:1.5rem;align-items:start;">

      <%!-- Client list --%>
      <div class="card" style="padding:0;">
        <div style="padding:1rem;border-bottom:1px solid #1e3a5f;">
          <form phx-change="search" phx-submit="search">
            <input type="text" name="q" value={@query} placeholder="Search clients…"
                   style="width:100%;padding:0.5rem 0.75rem;background:#0a0f1e;border:1px solid #1e3a5f;
                          border-radius:5px;color:#e2e8f0;font-size:0.85rem;"/>
          </form>
        </div>
        <div style="max-height:600px;overflow-y:auto;">
          <div :for={c <- @filtered_clients}
               phx-click="select_client" phx-value-id={c["id"]}
               style={"padding:0.75rem 1rem;cursor:pointer;border-bottom:1px solid #0f172a;font-size:0.875rem;
                       #{if @selected_client && @selected_client["id"] == c["id"], do: "background:#1e3a5f;", else: ""}"}>
            <div style="font-weight:600;">{c["firstname"]} {c["lastname"]}</div>
            <div :if={c["companyname"] != ""} style="color:#64748b;font-size:0.78rem;">{c["companyname"]}</div>
          </div>
          <div :if={@filtered_clients == []} style="padding:1.5rem;color:#64748b;text-align:center;font-size:0.875rem;">
            No clients found
          </div>
        </div>
      </div>

      <%!-- Client detail / comms panel --%>
      <div>
        <div :if={is_nil(@selected_client)} class="card" style="color:#64748b;text-align:center;padding:3rem;">
          Select a client to view their services and send a status update.
        </div>

        <div :if={@selected_client}>
          <div class="card" style="margin-bottom:1rem;">
            <div style="font-size:1.1rem;font-weight:700;margin-bottom:0.25rem;">
              {@selected_client["firstname"]} {@selected_client["lastname"]}
            </div>
            <div style="color:#64748b;font-size:0.85rem;">{@selected_client["email"]}</div>
            <div :if={@selected_client["companyname"] != ""}
                 style="color:#94a3b8;font-size:0.8rem;">{@selected_client["companyname"]}</div>
          </div>

          <div class="card" style="margin-bottom:1rem;padding:0;">
            <div style="padding:0.75rem 1.25rem;border-bottom:1px solid #1e3a5f;font-weight:600;font-size:0.9rem;">
              Active Services ({length(@client_services)})
            </div>
            <div :if={@client_services == []} style="padding:1rem 1.25rem;color:#64748b;font-size:0.85rem;">
              No services found
            </div>
            <table :if={@client_services != []}>
              <thead><tr><th>Service</th><th>Status</th><th>Next Due</th></tr></thead>
              <tbody>
                <tr :for={svc <- @client_services}>
                  <td style="font-size:0.85rem;">{svc["name"]}</td>
                  <td>
                    <span class={"badge #{if svc["status"] == "Active", do: "badge-resolved", else: "badge-acked"}"}>
                      {svc["status"]}
                    </span>
                  </td>
                  <td style="color:#64748b;font-size:0.8rem;">{svc["nextduedate"]}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div class="card">
            <div style="font-weight:600;margin-bottom:1rem;font-size:0.9rem;">📢 Send Status Update</div>
            <div :if={@active_incidents != []} style="margin-bottom:1rem;">
              <div style="font-size:0.75rem;color:#64748b;text-transform:uppercase;font-weight:600;margin-bottom:0.5rem;">
                Link to active incident
              </div>
              <div style="display:flex;flex-wrap:wrap;gap:0.4rem;">
                <span :for={inc <- @active_incidents}
                      style="background:#4c0519;border:1px solid #dc2626;border-radius:4px;
                             padding:0.2rem 0.5rem;font-size:0.75rem;cursor:pointer;">
                  {inc["render_for_web"]["title"] || inc["id"]}
                </span>
              </div>
            </div>
            <textarea rows="4"
              placeholder="Type a status update to send to this client via HostBill ticket…"
              style="width:100%;padding:0.6rem;background:#0a0f1e;border:1px solid #1e3a5f;
                     border-radius:5px;color:#e2e8f0;font-size:0.85rem;resize:vertical;margin-bottom:0.75rem;">
            </textarea>
            <button class="btn btn-primary" style="opacity:0.5;cursor:not-allowed;" disabled>
              Send via HostBill ticket (coming soon)
            </button>
          </div>
        </div>
      </div>
    </div>
    """
  end
end
