"use client";
import {withFormik} from "formik";
import InnerUpdateMedicalPackageForm from "./InnerUpdateMedicalPackageForm";
import {Language, ServerResponse} from "@/types";
import {QueryClient, UseMutateAsyncFunction} from "@tanstack/react-query";
import {CreateMedicalPackageTranslation} from "../new/CreateMedicalPackageForm";
import {toast} from "react-toastify";
import {handleAxiosError} from "@/lib/utils";
import {AppRouterInstance} from "next/dist/shared/lib/app-router-context.shared-runtime";

export interface UpdateMedicalPackageFormProps {
  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;
  }[];
  updateFn: UseMutateAsyncFunction<
    ServerResponse,
    Error,
    {id: string; data: UpdateMedicalPackageFormValues},
    ServerResponse
  >;
  updatePending: boolean;
  preValues: {
    translations: {
      id: number;
      title: string;
      content: string | null;
      lang_id: number | null;
      medicalPackageId: number | null;
    }[];
    id: number;
    thumbnail_id: number | null;
    thumbnail: {
      fileKey: string;
      filename: string | null;
      fileUrl: string | null;
    };
    icon: string | null;
    priority: number | null;
    parent_id: number | null;
  };
  id: string;
  router: AppRouterInstance;
}
export interface UpdateMedicalPackageFormValues {
  translations: {
    id: number;
    title: string;
    content: string | null;
    lang_id: number | null;
    medicalPackageId: number | null;
  }[];
  icon: string;
  thumbnail_id: number | null;
  priority: number;
  parent_id: number | null;
}

const UpdateMedicalPackageForm = withFormik<
  UpdateMedicalPackageFormProps,
  UpdateMedicalPackageFormValues
>({
  mapPropsToValues: (props) => ({
    translations: props.preValues.translations,
    icon: props.preValues.icon ?? "",
    priority: props.preValues.priority ?? 1,
    thumbnail_id: props.preValues.thumbnail_id ?? null,
    parent_id: props.preValues.parent_id ?? null,
  }),
  handleSubmit: async (values, {props}) => {
    try {
      const {message} = await props.updateFn({id: props.id, data: values});
      toast.success(message);
    } catch (error) {
      toast.error(handleAxiosError(error));
    }
  },
})(InnerUpdateMedicalPackageForm);

export default UpdateMedicalPackageForm;
