"use client";

import { Formik, Form } from "formik";
import { buildSubmitClickHandler } from "./useLearnServeFormSubmitClick";
import LearnServeScheduleModals from "./LearnServeScheduleModals";
import LearnServeFieldSections from "./LearnServeFieldSections";
import LearnServeAttachmentSections from "./LearnServeAttachmentSections";
import { learnServeValueFlags } from "./learnServeValueFlags";
import type { LearnServeFormState } from "./useLearnServeForm";

/**
 * The form itself: `<Formik>`, its render prop, and the two field sections.
 *
 * Takes the whole assembled state as one prop rather than forty. Everything in
 * it comes from `useLearnServeForm`, so listing the pieces individually would
 * be a second, drifting copy of that hook's return type — and every one of them
 * is needed somewhere in this tree.
 */
export default function LearnServeFormContent({
  form,
  autoSetTimeOnClick,
}: {
  form: LearnServeFormState;
  /** Clicking a time field opens the picker rather than typing into it. */
  autoSetTimeOnClick: boolean;
}) {
  const {
    id,
    isRepublish,
    opportunityData,
    selectedLanguage,
    formKey,
    initialValues,
    validationSchema,
    errorFieldSelectors,
    platformFeePercent,
    options,
    media,
    sponsorOptions,
    sponsorsLoading,
    sponsorsFetching,
    handleMenuScroll,
    setSponsorSearch,
    rememberSponsor,
    showEnglishTitle,
    showEnglishDescription,
    showMapPicker,
    setEnglishTitleToggle,
    setEnglishDescriptionToggle,
    setMapPickerToggle,
    opportunityId,
    open,
    setOpen,
    opentime,
    showConfirmModal,
    disableSaveButton,
    setInitialTimeSlots,
    handleConfirmAction,
    handleTimeSlotModalClose,
    setOpentime,
    setShowConfirmModal,
    handleSubmit,
    submitLoading,
    updateLoading,
    setPendingFormData,
    setShowUpdateConfirmModal,
    skipNextGeocodeRef,
  } = form;
  const { developmentPaid } = form.publishPermissions;

  return (
    <Formik
      // The tag choices decide which ids the saved interests preselect,
      // so remount once they land as well.
      /* See `EventForm`: the language is in the key directly; `formKey` stays
         for the saved-record remount, and the tag count was already here. */
      key={`${selectedLanguage}-${formKey}-${options.tagOptions.length}`}
      initialValues={{ ...initialValues, paymentTermsLocked: !isRepublish && initialValues.paymentTermsLocked }}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
      validateOnMount={false}
      validateOnBlur
      validateOnChange
    >
      {(bag) => {
        const {
        setFieldValue,
        values,
        setFieldTouched,
        touched,
        isSubmitting,
        errors,
        validateForm,
        } = bag;
        // Mark everything touched, validate, then submit or scroll to the error
        const handleFormSubmit = buildSubmitClickHandler({
          bag,
          errorFieldSelectors,
          id,
          isRepublish,
          setPendingFormData,
          setShowUpdateConfirmModal,
        });
        const { isInternshipOrCourse, isOnline, canBePaid, isPaid } =
          learnServeValueFlags(values, options, developmentPaid);

        return (
          <>
            <LearnServeScheduleModals
              values={values}
              open={open}
              onCloseTimeSlotModal={handleTimeSlotModalClose}
              setOpen={setOpen}
              showConfirmModal={showConfirmModal}
              onConfirmAction={handleConfirmAction}
              onDismissConfirm={() => setShowConfirmModal(false)}
              opentime={opentime}
              hasOpportunityId={Boolean(opportunityId)}
              onCloseCreateTiming={() => setOpentime(false)}
              disableSaveButton={disableSaveButton}
            />

            <Form className="selectfiled">
              <LearnServeFieldSections
                isPaid={isPaid}
                values={values}
                touched={touched as Record<string, unknown>}
                setFieldValue={setFieldValue}
                setFieldTouched={setFieldTouched}
                validateForm={validateForm}
                options={options}
                isOnline={isOnline}
                isInternshipOrCourse={isInternshipOrCourse}
                canBePaid={canBePaid}
                showEnglishTitle={showEnglishTitle}
                onAddEnglishTitle={() => setEnglishTitleToggle(true)}
                onRemoveEnglishTitle={() => {
                  // Clear as well as close, so a value typed and then
                  // dismissed can't be submitted invisibly.
                  setFieldValue("title_en", "");
                  setFieldTouched("title_en", false);
                  setEnglishTitleToggle(false);
                }}
                showEnglishDescription={showEnglishDescription}
                onAddEnglishDescription={() =>
                  setEnglishDescriptionToggle(true)
                }
                onRemoveEnglishDescription={() => {
                  // Clear as well as close, so an editor left holding
                  // `<p></p>` (or real text) can't be submitted from
                  // behind a collapsed panel.
                  setFieldValue("description_en", "");
                  setFieldTouched("description_en", false);
                  setEnglishDescriptionToggle(false);
                }}
                showMapPicker={showMapPicker}
                onUseMapPicker={() => setMapPickerToggle(true)}
                onUseLocationLink={() => setMapPickerToggle(false)}
                platformFeePercent={platformFeePercent}
                autoSetTimeOnClick={autoSetTimeOnClick}
                selectedLanguage={selectedLanguage}
                id={id}
                opportunityData={opportunityData}
                timeSlotModalOpen={open}
                setInitialTimeSlots={setInitialTimeSlots}
                skipNextGeocodeRef={skipNextGeocodeRef}
              />

              <LearnServeAttachmentSections
                values={values}
                errors={errors}
                touched={touched}
                setFieldValue={setFieldValue}
                setFieldTouched={setFieldTouched}
                media={media}
                tagOptions={options.tagOptions}
                tagsLoading={options.tagsLoading}
                sponsorOptions={sponsorOptions}
                sponsorsLoading={sponsorsLoading}
                sponsorsFetching={sponsorsFetching}
                handleMenuScroll={handleMenuScroll}
                setSponsorSearch={setSponsorSearch}
                rememberSponsor={rememberSponsor}
                onSubmitClick={handleFormSubmit}
                isSaving={submitLoading || updateLoading || isSubmitting}
                id={id}
                isRepublish={isRepublish}
              />
            </Form>
          </>
        );
      }}
    </Formik>
  );
}
