import {useForm} from 'react-hook-form';
import {yupResolver} from '@hookform/resolvers/yup';
import {object, string} from 'yup';
import {useMutation} from '@tanstack/react-query';
import {userLogin} from '@apis';
import {useBoolean} from 'ahooks';
import {message} from 'antd';
import {useStore} from 'zustand';
import {userStore} from '@stores';
import {useNavigate} from 'react-router-dom';
import {HOME_PATH} from '@routes';
import {USER_TOKEN_STORAGE} from '@utils';

type FormState = {
  name: string;
  password: string;
};

const validate = object({
  name: string().required('请输入账号'),
  password: string().required('请输入密码'),
});

function useLogin() {
  const [state, {set}] = useBoolean();
  const userStoreDispatch = useStore(userStore, state => state.init);
  const navigate = useNavigate();

  const mutation = useMutation(
    async function(params: {name: string, password: string}) {
      const {name, password} = params;
      return userLogin(name, password);
    },
    {
      onSuccess(data) {
        if (data.msg === '200') {
          message.success('登录成功');
          sessionStorage.setItem(USER_TOKEN_STORAGE, JSON.stringify(data.data));
          set(true);
          userStoreDispatch(data.data);
          navigate(HOME_PATH, {replace: true});
        }
      },
    },
  );

  return {...mutation, isDisable: state};
}

export function useFormState() {
  const {handleSubmit, formState: {errors}, control} = useForm<FormState>({
    resolver: yupResolver(validate),
  });
  const {isLoading, mutate, isDisable} = useLogin();

  const onSubmit = handleSubmit(function(val) {
    const {name, password} = val;
    mutate({name, password});
  });

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