import * as React from 'react';
import {
  cleanup,
  render,
  screen,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
  vi,
  expect,
  describe,
  it,
  afterEach,
} from 'vitest';
import matchers from '@testing-library/jest-dom/matchers';
import {
  ToggleTickBox,
  ToggleTickBoxDerivedElement,
} from '.';

expect.extend(matchers);

describe('ToggleTickBox', () => {
  afterEach(() => {
    cleanup();
  });

  it('renders a checkbox', () => {
    render(
      <ToggleTickBox />,
    );
    const checkbox = screen.getByRole('checkbox');
    expect(checkbox).toBeInTheDocument();
  });

  describe('on indeterminate', () => {
    it('renders an indeterminate checkbox', () => {
      render(
        <ToggleTickBox
          indeterminate
        />,
      );
      const checkbox = screen.getByRole('checkbox');
      expect(checkbox).toHaveProperty('indeterminate', true);
    });

    it('acknowledges passed ref object', () => {
      const ref = React.createRef<ToggleTickBoxDerivedElement>();
      render(
        <ToggleTickBox
          indeterminate
          ref={ref}
        />,
      );
      expect(ref.current).toHaveProperty('indeterminate', true);
    });

    it('acknowledges passed legacy ref', () => {
      let refElement = null as null | ToggleTickBoxDerivedElement;
      const ref = (element: ToggleTickBoxDerivedElement) => {
        refElement = element;
      };

      render(
        <ToggleTickBox
          indeterminate
          ref={ref}
        />,
      );

      const checkbox = screen.getByRole('checkbox');
      expect(checkbox).toHaveProperty('indeterminate', true);
      expect(refElement).toBe(checkbox);
    });
  });

  it('renders a block tick box', () => {
    render(
      <ToggleTickBox
        block
      />,
    );

    const base = screen.getByTestId('base');
    expect(base).toHaveClass('flex');
  });

  it('renders a subtext', () => {
    render(
      <ToggleTickBox
        subtext="subtext"
      />,
    );
    const subtext: HTMLElement = screen.getByTestId('subtext');
    expect(subtext).toBeInTheDocument();
  });

  it('handles click events', async () => {
    const onClick = vi.fn().mockImplementationOnce(
      (e: React.MouseEvent<ToggleTickBoxDerivedElement>) => {
        e.preventDefault();
      },
    );
    render(
      <ToggleTickBox
        onClick={onClick}
      />,
    );
    const checkbox: HTMLInputElement = screen.getByRole('checkbox');
    await userEvent.click(checkbox);
    expect(onClick).toBeCalled();
  });

  it('handles change events', async () => {
    const onChange = vi.fn().mockImplementationOnce(
      (e: React.MouseEvent<ToggleTickBoxDerivedElement>) => {
        e.preventDefault();
      },
    );

    render(
      <ToggleTickBox
        onChange={onChange}
      />,
    );
    const checkbox: HTMLInputElement = screen.getByRole('checkbox');
    await userEvent.click(checkbox);
    expect(onChange).toBeCalled();
  });
});
