import {editUserPassword} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {LOGIN_PATH} from '@routes';
import {userStore} from '@stores';
import {useMutation} from '@tanstack/react-query';
import {message} from 'antd';
import {useEffect} from 'react';
import {useForm} from 'react-hook-form';
import {useNavigate} from 'react-router-dom';
import {object, string} from 'yup';
import {useStore} from 'zustand';

type FormState = {
  oldPassword: string;
  newPassword: string;
  repeatPassword: string;
};

const validate = object({
  oldPassword: string().required('请输入原密码'),
  newPassword: string().required('请输入新密码'),
});

export function useEditPassword(onClose: () => void) {
  const logout = useStore(userStore, state => state.logout);
  const navigate = useNavigate();

  return useMutation({
    mutationFn: editUserPassword,
    onSuccess({msg}) {
      if (msg === '200') {
        onClose();
        message.success('修改成功，请重新登录');
        logout();
        navigate(LOGIN_PATH);
      }
    },
  });
}

export function useFormState(visible: boolean, onClose: () => void) {
  const {control, clearErrors, reset, setError, handleSubmit} =
    useForm<FormState>({
      defaultValues: {
        oldPassword: '',
        newPassword: '',
        repeatPassword: '',
      },
      resolver: yupResolver(validate),
    });

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

  const {isLoading, mutate} = useEditPassword(onClose);
  const userId = useStore(userStore, state => state.id);

  const onSubmit = handleSubmit(function ({
    oldPassword,
    newPassword,
    repeatPassword,
  }) {
    if (newPassword !== repeatPassword)
      return setError('repeatPassword', {
        type: 'custom',
        message: '两次输入密码不一致',
      });

    mutate({
      id: String(userId),
      password: oldPassword,
      newPassword,
    });
  });

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