import React, { ReactElement, ReactNode } from 'react';
import css from '../../utils/css';

import RadioButton from './RadioButton';
import { StyledRadioButtonGroupWrapper } from './StyledRadio';

import { CommonProps } from '../common';

export interface RadioButtonGroupProps extends CommonProps {
  /**
   * Layout to render radios.
   */
  layout?: 'no-gap' | 'gap';
  /**
   * Radio group name, used for form submission, this MUST be unique in a page, otherwise same name radio group will share the same selection.
   */
  name: string;
  /**
   * Change event handler receiving selected radio's value.
   */
  onChange: (value: string | number) => void;
  /**
   * An array of radio options to be selected.
   */
  options: {
    disabled?: boolean;
    intent?: 'basic' | 'success' | 'primary' | 'warning' | 'danger' | 'error';
    text: ReactNode;
    value: string | number;
  }[];
  /**
   * Size of button.
   */
  size?: 'small' | 'medium' | 'large';
  /**
   * Radio input value.
   */
  value?: string | number;
}

const GAP_LAYOUTS = {
  small: 'gap-small',
  medium: 'gap-medium',
  large: 'gap-large',
} as const;

const RadioButtonGroup = ({
  layout = 'no-gap',
  name,
  value,
  onChange,
  options,
  size = 'medium',
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: RadioButtonGroupProps): ReactElement => {
  const checkedOptIndex = options.findIndex(
    option => option.value === value && option.disabled !== true
  );
  const preCheckedIndex = checkedOptIndex - 1;

  return (
    <StyledRadioButtonGroupWrapper
      preCheckedIndex={preCheckedIndex}
      themeLayout={layout === 'no-gap' ? layout : GAP_LAYOUTS[size]}
      id={id}
      className={className}
      style={{ ...style, ...css(sx) }}
      data-test-id={dataTestId}
    >
      {options.map(option => {
        return (
          <RadioButton
            key={option.value}
            name={name}
            text={option.text}
            value={option.value}
            intent={option.intent}
            disabled={option.disabled}
            checked={option.value === value}
            size={size}
            onChange={(e): void => {
              if (e.target.checked === true) {
                onChange(option.value);
              }
            }}
          />
        );
      })}
    </StyledRadioButtonGroupWrapper>
  );
};

export default RadioButtonGroup;
