"use client";

import React from "react";
import { withFormik, type FormikBag } from "formik";
import InnerCourseForm from "./InnerCourseForm";

export interface CourseItem {
  id: string | number;
  title: string;
  institution: string;
  year: number | string;
  duration: string;
  description?: string;
}

export interface CourseFormValues {
  courses: CourseItem[];
}

/** این بخش را با WizardFormData واقعی پروژه‌ات هماهنگ کن */
export interface WizardFormData {
  courses: CourseItem[];
  // ... other steps
}

export type CourseFormProps = {
  step: number;
  setStep: React.Dispatch<React.SetStateAction<number>>;
  data: WizardFormData;
  update: (patch: Partial<WizardFormData>) => void;
};

export const COURSE_EMPTY_ITEM: CourseItem = {
  id: "",
  title: "",
  institution: "",
  year: "",
  duration: "",
  description: "",
};

export const COURSE_EMPTY_VALUES: CourseFormValues = {
  courses: [COURSE_EMPTY_ITEM],
};

const CourseForm = withFormik<CourseFormProps, CourseFormValues>({
  displayName: "CourseForm",

  enableReinitialize: true,

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

  // validationSchema: CourseValidationSchema,

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

    props.update({ courses: values.courses });
    props.setStep((prev) => prev + 1);

    setSubmitting(false);
  },
})(InnerCourseForm);

export default CourseForm;
