defmodule MvWeb.UserLive.FormMemberSelectionTest do
  @moduledoc """
  UI tests for member selection and unlink workflow.
  Tests member selection behavior and unlink process.
  Related to Issue #168.
  """

  use MvWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  alias Mv.Accounts
  alias Mv.Membership

  # Helper to setup authenticated connection for admin
  defp setup_admin_conn(conn) do
    conn_with_oidc_user(conn, %{email: "admin@example.com"})
  end

  describe "member selection" do
    test "input field shows selected member name", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      conn = setup_admin_conn(conn)

      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Alice",
            last_name: "Johnson",
            email: "alice@example.com"
          },
          actor: system_actor
        )

      {:ok, view, _html} = live(conn, ~p"/users/new")

      # Focus and search
      view
      |> element("#member-search-input")
      |> render_focus()

      # Select member
      view
      |> element("[data-member-id='#{member.id}']")
      |> render_click()

      html = render(view)

      # Input field should show member name
      assert html =~ "Alice Johnson"
    end

    test "confirmation box appears", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      conn = setup_admin_conn(conn)

      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Bob",
            last_name: "Williams",
            email: "bob@example.com"
          },
          actor: system_actor
        )

      {:ok, view, _html} = live(conn, ~p"/users/new")

      # Focus input
      view
      |> element("#member-search-input")
      |> render_focus()

      # Select member
      view
      |> element("[data-member-id='#{member.id}']")
      |> render_click()

      html = render(view)

      # Confirmation box should appear
      assert html =~ "Selected"
      assert html =~ "Bob Williams"
      assert html =~ "Save to confirm linking"
    end

    test "hidden input stores member ID", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      conn = setup_admin_conn(conn)

      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Charlie",
            last_name: "Brown",
            email: "charlie@example.com"
          },
          actor: system_actor
        )

      {:ok, view, _html} = live(conn, ~p"/users/new")

      # Focus input
      view
      |> element("#member-search-input")
      |> render_focus()

      # Select member
      view
      |> element("[data-member-id='#{member.id}']")
      |> render_click()

      # Check socket assigns (member ID should be stored)
      assert view |> element("#user-form") |> has_element?()
    end
  end

  describe "unlink workflow" do
    test "unlink hides dropdown", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      conn = setup_admin_conn(conn)
      # Create user with linked member
      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Frank",
            last_name: "Wilson",
            email: "frank@example.com"
          },
          actor: system_actor
        )

      {:ok, user} =
        Accounts.create_user(
          %{
            email: "frank@example.com",
            member: %{id: member.id}
          },
          actor: system_actor
        )

      {:ok, view, _html} = live(conn, ~p"/users/#{user.id}/edit")

      # Click unlink button
      view
      |> element("button[phx-click='unlink_member']")
      |> render_click()

      html = render(view)

      # Dropdown should not be visible
      refute html =~ ~r/role="listbox"/
    end

    test "unlink shows warning", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      conn = setup_admin_conn(conn)
      # Create user with linked member
      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Grace",
            last_name: "Taylor",
            email: "grace@example.com"
          },
          actor: system_actor
        )

      {:ok, user} =
        Accounts.create_user(
          %{
            email: "grace@example.com",
            member: %{id: member.id}
          },
          actor: system_actor
        )

      {:ok, view, _html} = live(conn, ~p"/users/#{user.id}/edit")

      # Click unlink button
      view
      |> element("button[phx-click='unlink_member']")
      |> render_click()

      html = render(view)

      # Should show warning
      assert html =~ "Unlinking scheduled"
      assert html =~ "Cannot select new member until saved"
    end

    test "unlink disables input", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      conn = setup_admin_conn(conn)
      # Create user with linked member
      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Henry",
            last_name: "Anderson",
            email: "henry@example.com"
          },
          actor: system_actor
        )

      {:ok, user} =
        Accounts.create_user(
          %{
            email: "henry@example.com",
            member: %{id: member.id}
          },
          actor: system_actor
        )

      {:ok, view, _html} = live(conn, ~p"/users/#{user.id}/edit")

      # Click unlink button
      view
      |> element("button[phx-click='unlink_member']")
      |> render_click()

      html = render(view)

      # Input should be disabled
      assert html =~ ~r/disabled/
    end

    test "save re-enables member selection", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      conn = setup_admin_conn(conn)
      # Create user with linked member
      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Isabel",
            last_name: "Martinez",
            email: "isabel@example.com"
          },
          actor: system_actor
        )

      {:ok, user} =
        Accounts.create_user(
          %{
            email: "isabel@example.com",
            member: %{id: member.id}
          },
          actor: system_actor
        )

      {:ok, view, _html} = live(conn, ~p"/users/#{user.id}/edit")

      # Click unlink button
      view
      |> element("button[phx-click='unlink_member']")
      |> render_click()

      # Submit form
      view
      |> form("#user-form")
      |> render_submit()

      # Navigate back to edit
      {:ok, view, _html} = live(conn, ~p"/users/#{user.id}/edit")

      html = render(view)

      # Should now show member selection input (not disabled)
      assert html =~ "member-search-input"
      refute html =~ "Unlinking scheduled"
    end
  end
end
