defmodule CentralcloudStaff.StakeholdersLive do
  use CentralcloudStaffWeb, :live_view
  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"""
    <h1 class="text-lg font-bold text-slate-100 mb-5 flex items-center gap-2">👥 Stakeholder Management</h1>

    <div class="grid grid-cols-[320px_1fr] gap-6 items-start">

      <%!-- Client list panel --%>
      <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg overflow-hidden">
        <div class="p-3 border-b border-[#1e3a5f]">
          <form phx-change="search" phx-submit="search">
            <input
              type="text"
              name="q"
              value={@query}
              placeholder="Search clients…"
              class="w-full px-3 py-1.5 bg-[#0a0f1e] border border-[#1e3a5f] rounded text-slate-200
                     text-sm outline-none focus:border-blue-600 placeholder-slate-600"
            />
          </form>
        </div>
        <div class="max-h-[600px] overflow-y-auto">
          <div
            :for={c <- @filtered_clients}
            phx-click="select_client"
            phx-value-id={c["id"]}
            class={[
              "px-4 py-3 cursor-pointer border-b border-[#0f172a] text-sm transition-colors hover:bg-[#0f1a2e]",
              if(@selected_client && @selected_client["id"] == c["id"], do: "bg-[#1e3a5f]")
            ]}
          >
            <div class="font-semibold text-slate-200">{c["firstname"]} {c["lastname"]}</div>
            <div :if={c["companyname"] != ""} class="text-slate-500 text-xs">{c["companyname"]}</div>
          </div>
          <div :if={@filtered_clients == []}
               class="p-6 text-slate-500 text-center text-sm">
            No clients found
          </div>
        </div>
      </div>

      <%!-- Client detail panel --%>
      <div>
        <div :if={is_nil(@selected_client)}
             class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-12 text-center text-slate-500">
          Select a client to view their services and send a status update.
        </div>

        <div :if={@selected_client} class="flex flex-col gap-4">
          <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-5">
            <p class="text-lg font-bold text-slate-100">
              {@selected_client["firstname"]} {@selected_client["lastname"]}
            </p>
            <p class="text-slate-500 text-sm mt-0.5">{@selected_client["email"]}</p>
            <p :if={@selected_client["companyname"] != ""}
               class="text-slate-400 text-xs mt-0.5">{@selected_client["companyname"]}</p>
          </div>

          <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg overflow-hidden">
            <div class="px-5 py-3 border-b border-[#1e3a5f] font-semibold text-sm text-slate-200">
              Active Services ({length(@client_services)})
            </div>
            <div :if={@client_services == []}
                 class="px-5 py-4 text-slate-500 text-sm">
              No services found
            </div>
            <table :if={@client_services != []} class="w-full text-sm">
              <thead>
                <tr class="text-left border-b border-[#1e3a5f]">
                  <th class="px-5 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Service</th>
                  <th class="px-5 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Status</th>
                  <th class="px-5 py-2.5 text-slate-500 text-xs font-semibold uppercase tracking-wider">Next Due</th>
                </tr>
              </thead>
              <tbody>
                <tr :for={svc <- @client_services} class="border-t border-[#0a0f1e]">
                  <td class="px-5 py-3 text-slate-200">{svc["name"]}</td>
                  <td class="px-5 py-3">
                    <span class={svc_status_badge(svc["status"])}>{svc["status"]}</span>
                  </td>
                  <td class="px-5 py-3 text-slate-500 text-xs">{svc["nextduedate"]}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div class="bg-[#0f1629] border border-[#1e3a5f] rounded-lg p-5">
            <p class="font-semibold text-sm text-slate-200 mb-3">📢 Send Status Update</p>
            <div :if={@active_incidents != []} class="mb-4">
              <p class="text-slate-500 text-[11px] font-semibold uppercase tracking-wider mb-2">
                Active incidents
              </p>
              <div class="flex flex-wrap gap-1.5">
                <span
                  :for={inc <- @active_incidents}
                  class="bg-red-950 border border-red-700 rounded px-2 py-0.5 text-red-300 text-xs"
                >
                  {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…"
              class="w-full px-3 py-2 bg-[#0a0f1e] border border-[#1e3a5f] rounded text-slate-200
                     text-sm resize-y mb-3 focus:border-blue-600 outline-none placeholder-slate-600"
            >
            </textarea>
            <button
              disabled
              class="inline-flex items-center px-4 py-1.5 rounded bg-blue-700 text-white text-sm
                     font-medium opacity-50 cursor-not-allowed"
            >
              Send via HostBill ticket (coming soon)
            </button>
          </div>
        </div>
      </div>
    </div>
    """
  end

  defp svc_status_badge("Active"),
    do: "inline-block px-2 py-0.5 rounded text-[11px] font-semibold uppercase bg-green-950 text-green-300 border border-green-700"
  defp svc_status_badge(_),
    do: "inline-block px-2 py-0.5 rounded text-[11px] font-semibold uppercase bg-amber-950 text-amber-300 border border-amber-700"
end
