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

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

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

export function useFormState({
  onClose,
  id,
  visible,
  onFetch,
}: {
  id: string;
  visible: boolean;
  onFetch: () => void;
  onClose: () => void;
}) {
  const isEdit = Boolean(id);
  const pid = useContextSection(context, state => state[0].pId);
  const formInstance = useForm<FormState>({
    defaultValues: {
      menuName: '',
      menuUrl: '',
      menuOrderBy: '0',
    },
    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, menuUrl, menuOrderBy}) {
    const params: AddMenuParams = {
      name: menuName,
      url: menuUrl,
      pId: pid ?? '0',
      orderBy: menuOrderBy,
      img: '',
    };

    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 pId = useContextSection(context, state => state[0].pId);

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

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