import css from './index.module.css';
import {Row, Col, Input} 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;
  type?: string;
  disabled?: boolean;
  required?: boolean;
  onBlur?: () => void;
  tip?: string;
} & UseControllerProps<any, any>;

const OperationField: FC<Props> = function ({
  control,
  name,
  label,
  placeholder,
  type,
  disabled,
  required,
  onBlur,
  tip,
}) {
  return (
    <Row 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 (
              <>
                <Input
                  onBlur={onBlur}
                  className={classNames([css.modalField, css.filedWidth])}
                  disabled={disabled}
                  name={name}
                  placeholder={placeholder ?? '请输入'}
                  id={`operation_${name}`}
                  data-testid={`field_${name}`}
                  value={value}
                  onChange={onChange}
                  ref={ref}
                  type={type}
                />
                {tip && <p className={css.textTip}>{tip}</p>}
                <p
                  className={classNames([
                    css.errorTips,
                    {[css.errorTipsHidden]: !errorTips},
                  ])}
                >
                  {errorTips}
                </p>
              </>
            );
          }}
        />
      </Col>
    </Row>
  );
};

export default OperationField;
