import { describe, it, expect, vi } from 'vitest';
import * as React from "react";
import { render, screen, fireEvent } from "../../tests/test-utils";
import userEvent from "@testing-library/user-event";
import { TitleSelect } from "./TitleSelect";
import type { Title } from "../../types";

// Mock data
import titles from '../../mocks/data/titles.json';
const mockItem: Title = titles[0] as Title;

// Mock onTitleSelect function
const mockOnTitleSelect = vi.fn();

describe("TitleSelect Component", () => {
  it("renders the filter dropdown with the correct options", async () => {
    render(
      <TitleSelect
        onTitleSelect={mockOnTitleSelect}
      />
    );

    const filterDropdown = screen.getByRole("combobox");
    const options = screen.getAllByRole("option");

    expect(filterDropdown).toBeInTheDocument();
    expect(options).toHaveLength(3);

    expect(options[0]).toHaveTextContent("MOVIE");
    expect(options[1]).toHaveTextContent("SHOW");
    expect(options[2]).toHaveTextContent("ALL");
  });

  it("updates the active filter when a new option is selected", async () => {
    render(
      <TitleSelect
        onTitleSelect={mockOnTitleSelect}
      />
    );

    const filterDropdown = screen.getByRole("combobox");
    fireEvent.change(filterDropdown, { target: { value: "movie" } });

    // Check if the active filter is updated
    expect(filterDropdown).toHaveValue("movie");
  });

  it(
    "calls onTitleSelect when a title is selected",
    async () => {
      render(<TitleSelect onTitleSelect={mockOnTitleSelect} />);

      const query = mockItem.title;
      const input = screen.getByRole("textbox");

      userEvent.type(input, query);

      const listbox = await screen.findByRole("list");
      expect(listbox).toBeInTheDocument();

      const suggestion = await screen.findByText(query, { selector: "mark" }, { timeout: 3000 });
      expect(suggestion).toBeInTheDocument();

      await userEvent.click(suggestion);

      expect(mockOnTitleSelect).toHaveBeenCalledWith(mockItem);
    },
    5000
  );

  it("renders the help text when provided", async () => {
    const helpText = "Search for a title";
    render(
      <TitleSelect
        onTitleSelect={mockOnTitleSelect}
        help={<span>{helpText}</span>}
      />
    );

    const helpElement = screen.getByText(helpText);
    expect(helpElement).toBeInTheDocument();
  });

  it("initializes with the selectedTitle if provided", async () => {
    render(
      <TitleSelect
        onTitleSelect={mockOnTitleSelect}
        selectedTitle={mockItem}
      />
    );

    // Check if the input field is pre-filled with the selected title
    const input = screen.getByRole("textbox");
    expect(input).toHaveValue(mockItem.title);
  });
});