import {withFormik} from "formik";
import InnerCreateExpertiseForm from "./InnerCreateExpertiseForm";
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";
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 CreateExpertiseProps {
  router: AppRouterInstance;
  languages: Language[];
  createFn:UseMutateAsyncFunction<ServerResponse,Error,CreateExpertiseValues,ServerResponse>,
  createPending:boolean
}
export interface CreateExpertiseValues {
  translations: CreateExpertiseTranslation[];
  slug: string;
}
const CreateExpertiseForm = withFormik<
  CreateExpertiseProps,
  CreateExpertiseValues
>({
  mapPropsToValues: (props) => ({
    slug: "",
    translations: buildInitialTranslations(props.languages),
  }),
  validationSchema:CreateExpertiseValidationSchema,
  handleSubmit: async (values, {props}) => {
    try {
      const {message}=await props.createFn(values)

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

export default CreateExpertiseForm;
