import {withFormik} from "formik";
import InnerCreateMedicalPackageForm from "./InnerCreateMedicalPackageForm";
import {QueryClient, UseMutateAsyncFunction} from "@tanstack/react-query";
import {Language, ServerResponse} from "@/types";
import {toast} from "react-toastify";
import {handleAxiosError} from "@/lib/utils";

export interface CreateMedicalPackageProps {
  queryClient: QueryClient;
  languages: Language[];
  parents: {
    translations: {
      id: number;
      lang_id: number | null;
      title: string;
      content: string | null;
      medicalPackageId: number | null;
    }[];
    id: number;
    thumbnail_id: number;
    icon: string | null;
    priority: number | null;
    parent_id: number | null;
  }[];
  createFn: UseMutateAsyncFunction<
    ServerResponse,
    Error,
    CreateMedicalPackageValues,
    ServerResponse
  >;
  createPending: boolean;
}
export interface CreateMedicalPackageValues {
  translations: CreateMedicalPackageTranslation[];
  icon: string;
  thumbnail_id: number | null;
  priority: number;
  parent_id: number | null;
  price:string
}
export interface CreateMedicalPackageTranslation {
  lang_id: number;
  title: string;
  content: string;
}
function buildInitialTranslations(
  languages: Language[],
): CreateMedicalPackageTranslation[] {
  return languages.map((lang) => ({
    lang_id: lang.id,
    title: "",
    content: "",
    // position: "",
  }));
}
const CreateMedicalPackageForm = withFormik<
  CreateMedicalPackageProps,
  CreateMedicalPackageValues
>({
  mapPropsToValues: (props) => ({
    translations: buildInitialTranslations(props.languages),
    icon: "",
    price:"",
    priority: 1,
    thumbnail_id: null,
    parent_id: null,
  }),
  handleSubmit: async (values, {props}) => {
    console.log(values)
    try {
      const {message} = await props.createFn(values);
      toast.success(message);

      props.queryClient.invalidateQueries({
        queryKey: ["get-all-medical-packages"],
      });
    } catch (error) {
      toast.error(handleAxiosError(error));
    }
  },
})(InnerCreateMedicalPackageForm);

export default CreateMedicalPackageForm;
