import { render, screen } from '../../../test-utils';

import UploadImageStep from '.';

beforeAll(() => {
  Object.defineProperty(window, 'matchMedia', {
    writable: true,
    value: jest.fn().mockImplementation((query: string) => ({
      matches: false,
      media: query,
      onchange: null,
      addListener: jest.fn(),
      removeListener: jest.fn(),
      addEventListener: jest.fn(),
      removeEventListener: jest.fn(),
      dispatchEvent: jest.fn(),
    })),
  });
});

describe('uploadImageStep', () => {
  const UPLOADIMAGE_STEP_PROPS = {
    fileDropped: jest.fn(),
    isComplete: false,
    usAccept: 'image/*',
    usButtonText: 'Upload Image',
    usDisabled: false,
    usLabel: 'Upload your image',
    usHelpImage: 'https://example.com/help-image.png',
    usPlaceholder: 'Drag and drop an image or click to upload',
    errorMessage: '',
    errorIconLabel: '',
  };

  let container: HTMLElement;

  beforeEach(() => {
    const view = render(<UploadImageStep {...UPLOADIMAGE_STEP_PROPS} />);
    container = view.container;
  });

  test('renders container', () => {
    const processing = container.querySelector('.droppable-default-card');
    expect(processing).toBeInTheDocument();
  });

  test('renders helpImage or Upload icon', () => {
    const uploadIcons = screen.getAllByAltText('Upload your image');
    expect(uploadIcons.length).toBeGreaterThan(0);
    expect(uploadIcons[0]).toBeInTheDocument();
  });

  test('renders label', () => {
    expect(screen.getByText(UPLOADIMAGE_STEP_PROPS.usLabel)).toBeInTheDocument();
  });

  test('renders placeholder', () => {
    expect(screen.getByText(UPLOADIMAGE_STEP_PROPS.usPlaceholder)).toBeInTheDocument();
  });

  test('renders buttonText', () => {
    expect(screen.getByText(UPLOADIMAGE_STEP_PROPS.usButtonText)).toBeInTheDocument();
  });

  test('should render with `errorIconLabel` and `errorMessage` override', () => {
    const errorIconLabel = 'Error icon label';
    const errorMessage = 'Maximum filesize is 2MB.';
    const { container } = render(
      <UploadImageStep
        {...UPLOADIMAGE_STEP_PROPS}
        errorMessage={errorMessage}
        errorIconLabel={errorIconLabel}
      />,
    );

    expect(screen.getByLabelText(errorIconLabel)).toBeInTheDocument();
    expect(screen.getByText(errorMessage)).toBeInTheDocument();
  });

  test('focuses on the upload input when label is clicked', () => {
    const input = screen.getByLabelText(UPLOADIMAGE_STEP_PROPS.usButtonText);
    input.focus();
    expect(input).toHaveFocus();
  });

  test('triggers file selection on Enter key press', () => {
    const input = screen.getByLabelText(UPLOADIMAGE_STEP_PROPS.usButtonText);
    input.focus();
    const event = new KeyboardEvent('keydown', { key: 'Enter' });
    input.dispatchEvent(event);
    expect(input).toHaveFocus();
    expect(input).toHaveAttribute('type', 'file');
  });
});
