import css from './index.module.css';
import {Row, Space, 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}[]
} & UseControllerProps<any, any>;

const ModalSelect: FC<Props> = function({
  control,
  name,
  width,
  label,
  placeholder,
  data,
}) {
  return (
    <Row style={{width: width ?? '300px'}}>
      <Space direction='vertical' className='width-full'>
        <Col>
          <label htmlFor={`operation_${name}`}>{label}</label>
        </Col>
        <Col>
          <Controller
            name={name}
            control={control}
            render={function({field: {value, onChange, ref}, formState: {errors}}) {
              const errorTips = errors[name]?.message?.toString() ?? '';

              return (
                <>
                  <Select
                    data-testid={`select_${name}`}
                    defaultActiveFirstOption={false}
                    filterOption={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>
      </Space>
    </Row>
  );
};

export default ModalSelect;
