import { forwardRef } from 'react';
import LegacyButton, { LegacyButtonProps } from './LegacyButton';
import { ButtonReferenceType, ButtonProps as NewButtonProps } from './Button.types';
import NewButton from './Button';

export type ButtonProps = LegacyButtonProps | NewButtonProps;

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

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

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

  const legacyButtonTypes: LegacyButtonProps['type'][] = [
    'accent',
    'negative',
    'positive',
    'primary',
    'pay',
    'secondary',
    'danger',
    'link',
  ];

  const resolveSize = () => {
    if (size) {
      return { xs: 'sm', sm: 'sm', md: 'md', lg: 'lg' }[size] || size;
    }

    return size;
  };

  return {
    ...newProps,
    size: resolveSize(),
    priority: mappedPriority,
    sentiment: mappedSentiment || ('sentiment' in props ? props.sentiment : null),
    type: type && !legacyButtonTypes.includes(type) ? type : props.htmlType || null,
    v2: true,
  } as NewButtonProps;
};

const Button = forwardRef<ButtonReferenceType, ButtonProps>(({ v2 = false, ...props }, ref) => {
  if (v2) {
    const mappedProps = mapProps(props as LegacyButtonProps);
    return <NewButton {...mappedProps} ref={ref} />;
  }

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

Button.displayName = 'Button';

export default Button;
