"use client";

import { withFormik, type FormikBag } from "formik";
import type { ReferralFormProps, ReferralFormValues } from "./types";
import { REFERRAL_EMPTY_VALUES } from "./constant";
import { ReferralValidationSchema } from "./validation";
import InnerReferralForm from "./InnerReferralForm";

const ReferralForm = withFormik<ReferralFormProps, ReferralFormValues>({
  displayName: "ReferralForm",

  enableReinitialize: true,

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

  validationSchema: ReferralValidationSchema,

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

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

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

export default ReferralForm;
