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

import Radio from './Radio';
import { StyledWrapper, Spacer } from './StyledRadio';

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

export interface RadioGroupProps extends CommonProps {
  /**
   * Layout to render the group.
   */
  layout?: 'vertical' | 'horizontal';
  /**
   * 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;
    text: string | ReactElement;
    value: string | number;
  }[];
  /**
   * Radio input value.
   */
  value: string | number;
}

const RadioGroup = ({
  name,
  value,
  layout = 'vertical',
  onChange,
  options,
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: RadioGroupProps): ReactElement => {
  return (
    <StyledWrapper
      id={id}
      className={className}
      style={{ ...style, ...css(sx) }}
      data-test-id={dataTestId}
      themeLayout={layout}
    >
      {options.map((option, index) => {
        return (
          <React.Fragment key={option.value}>
            {index !== 0 && <Spacer themeLayout={layout} />}
            <Radio
              name={name}
              text={option.text}
              value={option.value}
              disabled={option.disabled}
              checked={option.value === value}
              onChange={(e): void => {
                if (e.target.checked) {
                  onChange(option.value);
                }
              }}
            />
          </React.Fragment>
        );
      })}
    </StyledWrapper>
  );
};

export default RadioGroup;
