"use client";

import { withFormik, type FormikBag } from "formik";
import type {
  WorkExperienceFormProps,
  WorkExperienceFormValues,
} from "./types";
import { WORK_EXPERIENCE_EMPTY_VALUES } from "./constant";
import { WorkExperienceValidationSchema } from "./validation";
import InnerWorkExperienceForm from "./InnerWorkExperienceForm";

const WorkExperienceForm = withFormik<
  WorkExperienceFormProps,
  WorkExperienceFormValues
>({
  displayName: "WorkExperienceForm",

  enableReinitialize: true,

  mapPropsToValues: (props) => {
    return {
      workExperiences:
        props.data?.workExperiences?.length > 0
          ? props.data.workExperiences
          : WORK_EXPERIENCE_EMPTY_VALUES.workExperiences,
    };
  },

  validationSchema: WorkExperienceValidationSchema,

  handleSubmit: async (
    values,
    bag: FormikBag<WorkExperienceFormProps, WorkExperienceFormValues>,
  ) => {
    const { props, setSubmitting } = bag;

    props.update({
      workExperiences: values.workExperiences,
    });

    props.setStep((prev) => prev + 1);
    setSubmitting(false);
  },
})(InnerWorkExperienceForm);

export default WorkExperienceForm;
