import type { SelectProps } from 'antd';
import { Form, Select as AntSelect } from 'antd';
import type { FC } from 'react';
import { useMemo } from 'react';
import type { BaseElementProps, BaseOption } from './types';

const { Item: FormItem } = Form;

type ElementProps = {
  options: BaseOption[];
};

export default (function Select({
  value = null,
  setValue,
  options = [],
  status,
  isValid,
  help,
  ...props
}: BaseElementProps<string | null> & ElementProps) {
  const optionsWithNull = useMemo(
    () => [
      {
        label: 'Не выбрано',
        value: null,
      },
      ...options,
    ],
    [options]
  );

  return (
    <FormItem hasFeedback validateStatus={isValid === false ? 'error' : ''} help={help}>
      <AntSelect
        value={value}
        onChange={setValue}
        disabled={status === 'Disabled'}
        loading={status === 'Loading'}
        optionFilterProp="children"
        options={optionsWithNull}
        {...props}
      />
    </FormItem>
  );
} as FC<SelectProps>);
