import css from './index.module.css';
import {Input, Space} from 'antd';
import classNames from 'classnames';
import {FC} from 'react';
import {Controller, UseControllerProps} from 'react-hook-form';

type Props = {
  label: string;
  placeholder?: string;
  type?: string;
  disabled?: boolean;
  required?: boolean;
  onBlur?: () => void;
} & UseControllerProps<any, any>;

const FormField: FC<Props> = function ({
  control,
  name,
  label,
  placeholder,
  type,
  disabled,
  onBlur,
}) {
  return (
    <Space direction='vertical' className='width-full'>
      <label htmlFor={`operation_${name}`}>{label}</label>
      <Controller
        name={name}
        control={control}
        render={function ({
          field: {value, onChange, ref},
          formState: {errors},
        }) {
          const errorTips = errors[name]?.message?.toString() ?? '';
          return (
            <>
              <Input
                onBlur={onBlur}
                disabled={disabled}
                name={name}
                placeholder={placeholder ?? '请输入'}
                id={`operation_${name}`}
                data-testid={`field_${name}`}
                value={value}
                onChange={onChange}
                ref={ref}
                type={type}
              />
              <p
                className={classNames([
                  css.errorTips,
                  {[css.errorTipsHidden]: !errorTips},
                ])}
              >
                {errorTips}
              </p>
            </>
          );
        }}
      />
    </Space>
  );
};

export default FormField;
