"use client";

import type { FormikProps } from "formik";
import {
  scrollToFirstError,
  type ErrorFieldSelectors,
} from "@/features/shared/scrollToFirstError";
import type { LearnServeFormValues } from "./learnServeFormTypes";
import type { PendingSubmission } from "./useLearnServeSubmit";

type Bag = FormikProps<LearnServeFormValues>;

/**
 * What the Publish / Save button does before anything is sent.
 *
 * Formik only marks a field touched once it has been visited, so a field the
 * organizer never scrolled to would fail validation silently. Everything is
 * marked touched first, then validated; a failure scrolls to the offending
 * field rather than leaving the button looking unresponsive.
 *
 * Editing then stops for a confirmation, because saving sends the opportunity
 * back for re-approval.
 */
export function buildSubmitClickHandler({
  bag,
  errorFieldSelectors,
  id,
  isRepublish,
  setPendingFormData,
  setShowUpdateConfirmModal,
}: {
  bag: Bag;
  errorFieldSelectors: ErrorFieldSelectors;
  id?: string;
  isRepublish?: boolean;
  setPendingFormData: (pending: PendingSubmission | null) => void;
  setShowUpdateConfirmModal: (open: boolean) => void;
}) {
  const { values, setTouched, validateForm, submitForm } = bag;

  const handleFormSubmit = async () => {
    const touchedFields = Object.keys(values).reduce(
      (acc, field) => {
        acc[field] = true;
        return acc;
      },
      {} as Record<string, boolean>
    );
    setTouched(touchedFields);

    const validationErrors = await validateForm();
    if (Object.keys(validationErrors).length > 0) {
      scrollToFirstError(validationErrors, errorFieldSelectors);
      return;
    }

    // Updating an existing opportunity asks for confirmation first
    if (id && !isRepublish) {
      // Keep the real setters so a confirmed API failure reaches the visible fields.
      setPendingFormData({ values, helpers: bag });
      setShowUpdateConfirmModal(true);
      return;
    }

    submitForm();
  };

  return handleFormSubmit;
}
