import {filterOptions} from '@utils';
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;
  width?: string;
  data: {value: string, label: string}[];
  required?: boolean;
  showSearch?: boolean;
} & UseControllerProps<any, any>;

const ModalSelect: FC<Props> = function({
  control,
  name,
  label,
  placeholder,
  data,
  required,
  showSearch,
}) {
  return (
    <Row className='full-width' gutter={12}>
      <Col span={6} offset={2}>
        <label
          className={
            classNames([
              css.textRight,
              {[css.fieldRequired]: required ?? true},
            ])
          }
          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={showSearch}
                  rootClassName={classNames([css.modalSelect, css.filedWidth])}
                  data-testid={`select_${name}`}
                  defaultActiveFirstOption={false}
                  filterOption={showSearch ? filterOptions : false}
                  placeholder={placeholder ?? '请选择'}
                  id={`operation_${name}`}
                  // 处理placeholder不显示问题
                  value={value.length ? value : void 0}
                  onChange={onChange}
                  ref={ref}
                  options={data}
                  className='width-full'
                  getPopupContainer={(node: HTMLElement) => node.parentNode as HTMLElement}
                />
                <p className={classNames([css.errorTips, {[css.errorTipsHidden]: !errorTips}])}>
                  {errorTips}
                </p>
              </>
            );
          }}
        />

      </Col>
    </Row>
  );
};

export default ModalSelect;
