// @vitest-environment jsdom

import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ComponentProps } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { BallboxStoreClubDetail } from "@/lib/ballbox-store";
import { NetworkAdminVenueCard } from "@/components/network-admin-venue-card";

const clubs: BallboxStoreClubDetail[] = [
  {
    id: "club_1",
    atcSportclubId: "101",
    name: "Club One",
    locationName: "Buenos Aires",
    venues: [
      {
        id: "venue_1",
        name: "Venue One",
        slug: "venue-one",
        status: "active",
        machines: 1,
        screens: 2,
        screenIds: ["screen_a", "screen_b"],
        vendingMachines: [
          {
            id: "machine_1",
            label: "Machine One",
            active: true,
            screenId: "screen_a",
          },
        ],
      },
    ],
  },
];

function renderVenueCard(overrides?: Partial<ComponentProps<typeof NetworkAdminVenueCard>>) {
  return render(
    <NetworkAdminVenueCard
      clubId="club_1"
      venue={clubs[0].venues[0]}
      busy={false}
      setClubs={vi.fn()}
      machineForm={{ label: "", active: true }}
      setMachineForms={vi.fn()}
      emptyMachineForm={{ label: "", active: true }}
      venueStatusOptions={["active", "inactive"]}
      selectClassName="select"
      mutedPanelClassName="muted"
      insetPanelClassName="inset"
      wellClassName="well"
      runMutation={vi.fn()}
      {...overrides}
    />
  );
}

describe("NetworkAdminVenueCard", () => {
  afterEach(() => {
    cleanup();
  });

  it("updates the targeted venue name through setClubs", () => {
    const setClubs = vi.fn();
    renderVenueCard({ setClubs });

    fireEvent.change(screen.getByDisplayValue("Venue One"), { target: { value: "Venue Renamed" } });

    const update = setClubs.mock.calls[0]?.[0] as ((value: BallboxStoreClubDetail[]) => BallboxStoreClubDetail[]) | undefined;
    expect(update).toBeTypeOf("function");

    const nextClubs = update?.(clubs);
    expect(nextClubs?.[0].venues[0].name).toBe("Venue Renamed");
    expect(nextClubs?.[0].venues[0].slug).toBe("venue-one");
  });

  it("updates the targeted machine active flag through setClubs", () => {
    const setClubs = vi.fn();
    renderVenueCard({ setClubs });

    fireEvent.click(screen.getAllByRole("checkbox")[1]);

    const update = setClubs.mock.calls[0]?.[0] as ((value: BallboxStoreClubDetail[]) => BallboxStoreClubDetail[]) | undefined;
    expect(update).toBeTypeOf("function");

    const nextClubs = update?.(clubs);
    expect(nextClubs?.[0].venues[0].vendingMachines[0].active).toBe(false);
  });
});
