"use client";
import {QueryClient, UseMutateAsyncFunction} from "@tanstack/react-query";
import {withFormik} from "formik";
import {AppRouterInstance} from "next/dist/shared/lib/app-router-context.shared-runtime";
import {SetStateAction} from "react";
import {toast} from "react-toastify";
import InnerCreateTosForm from "./InnerCreateTosForm";
import { ServerResponse } from "@/types";

export interface CreateTosFormValues {
  title: string;
  content: string;
  version: string;
  isActive: boolean;
}

export interface CreateFormProps {
  router: AppRouterInstance;
  isPending: boolean;
  createFn: UseMutateAsyncFunction<ServerResponse, Error, CreateTosFormValues, ServerResponse>;
  mode: "new" | "edit" | "form";
  setMode: React.Dispatch<SetStateAction<"new" | "edit" | "form">>;
  queryClient: QueryClient;
}

const CreateTosForm = withFormik<CreateFormProps, CreateTosFormValues>({
  mapPropsToValues: () => ({
    title: "",
    content: "",
    isActive: false,
    version: "",
  }),
  handleSubmit: async (values, {props}) => {
    try {
      await props.createFn(values);
      toast.success("done");

      props.queryClient.invalidateQueries({queryKey: ["get-all-tos"]});
      props.setMode("new")
      props.router.refresh();
    } catch {
      toast.error("asdadasd");
    }
  },
})(InnerCreateTosForm);

export default CreateTosForm;
