/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { forwardRef } from 'react';
import LegacyButton, { ButtonProps as LegacyButtonProps } from '../LegacyButton';
import NewButton from '../Button';
import { ButtonProps as NewButtonProps } from '../Button/src/Button.types';

export type ButtonProps = {
  useNewButton?: boolean;
} & (LegacyButtonProps | NewButtonProps);

const mapProps = (props: LegacyButtonProps): NewButtonProps => {
  const { priority, size, type, as, ...newProps } = props;

  const priorityMapping: Record<string, Record<string, NewButtonProps['priority']>> = {
    accent: {
      primary: 'primary',
      secondary: 'tertiary',
      tertiary: 'minimal',
    },
    positive: {
      primary: 'primary',
      secondary: 'tertiary',
      tertiary: 'tertiary',
    },
    negative: {
      primary: 'primary',
      secondary: 'secondary',
      tertiary: 'secondary',
    },
  };

  const mappedPriority =
    type && priority ? priorityMapping[type]?.[priority] || priority : priority || undefined;
  const mappedAppearance = type === 'negative' ? 'negative' : undefined;

  return {
    ...newProps,
    size:
      size === 'xs' || size === 'sm' ? 'sm' : size === 'md' ? 'md' : size === 'lg' ? 'lg' : size,
    priority: mappedPriority,
    appearance: mappedAppearance || ('appearance' in props ? props.appearance : undefined),
    type: as === 'button' ? props.htmlType : undefined,
    href: as === 'a' ? props.href || '' : undefined,
  } as NewButtonProps;
};

const Button = forwardRef<HTMLButtonElement | HTMLAnchorElement, ButtonProps>(
  ({ useNewButton = false, ...props }, ref) => {
    if (useNewButton) {
      const mappedProps = mapProps(props as LegacyButtonProps);
      return <NewButton {...mappedProps} ref={ref as any} />;
    }

    return <LegacyButton {...(props as LegacyButtonProps)} ref={ref} />;
  },
);

Button.displayName = 'Button';

export default Button;
