"use client";
import {withFormik} from "formik";
import {AppRouterInstance} from "next/dist/shared/lib/app-router-context.shared-runtime";
import * as Yup from "yup";
import {UsersType} from "@/constants";
import {Expertise, Language} from "@/types";
import {toast} from "react-toastify";
import axios from "axios";
import privateApi from "@/service/http/privateCall.axios";
import InnerCreateTransferTeamMember from "./InnerCreateTransferTeamMember";

export const translationSchema = Yup.object({
  lang_id: Yup.number().required("Language is required"),

  firstName: Yup.string()
    .max(255, "First name is too long")
    .required("First name is required"),

  lastName: Yup.string()
    .max(255, "Last name is too long")
    .required("Last name is required"),

  position: Yup.string()
    .max(255, "Position is too long")
    .required("Position is required"),

  expertise: Yup.string()
    .max(500, "Expertise is too long")
    .nullable()
    .notRequired(),
});

export const CreateUserValidationSchema = Yup.object({
  email: Yup.string().email("فرمت ایمیل اشتباه است").required("ایمیل الزامیست"),
  // slug: Yup.string().required("اسلاگ الزامیست"),

  medicalNumber: Yup.string().required("شماره نظام پزشکی الزامیست"),

  phone: Yup.string()
    .matches(/^(?:\+98|0)?9\d{9}$/, "فرمت موبایل اشتباه است")
    .nullable()
    .notRequired(),

  type: Yup.mixed<UsersType>()
    .oneOf(
      [UsersType.DOCTOR, UsersType.TRANSFER_TEAM, UsersType.DEPARTMENT],
      "دسته بندی کاربر اشتباه است"
    )
    .required("دسته بندی کاربر وارد نشده است"),

  imageId: Yup.number().nullable().notRequired(),

  expertiseId: Yup.number()
    .typeError("فرمت تخصص اشتباه است")
    .required("تخصص وارد نشده است"),

  translations: Yup.array()
    .of(translationSchema)
    .min(1, "حداقل یک ترجمه الزامی است")
    .required("Translations are required"),
});
export interface CreateUserTranslation {
  lang_id: number;
  firstName: string;
  lastName: string;
  position: string;
  expertise?: string | null;
}
function buildInitialTranslations(
  languages: Language[]
): CreateUserTranslation[] {
  return languages.map((lang) => ({
    lang_id: lang.id,
    firstName: "",
    lastName: "",
    position: "",
  }));
}
export interface CreateTransferTeamMemberValues {
  translations: CreateUserTranslation[];
  type: UsersType;
  email: string;
  phone: string;
  medicalNumber: string;
  imageId: number | null;
  expertiseId: number | null;
}

export interface CreateTransferTeamMemberProps {
  router: AppRouterInstance;
  languages: Language[];
  expertises: Expertise[];
  initialValues?: Partial<CreateTransferTeamMemberValues>;
}
const CreateTransferTeamMember = withFormik<
  CreateTransferTeamMemberProps,
  CreateTransferTeamMemberValues
>({
  mapPropsToValues: (props) => ({
    translations: buildInitialTranslations(props.languages),
    email: "",
    phone: "",
    medicalNumber: "",
    imageId: null,
    expertiseId: null,
    type: "TRANSFER_TEAM",
    ...props.initialValues, // اگر فیلدهای دیگری بخواهی
  }),
  // validationSchema: CreateUserValidationSchema,
  handleSubmit: async (values, {props}) => {
    
    try {
      const data = await privateApi.post("/user/create", values);
      toast.success(data?.data?.message);
    } catch (error) {
      if (axios.isAxiosError(error)) {
        // اینجا می‌دونیم که خطا از axios است
        toast.error(error.response?.data?.error?.message);
      } else {
        // خطای عمومی
        console.error("Unexpected error:", error);
      }
    }
  },
})(InnerCreateTransferTeamMember);

export default CreateTransferTeamMember;
