import type { BaseElementProps, BaseOption } from './types';
import type { RadioChangeEvent, RadioGroupProps, SpaceProps } from 'antd';
import { Form, Radio as AntRadio, Space } from 'antd';
import type { FC } from 'react';

const { Item: FormItem } = Form;

type ElementProps = BaseElementProps<string | null> & {
  options: BaseOption[];
  spaceProps?: SpaceProps;
};

type RadioProps = RadioGroupProps & {
  spaceProps?: SpaceProps;
};

function Radio({
  value = null,
  setValue,
  options,
  status,
  validateStatus,
  help,
  spaceProps,
  ...props
}: ElementProps) {
  function handleChange(event: RadioChangeEvent) {
    setValue(event.target.value);
  }

  return (
    <FormItem hasFeedback help={help} validateStatus={validateStatus}>
      <AntRadio.Group
        disabled={status === 'Disabled'}
        onChange={handleChange}
        value={value}
        {...props}
      >
        <Space {...spaceProps}>
          {options.map((option) => (
            <AntRadio key={option.value} value={option.value}>
              {option.label}
            </AntRadio>
          ))}
        </Space>
      </AntRadio.Group>
    </FormItem>
  );
}

export default Radio as FC<RadioProps>;
