import { render, screen } from '../../test-utils';
import userEvent from '@testing-library/user-event';
import { ListItem, type ListItemProps } from '../ListItem';

describe('ListItem.Checkbox', () => {
  const renderWith = (overrides: Partial<ListItemProps> = {}) =>
    render(<ListItem title="Test title" {...overrides} />);

  it('renders checkbox', () => {
    renderWith({ control: <ListItem.Checkbox /> });
    expect(screen.getByRole('checkbox')).toBeInTheDocument();
  });

  describe('checked state', () => {
    it('reflects checked state', () => {
      renderWith({ control: <ListItem.Checkbox checked onChange={jest.fn()} /> });
      expect(screen.getByRole('checkbox')).toBeChecked();
    });

    it('reflects unchecked state', () => {
      renderWith({ control: <ListItem.Checkbox checked={false} onChange={jest.fn()} /> });
      expect(screen.getByRole('checkbox')).not.toBeChecked();
    });

    it('supports indeterminate state', () => {
      renderWith({ control: <ListItem.Checkbox indeterminate /> });
      expect(screen.getByRole('checkbox')).toHaveProperty('indeterminate', true);
    });
  });

  describe('interactivity', () => {
    it('handles onChange events', async () => {
      const handleChange = jest.fn();
      renderWith({ control: <ListItem.Checkbox checked={false} onChange={handleChange} /> });

      await userEvent.click(screen.getByRole('checkbox'));
      expect(handleChange).toHaveBeenCalledTimes(1);
    });

    it('is disabled when ListItem is disabled', () => {
      renderWith({
        disabled: true,
        control: <ListItem.Checkbox checked={false} onChange={jest.fn()} />,
      });

      expect(screen.getByRole('checkbox')).toBeDisabled();
    });

    it('handles onFocus events', async () => {
      const handleFocus = jest.fn();
      renderWith({
        control: <ListItem.Checkbox checked={false} onFocus={handleFocus} onChange={() => {}} />,
      });

      await userEvent.tab();
      expect(handleFocus).toHaveBeenCalledTimes(1);
    });

    it('handles onBlur events', async () => {
      const handleBlur = jest.fn();
      renderWith({
        control: <ListItem.Checkbox checked={false} onBlur={handleBlur} onChange={() => {}} />,
      });

      const checkbox = screen.getByRole('checkbox');
      await userEvent.click(checkbox);
      await userEvent.tab();
      expect(handleBlur).toHaveBeenCalledTimes(1);
    });
  });

  it('supports name and value attributes', () => {
    const checkboxName = 'test-checkbox';
    const checkboxValue = 'test-value';
    renderWith({ control: <ListItem.Checkbox name={checkboxName} value={checkboxValue} /> });

    const checkbox = screen.getByRole('checkbox');
    expect(checkbox).toHaveAttribute('name', checkboxName);
    // eslint-disable-next-line jest-dom/prefer-to-have-value
    expect(checkbox).toHaveAttribute('value', checkboxValue);
  });
});
