import {editStorageType} from '@apis';
import {useMutation} from '@tanstack/react-query';
import {message} from 'antd';
import {useEffect} from 'react';
import {useForm} from 'react-hook-form';

type FormState = {
  storageType: string;
};

export function useFormState({
  id,
  type,
  onClose,
  onFetch,
}: {
  id: string;
  type: string;
  onClose: () => void;
  onFetch: () => void;
}) {
  const {control, setValue, clearErrors, handleSubmit} = useForm<FormState>({
    defaultValues: {storageType: ''},
  });

  useEffect(
    function () {
      setValue('storageType', type);
      clearErrors();
    },
    [clearErrors, setValue, type, id],
  );

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

  const onSubmit = handleSubmit(function ({storageType}) {
    mutate({id, warehouseType: storageType});
  });

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