import {addRole, editRole, getRoleInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {usePutData, useQueryDataInfo} from '@hooks';
import {AddRoleParams} from '@models';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';

type FormState = {
  roleName: string;
  roleRemarks: string;
};

const validate = object({
  roleName: string().required('请输入角色名称'),
});

export function useFormState({
  visible,
  onFetch,
  onClose,
  id,
}: {
  visible: boolean;
  id: string;
  onFetch: () => void;
  onClose: () => void;
}) {
  const formInstance = useForm<FormState>({
    defaultValues: {
      roleName: '',
      roleRemarks: '',
    },
    resolver: yupResolver(validate),
  });
  const {handleSubmit, clearErrors} = formInstance;

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

  const [isLoading, {addMutate, editMutate}] = usePutData({
    addFn: addRole,
    editFn: editRole,
    onClose,
    onFetch,
  });

  const onSubmit = handleSubmit(function ({roleName, roleRemarks}) {
    const params: AddRoleParams = {remarks: roleRemarks, roleName};

    id ? 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: getRoleInfo,
    params: [id],
    enabled: Boolean(id),
  });

  useEffect(
    function () {
      setValue('roleName', data?.roleName ?? '');
      setValue('roleRemarks', data?.remarks ?? '');
    },
    [data, setValue],
  );
}
