import {addMenu, editMenu, getMenuInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {usePutData, useQueryDataInfo} from '@hooks';
import {AddMenuParams} from '@models';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';

type FormState = {
  menuName: string;
  menuOrderBy: string;
  menuIcon: string;
};

const validate = object({
  menuName: string().required('请输入菜单名称'),
  menuOrderBy: string().required('请输入菜单排序'),
  menuIcon: string().required('请输入菜单图标'),
});

export function useFormState({
  onClose,
  id,
  visible,
  onFetch,
}: {
  id: string;
  visible: boolean;
  onFetch: () => void;
  onClose: () => void;
}) {
  const isEdit = Boolean(id);

  const formInstance = useForm<FormState>({
    defaultValues: {
      menuName: '',
      menuOrderBy: '0',
      menuIcon: '',
    },
    resolver: yupResolver(validate),
  });
  const {handleSubmit, clearErrors} = formInstance;
  const [isLoading, {addMutate, editMutate}] = usePutData({
    addFn: addMenu,
    editFn: editMenu,
    onClose,
    onFetch,
  });

  useEffect(
    function () {
      visible && clearErrors();
    },
    [clearErrors, visible],
  );

  const onSubmit = handleSubmit(function ({menuName, menuOrderBy, menuIcon}) {
    const params: AddMenuParams = {
      name: menuName,
      url: '.',
      pId: '0',
      orderBy: menuOrderBy,
      img: menuIcon,
    };
    isEdit ? editMutate({id, ...params}) : addMutate(params);
  });

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

export function useField() {
  return useFormContext<FormState>();
}

export function useFormValues(id: string) {
  const {setValue} = useFormContext<FormState>();

  const data = useQueryDataInfo({
    queryFn: getMenuInfo,
    params: ['0', id, 'PC'],
    enabled: Boolean(id),
  });

  useEffect(
    function () {
      setValue('menuName', data?.name ?? '');
      setValue('menuOrderBy', data?.orderBy ?? '0');
      setValue('menuIcon', data?.img ?? '');
    },
    [data, setValue],
  );
}
