"use client";

import { withFormik, type FormikBag } from "formik";
import type { RelationFormProps, RelationFormValues } from "./types";
import { RELATION_INITIAL_VALUES } from "./constant";
import { RelationValidationSchema } from "./validation";
import InnerRelationForm from "./InnerRelationForm";

const RelationForm = withFormik<RelationFormProps, RelationFormValues>({
  displayName: "RelationForm",

  enableReinitialize: true,

  mapPropsToValues: (props) => {
    // اگر داده‌ای از قبل بود استفاده کن، در غیر این صورت مقدار اولیه (۲تایی)
    if (props.data?.relations?.length === 2) {
      return { relations: props.data.relations };
    }
    return RELATION_INITIAL_VALUES;
  },

  validationSchema: RelationValidationSchema,

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

    props.update({ relations: values.relations });
    props.setStep((prev) => prev + 1);
    setSubmitting(false);
  },
})(InnerRelationForm);

export default RelationForm;
