"use client";
import {withFormik} from "formik";
import InnerLoginForm from "./InnerLoginForm";
import * as yup from "yup";
import {toast} from "react-toastify";
import {AppRouterInstance} from "next/dist/shared/lib/app-router-context.shared-runtime";
import {UseMutateAsyncFunction} from "@tanstack/react-query";
import {handleAxiosError} from "@/lib/utils";
import {ServerResponse} from "@/types";
export interface LoginFormValues {
  username: string;
  password: string;
  rememberMe: boolean;
}
export interface LoginFormProps {
  router: AppRouterInstance;
  loginFn: UseMutateAsyncFunction<
    ServerResponse,
    Error,
    LoginFormValues,
    ServerResponse
  >;
  loginPending: boolean;
}

const LoginFormValidationSchema = yup.object({
  username: yup.string().required("نام کاربری وارد نشده است"),
  password: yup.string().required("کلمه عبور وارد نشده است"),
});

const LoginForm = withFormik<LoginFormProps, LoginFormValues>({
  mapPropsToValues: () => ({
    username: "",
    password: "",
    rememberMe: false,
  }),
  validationSchema: LoginFormValidationSchema,
  handleSubmit: async (values, {props}) => {
    try {
      const {message} = await props.loginFn(values);
      toast.success(message);
      props.router.refresh();
    } catch (error) {
      toast.error(handleAxiosError(error));
    }
  },
})(InnerLoginForm);

export default LoginForm;
