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

const { Item: FormItem } = Form;

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

export default function Radio({
  value = null,
  setValue,
  options,
  status,
  isValid,
  help,
  spaceProps,
  ...props
}: ElementProps) {
  function handleChange(e: RadioChangeEvent) {
    setValue(e.target.value);
  }

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

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

export type { RadioProps };
