import {withFormik} from "formik";
import * as Yup from "yup";
import {Language, ServerResponse} from "@/types";
import {AppRouterInstance} from "next/dist/shared/lib/app-router-context.shared-runtime";
import {UseMutateAsyncFunction} from "@tanstack/react-query";
import {toast} from "react-toastify";
import {handleAxiosError} from "@/lib/utils";
import InnerUpdateExpertiseForm from "./InnerUpdateExpertise";
export const translationSchema = Yup.object({
  lang_id: Yup.number().required("Language is required"),

  displayName: Yup.string()
    .max(255, "Display name is too long")
    .required("Display name is required"),
});

export const CreateExpertiseValidationSchema = Yup.object({
  slug: Yup.string().required("اسلاگ الزامیست"),

  translations: Yup.array()
    .of(translationSchema)
    .min(1, "حداقل یک ترجمه الزامی است")
    .required("Translations are required"),
});

export interface CreateExpertiseTranslation {
  lang_id: number;
  displayName: string;
}
// function buildInitialTranslations(
//   languages: Language[]
// ): CreateExpertiseTranslation[] {
//   return languages.map((lang) => ({
//     lang_id: lang.id,
//     displayName: "",
//   }));
// }
export interface UpdateExpertiseProps {
  router: AppRouterInstance;
  languages: Language[];
  updateFn: UseMutateAsyncFunction<
    ServerResponse,
    Error,
    {data: CreateExpertiseValues; id: string},
    ServerResponse
  >;
  updatePending: boolean;
  preValues: {
    translations: {
      id: number;
      lang_id: number;
      expertiseId: number;
      displayName: string;
    }[];
  } & {
    slug: string;
    id: number;
  };
  id: string;
}
export interface CreateExpertiseValues {
  translations: CreateExpertiseTranslation[];
  slug: string;
}
const UpdateExpertiseForm = withFormik<
  UpdateExpertiseProps,
  CreateExpertiseValues
>({
  mapPropsToValues: (props) => ({
    slug: props.preValues.slug,
    translations: props.preValues.translations,
  }),
  validationSchema: CreateExpertiseValidationSchema,
  handleSubmit: async (values, {props}) => {
    try {
      const {message} = await props.updateFn({data: values, id: props.id});

      toast.success(message);
      props.router.push("/expertise");
    } catch (error) {
      toast.error(handleAxiosError(error));
    }
  },
})(InnerUpdateExpertiseForm);

export default UpdateExpertiseForm;
