import { render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { waitForLoading } from './Loading.test.js';
import CreateTitle from './CreateTitle.js';
import { useState } from 'react';

vi.mock('../../assets/lightbulb.svg?react', () => ({
  default: () => <div data-testid="lightbulb-icon">Lightbulb</div>,
}));

describe('CreateTitle component', () => {
  test('renders the title tag label', () => {
    render(<CreateTitle accountId="12345" draftId="bead88f1-bd37-48a7-9861-46f04058141d" />);
    expect(screen.getByText('Title tag')).toBeInTheDocument();
  });

  test('displays Topic and Length validation sections', () => {
    render(<CreateTitle accountId="12345" draftId="bead88f1-bd37-48a7-9861-46f04058141d" />);
    expect(screen.getByText('Topic')).toBeInTheDocument();
    expect(screen.getByText('Length')).toBeInTheDocument();
  });

  test('renders the text input field', () => {
    render(<CreateTitle accountId="12345" draftId="bead88f1-bd37-48a7-9861-46f04058141d" />);
    const input = screen.getByTestId('title-tag-input');
    expect(input).toBeInTheDocument();
  });

  test('updates input value when typing', async () => {
    const user = userEvent.setup();
    const CreateTitleWrapper = () => {
      const [text, setText] = useState<string>('');
      return (
        <CreateTitle
          accountId="12345"
          draftId="bead88f1-bd37-48a7-9861-46f04058141d"
          text={text}
          setText={setText}
        />
      );
    };
    render(<CreateTitleWrapper />);

    const input = screen.getByTestId('title-tag-input');
    await user.clear(input);
    await user.type(input, 'My Test Title');

    expect(input).toHaveValue('My Test Title');
  });

  test('shows reload button in menu footer', async () => {
    const user = userEvent.setup();
    const { container } = render(
      <CreateTitle accountId="12345" draftId="bead88f1-bd37-48a7-9861-46f04058141d" />,
    );

    // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- custom component DOM structure
    const openButton = container.querySelector('.create-title__dropdown-indicator') as Element;
    await user.click(openButton);

    const reloadButton = screen.getByTestId('reload-titles');
    expect(reloadButton).toBeInTheDocument();
  });

  test('calls mutate when reload button is clicked', async () => {
    const user = userEvent.setup();
    const CreateTitleWrapper = () => {
      const [text, setText] = useState<string>('');
      return (
        <CreateTitle
          accountId="12345"
          draftId="bead88f1-bd37-48a7-9861-46f04058141d"
          text={text}
          setText={setText}
        />
      );
    };
    const { container } = render(<CreateTitleWrapper />);

    // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- custom component DOM structure
    const openButton = container.querySelector('.create-title__dropdown-indicator') as Element;
    await user.click(openButton);
    await waitForLoading();
    let firstOption = screen.getAllByRole('option')[0];
    expect(firstOption).toHaveTextContent(
      'Inside Gritty, Phanatic & Swoop: Philadelphia Mascot Legends',
    );

    const reloadButton = screen.getByTestId('reload-titles');
    await user.click(reloadButton);
    await waitForLoading();
    firstOption = screen.getAllByRole('option')[0];
    expect(firstOption).toHaveTextContent(
      'Gritty, Phanatic & Swoop: Ultimate Guide to Philly Mascots 2025',
    );
  });

  test('closes select when Close button is clicked', async () => {
    const user = userEvent.setup();
    const { container } = render(
      <CreateTitle accountId="12345" draftId="bead88f1-bd37-48a7-9861-46f04058141d" />,
    );

    // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- custom component DOM structure
    const openButton = container.querySelector('.create-title__dropdown-indicator') as Element;
    await user.click(openButton);
    await waitForLoading();

    const closeButton = screen.getByRole('button', { name: 'Close' });
    await user.click(closeButton);

    const listbox = screen.queryByRole('listbox');
    expect(listbox).not.toBeInTheDocument();
  });

  test('hides text input when menu is open', async () => {
    const user = userEvent.setup();
    const { container } = render(
      <CreateTitle accountId="12345" draftId="bead88f1-bd37-48a7-9861-46f04058141d" />,
    );

    let input = screen.queryByTestId('title-tag-input');
    expect(input).toBeInTheDocument();
    // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- custom component DOM structure
    const openButton = container.querySelector('.create-title__dropdown-indicator') as Element;
    await user.click(openButton);
    input = screen.queryByTestId('title-tag-input');
    expect(input).not.toBeInTheDocument();
  });

  test('validates title length correctly', async () => {
    const user = userEvent.setup();
    const CreateTitleWrapper = () => {
      const [text, setText] = useState<string>('');
      return (
        <CreateTitle
          accountId="12345"
          draftId="bead88f1-bd37-48a7-9861-46f04058141d"
          text={text}
          setText={setText}
        />
      );
    };
    render(<CreateTitleWrapper />);

    const input = screen.getByTestId('title-tag-input');
    // Type exactly 55 characters (within valid range of 50-61)
    await user.type(input, 'A'.repeat(55));

    const indicators = screen.getAllByTestId('form-indicator');
    const lengthIndicator = indicators[1]; // Second indicator is for length
    expect(lengthIndicator).toHaveAttribute('data-valid', 'true');
  });

  test('applies open class to form when menu is open', async () => {
    const user = userEvent.setup();
    const { container } = render(
      <CreateTitle accountId="12345" draftId="bead88f1-bd37-48a7-9861-46f04058141d" />,
    );

    // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- checking CSS class state
    const form = container.querySelector('.create-title__form');
    expect(form).not.toHaveClass('create-title__form--is-open');

    // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access -- custom component DOM structure
    const openButton = container.querySelector('.create-title__dropdown-indicator') as Element;
    await user.click(openButton);

    expect(form).toHaveClass('create-title__form--is-open');
  });
});
