import {withFormik} from "formik";
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 InnerUpdateLanguageForm from "./InnerUpdateLanguageForm";
import {ServerResponse} from "@/types";

export interface UpdateLanguageFormProps {
  router: AppRouterInstance;
  updateFn: UseMutateAsyncFunction<
    ServerResponse,
    Error,
    {data: UpdateLanguageFormValues; id: string},
    ServerResponse
  >;
  updatePending: boolean;
  queryClient: QueryClient;
  id: string;
  preValues: {title: string; slug: string};
}

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

const UpdateLanguageForm = withFormik<
  UpdateLanguageFormProps,
  UpdateLanguageFormValues
>({
  mapPropsToValues: () => ({
    title: "",
    slug: "",
  }),
  handleSubmit: async (values, {props}) => {
    try {
      const {message} = await props.updateFn({data: values, id: props.id});

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

export default UpdateLanguageForm;
