defmodule MvWeb.GroupLive.ShowRemoveMemberTest do
  @moduledoc """
  Tests for removing members from groups via the Remove button.
  Tests successful remove, edge cases, and immediate removal (no confirmation).
  """

  use MvWeb.ConnCase, async: false
  import Phoenix.LiveViewTest
  use Gettext, backend: MvWeb.Gettext

  alias Mv.Membership
  alias Mv.Fixtures

  describe "successful remove member" do
    test "member is removed from group after clicking Remove", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      group = Fixtures.group_fixture()

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

      # Add member to group
      Membership.create_member_group(%{member_id: member.id, group_id: group.id},
        actor: system_actor
      )

      {:ok, view, _html} = live(conn, "/groups/#{group.slug}")

      assert has_element?(view, "[data-testid=group-show-members-table]", "Alice")

      view
      |> element("[data-testid=group-show-remove-member][phx-value-member_id='#{member.id}']")
      |> render_click()

      refute has_element?(view, "[data-testid=group-show-members-table]", "Alice")
    end

    test "member is successfully removed from group (verified in list)", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      group = Fixtures.group_fixture()

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

      Membership.create_member_group(%{member_id: member.id, group_id: group.id},
        actor: system_actor
      )

      {:ok, view, _html} = live(conn, "/groups/#{group.slug}")

      assert has_element?(view, "[data-testid=group-show-members-table]", "Bob")

      view
      |> element("[data-testid=group-show-remove-member][phx-value-member_id='#{member.id}']")
      |> render_click()

      refute has_element?(view, "[data-testid=group-show-members-table]", "Bob")
    end

    test "group member list updates automatically after remove", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      group = Fixtures.group_fixture()

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

      Membership.create_member_group(%{member_id: member.id, group_id: group.id},
        actor: system_actor
      )

      {:ok, view, _html} = live(conn, "/groups/#{group.slug}")

      assert has_element?(view, "[data-testid=group-show-members-table]", "Charlie")

      view
      |> element("[data-testid=group-show-remove-member][phx-value-member_id='#{member.id}']")
      |> render_click()

      refute has_element?(view, "[data-testid=group-show-members-table]", "Charlie")
    end

    test "member count updates automatically after remove", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      group = Fixtures.group_fixture()

      {:ok, member1} =
        Membership.create_member(
          %{
            first_name: "David",
            last_name: "Wilson",
            email: "david@example.com"
          },
          actor: system_actor
        )

      {:ok, member2} =
        Membership.create_member(
          %{
            first_name: "Eve",
            last_name: "Davis",
            email: "eve@example.com"
          },
          actor: system_actor
        )

      # Add both members
      Membership.create_member_group(%{member_id: member1.id, group_id: group.id},
        actor: system_actor
      )

      Membership.create_member_group(%{member_id: member2.id, group_id: group.id},
        actor: system_actor
      )

      {:ok, view, html} = live(conn, "/groups/#{group.slug}")

      # Get initial count (should be 2)
      initial_count = extract_member_count(html)
      assert initial_count >= 2

      # Remove one member (need to get member_id from HTML or use first available)
      # For this test, we'll remove the first member
      _html_before = render(view)
      # Extract first member ID from the rendered HTML or use a different approach
      # Since we have member1 and member2, we can target member1 specifically
      view
      |> element("[data-testid=group-show-remove-member][phx-value-member_id='#{member1.id}']")
      |> render_click()

      # Count should have decreased
      html = render(view)
      new_count = extract_member_count(html)
      assert new_count == initial_count - 1
    end

    test "no confirmation dialog appears (immediate removal)", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      group = Fixtures.group_fixture()

      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Frank",
            last_name: "Moore",
            email: "frank@example.com"
          },
          actor: system_actor
        )

      Membership.create_member_group(%{member_id: member.id, group_id: group.id},
        actor: system_actor
      )

      {:ok, view, _html} = live(conn, "/groups/#{group.slug}")

      view
      |> element("[data-testid=group-show-remove-member][phx-value-member_id='#{member.id}']")
      |> render_click()

      refute has_element?(view, "[data-testid=group-show-members-table]", "Frank")
    end
  end

  describe "edge cases" do
    test "remove works for last member in group (group becomes empty)", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      group = Fixtures.group_fixture()

      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Grace",
            last_name: "Taylor",
            email: "grace@example.com"
          },
          actor: system_actor
        )

      Membership.create_member_group(%{member_id: member.id, group_id: group.id},
        actor: system_actor
      )

      {:ok, view, _html} = live(conn, "/groups/#{group.slug}")

      assert has_element?(view, "[data-testid=group-show-members-table]", "Grace")

      view
      |> element("[data-testid=group-show-remove-member][phx-value-member_id='#{member.id}']")
      |> render_click()

      assert has_element?(view, "[data-testid=group-show-no-members]")

      html = render(view)
      count = extract_member_count(html)
      assert count == 0
    end

    test "remove works when member is in multiple groups (only this group affected)", %{
      conn: conn
    } do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      group1 = Fixtures.group_fixture()
      group2 = Fixtures.group_fixture()

      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Henry",
            last_name: "Anderson",
            email: "henry@example.com"
          },
          actor: system_actor
        )

      # Add member to both groups
      Membership.create_member_group(%{member_id: member.id, group_id: group1.id},
        actor: system_actor
      )

      Membership.create_member_group(%{member_id: member.id, group_id: group2.id},
        actor: system_actor
      )

      {:ok, view, _html} = live(conn, "/groups/#{group1.slug}")

      view
      |> element("[data-testid=group-show-remove-member][phx-value-member_id='#{member.id}']")
      |> render_click()

      refute has_element?(view, "[data-testid=group-show-members-table]", "Henry")

      {:ok, view2, _html2} = live(conn, "/groups/#{group2.slug}")
      assert has_element?(view2, "[data-testid=group-show-members-table]", "Henry")
    end

    test "remove is idempotent (no error if member already removed)", %{conn: conn} do
      system_actor = Mv.Helpers.SystemActor.get_system_actor()
      group = Fixtures.group_fixture()

      {:ok, member} =
        Membership.create_member(
          %{
            first_name: "Isabel",
            last_name: "Martinez",
            email: "isabel@example.com"
          },
          actor: system_actor
        )

      Membership.create_member_group(%{member_id: member.id, group_id: group.id},
        actor: system_actor
      )

      {:ok, view, _html} = live(conn, "/groups/#{group.slug}")

      view
      |> element("[data-testid=group-show-remove-member][phx-value-member_id='#{member.id}']")
      |> render_click()

      if has_element?(view, "[data-testid=group-show-members-table]", "Isabel") do
        view
        |> element("[data-testid=group-show-remove-member][phx-value-member_id='#{member.id}']")
        |> render_click()

        assert render(view)
      end
    end
  end

  # Helper function to extract member count from HTML
  defp extract_member_count(html) do
    case Regex.run(~r/Total:\s*(\d+)/, html) do
      [_, count_str] -> String.to_integer(count_str)
      _ -> 0
    end
  end
end
