import {Select as SelectOri} from 'antd';
import css from './index.module.css';
import {FC} from 'react';
import classNames from 'classnames';
import {useSelectFilterOptions} from '@hooks';

type Props = {
  label: string;
  value: string | string[];
  name: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  options: {label: string; value: string}[];
  loading?: boolean;
  multiple?: boolean;
  hideClear?: boolean;
};

const Select: FC<Props> = function ({
  label,
  value,
  onChange,
  placeholder,
  name,
  options,
  loading,
  multiple,
  hideClear,
}) {
  const [filterOptions, {onSelectSearch}] = useSelectFilterOptions(options);

  return (
    <div className={css.field}>
      <label htmlFor={`filter_${name}`} className={css.fieldLabel}>
        {label}
      </label>
      <div className={css.fieldWrapper}>
        <SelectOri
          allowClear={!hideClear}
          onClear={() => {
            onChange?.('');
          }}
          filterOption={false}
          showSearch
          className={classNames('width-full')}
          id={`filter_${name}`}
          data-testid={`filter_${name}`}
          placeholder={placeholder ?? '请选择'}
          value={value?.length ? (value as any) : void 0}
          options={filterOptions}
          onChange={onChange}
          loading={loading}
          getPopupContainer={(node: HTMLElement) =>
            node.parentNode as HTMLElement
          }
          onSearch={onSelectSearch}
          mode={multiple ? 'multiple' : void 0}
          maxTagCount='responsive'
        />
      </div>
    </div>
  );
};

export default Select;
