import {useSelectFilterOptions} from '@hooks';
import css from './index.module.css';
import {Row, Col, Select} from 'antd';
import classNames from 'classnames';
import {FC} from 'react';
import {Controller, UseControllerProps} from 'react-hook-form';

type Props = {
  label: string;
  placeholder?: string;
  /**@deprecated */
  width?: string;
  data: {value: string; label: string}[];
  required?: boolean;
  /** @deprecated */
  showSearch?: boolean;
  tip?: string;
  onSearch?: (value: string) => void;
  loading?: boolean;
  multiple?: boolean;
} & UseControllerProps<any, any>;

const ModalSelect: FC<Props> = function ({
  control,
  name,
  label,
  placeholder,
  data,
  required = true,
  tip,
  onSearch,
  loading,
  multiple,
}) {
  const [options, {onSelectSearch}] = useSelectFilterOptions(data);

  return (
    <Row className='full-width' gutter={12}>
      <Col span={6} offset={2}>
        <label
          className={classNames([
            css.textRight,
            {[css.fieldRequired]: required},
          ])}
          htmlFor={`operation_${name}`}
        >
          {label}
        </label>
      </Col>
      <Col span={12}>
        <Controller
          name={name}
          control={control}
          render={function ({
            field: {value, onChange, ref},
            formState: {errors},
          }) {
            const errorTips = errors[name]?.message?.toString() ?? '';

            return (
              <>
                <Select
                  showSearch
                  rootClassName={classNames([
                    css.modalSelect,
                    css.filedWidth,
                    {[css.multipleSelect]: multiple},
                  ])}
                  filterOption={false}
                  data-testid={`field_${name}`}
                  defaultActiveFirstOption={false}
                  placeholder={placeholder ?? '请选择'}
                  id={`field_${name}`}
                  // 处理placeholder不显示问题
                  value={value?.length ? value : void 0}
                  onChange={onChange}
                  ref={ref}
                  options={options}
                  className='width-full'
                  getPopupContainer={(node: HTMLElement) =>
                    node.parentNode as HTMLElement
                  }
                  onSearch={onSearch ? onSearch : onSelectSearch}
                  listHeight={150}
                  loading={loading}
                  mode={multiple ? 'multiple' : void 0}
                />
                {tip && <p className={css.textTip}>{tip}</p>}
                <p
                  className={classNames([
                    css.errorTips,
                    {[css.errorTipsHidden]: !errorTips},
                  ])}
                >
                  {errorTips}
                </p>
              </>
            );
          }}
        />
      </Col>
    </Row>
  );
};

export default ModalSelect;
