import type { CheckboxProps as AntCheckboxProps } from 'antd';
import { Checkbox as AntCheckbox, Form } from 'antd';
import type { CheckboxChangeEvent } from 'antd/lib/checkbox';
import type { FC } from 'react';
import type { BaseElementProps } from './types';

const { Item: FormItem } = Form;

type ElementProps = {
  text: string;
};

type CheckboxProps = AntCheckboxProps & ElementProps;

export default (function Checkbox({
  value,
  setValue,
  status,
  isValid,
  help,
  text,
  ...props
}: BaseElementProps<boolean> & ElementProps) {
  function handleChange(e: CheckboxChangeEvent) {
    setValue(e.target.checked);
  }

  return (
    <FormItem hasFeedback validateStatus={isValid === false ? 'error' : ''} help={help}>
      <AntCheckbox
        checked={value}
        onChange={handleChange}
        disabled={status === 'Disabled'}
        {...props}
      >
        {text}
      </AntCheckbox>
    </FormItem>
  );
} as FC<CheckboxProps>);
