import {addInventory} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {useMutation} from '@tanstack/react-query';
import {message} from 'antd';
import {useEffect} from 'react';
import {useForm} from 'react-hook-form';
import {object, string} from 'yup';

type FormState = {
  inventoryTitle: string;
};

const validate = object({
  inventoryTitle: string().required('请输入盘点标题'),
});

export function useFormState({
  visible,
  onClose,
  onFetch,
}: {
  visible: boolean;
  onClose: () => void;
  onFetch: () => void;
}) {
  const {clearErrors, setValue, handleSubmit, control} = useForm<FormState>({
    resolver: yupResolver(validate),
    defaultValues: {
      inventoryTitle: '',
    },
  });

  useEffect(
    function () {
      if (visible) {
        setValue('inventoryTitle', '');
        clearErrors();
      }
    },
    [clearErrors, setValue, visible],
  );

  const {isLoading, mutate} = useMutation({
    mutationFn: addInventory,
    onSuccess({msg}) {
      if (msg === '200') {
        onClose();
        onFetch();
        message.success('新增成功');
      }
    },
  });

  const onSubmit = handleSubmit(function ({inventoryTitle}) {
    mutate(inventoryTitle);
  });

  return [{control, isLoading}, {onSubmit}] as const;
}
