import { screen } from '@testing-library/react';
import PrimitiveButton from '../src';
import messages from '../../../i18n/commonMessages/Button.messages';
import { render } from '../../../test-utils';

describe('Button', () => {
  const defaultProps = {
    children: 'Click me',
  };

  const renderButton = (
    props?: Partial<typeof defaultProps>,
    locale = 'en',
    localeMessages = messages,
  ) => {
    return render(
      <PrimitiveButton {...defaultProps} {...props} />,
      // @ts-expect-error: props be missing properties from type
      { locale, messages: localeMessages },
    );
  };

  it('renders a button by default', () => {
    renderButton();
    expect(screen.getByRole('button')).toBeInTheDocument();
    expect(screen.getByRole('button')).toHaveTextContent('Click me');
  });

  it('applies the correct classes based on props', () => {
    const props = {
      ...defaultProps,
      className: 'custom-class',
    };

    renderButton(props);

    const button = screen.getByRole('button');
    expect(button).toHaveClass('wds-Button');
    expect(button).toHaveClass('custom-class');
  });

  it('disables the button when disabled is true', () => {
    const props = {
      ...defaultProps,
      disabled: true,
    };

    renderButton(props);

    const button = screen.getByRole('button');
    expect(button).toHaveClass('wds-Button--disabled');
    expect(button).toBeDisabled();
  });

  it('sets data-testid attribute', () => {
    const props = {
      ...defaultProps,
      testId: 'custom-id',
    };

    renderButton(props);

    const button = screen.getByTestId('custom-id');
    expect(button).toBeInTheDocument();
  });

  it('sets the type attribute to submit', () => {
    const props = {
      ...defaultProps,
      type: 'submit',
    };

    renderButton(props);

    const button = screen.getByRole('button');
    expect(button).toHaveAttribute('type', 'submit');
  });

  it('sets the type attribute to reset', () => {
    const props = {
      ...defaultProps,
      type: 'reset',
    };

    renderButton(props);

    const button = screen.getByRole('button');
    expect(button).toHaveAttribute('type', 'reset');
  });

  it('sets the type attribute to button by default', () => {
    renderButton();
    const button = screen.getByRole('button');
    expect(button).toHaveAttribute('type', 'button');
  });

  it('displays the aria-label in Spanish when loading', () => {
    const props = {
      ...defaultProps,
      loading: true,
    };

    const spanishMessages = {
      ...messages,
      'neptune.Button.loadingAriaLabel': 'cargando',
    };

    renderButton(props, 'es', spanishMessages);

    const button = screen.getByRole('button');
    expect(button).toHaveAttribute('aria-label', 'cargando');
  });
});
