import {withFormik} from "formik";
import InnerCreateLanguageForm from "./InnerCreateLanguageForm";
import {AppRouterInstance} from "next/dist/shared/lib/app-router-context.shared-runtime";
import {QueryClient, UseMutateAsyncFunction} from "@tanstack/react-query";
import {toast} from "react-toastify";
import {handleAxiosError} from "@/lib/utils";
import * as yup from 'yup'
import { ServerResponse } from "@/types";

const CreateLanguageValidationSchema = yup.object({
  title:yup.string().required("عنوان وارد نشده است"),
  slug:yup.string().required("اسلاگ وارد نشده است")
})


export interface CreateLanguageFormProps {
  router: AppRouterInstance;
  createFn: UseMutateAsyncFunction<ServerResponse, Error, CreateLanguageFormValues, ServerResponse>;
  createPending: boolean;
  queryClient: QueryClient;
}

export interface CreateLanguageFormValues {
  title: string;
  slug: string;
}

const CreateLanguageForm = withFormik<
  CreateLanguageFormProps,
  CreateLanguageFormValues
>({
  mapPropsToValues: () => ({
    title: "",
    slug: "",
  }),
  validationSchema:CreateLanguageValidationSchema,
  handleSubmit: async (values, {props}) => {
    try {
      const {message} = await props.createFn(values);

      toast.success(message);
      props.queryClient.invalidateQueries({queryKey: ["get-all-languages"]});
      props.router.refresh();
    } catch (error) {
      toast.error(handleAxiosError(error));
    }
  },
})(InnerCreateLanguageForm);

export default CreateLanguageForm;
