"use client";

import { Formik, Form } from "formik";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/Button";
import { buildVolunteerSubmitClick } from "./volunteerSubmitClick";
import VolunteerFormEffects from "./VolunteerFormEffects";
import VolunteerFieldGrid from "./VolunteerFieldGrid";
import VolunteerContextSections from "./VolunteerContextSections";
import VolunteerDescriptionFields from "./VolunteerDescriptionFields";
import VolunteerAttachmentSections from "./VolunteerAttachmentSections";
import { VolunteerFormState } from "./useVolunteerForm";

/**
 * The form itself: `<Formik>`, its render prop, and the field sections.
 *
 * Takes the whole assembled state as one prop rather than forty. Everything in
 * it comes from `useVolunteerForm`, so listing the pieces individually would be
 * a second, drifting copy of that hook's return type.
 */
export default function VolunteerFormContent({
  form,
  autoSetTimeOnClick,
}: {
  form: VolunteerFormState;
  /** Clicking a time field opens the picker rather than typing into it. */
  autoSetTimeOnClick: boolean;
}) {
  const { t } = useTranslation();
  const {
    id,
    isRepublish,
    opportunityData,
    selectedLanguage,
    formKey,
    initialValues,
    validationSchema,
    errorFieldSelectors,
    genderOptions,
    genderLoading,
    volunteerCategoryOptions,
    opportunityPrivacyOptions,
    showOpportunitySection,
    titleColSpanClass,
    showEnglishTitle,
    showEnglishDescription,
    showMapPicker,
    setEnglishTitleToggle,
    setEnglishDescriptionToggle,
    setMapPickerToggle,
    selectedCheckBoxes,
    handleCheckboxChange,
    handleSubmit,
    submitLoading,
    updateLoading,
    skipNextGeocodeRef,
  } = form;

  return (
    <Formik
      /* See `EventForm`: the language is in the key directly, `formKey` stays
         for the saved-record remount. */
      key={`${selectedLanguage}-${formKey}`}
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
      enableReinitialize
      validateOnMount={false}
      validateOnBlur
      validateOnChange
    >
      {({
        setFieldValue,
        values,
        setFieldTouched,
        errors,
        touched,
        isSubmitting,
        submitForm,
        validateForm,
        setTouched,
      }) => {
        const handleFormSubmit = buildVolunteerSubmitClick(
          { values, setTouched, validateForm, submitForm },
          errorFieldSelectors
        );

        return (
          <Form className="selectfiled">
            <VolunteerFormEffects
              values={values}
              touched={touched as Record<string, unknown>}
              validateForm={validateForm}
              setFieldValue={setFieldValue}
              opportunityData={opportunityData}
              id={id}
              selectedLanguage={selectedLanguage}
              skipNextGeocodeRef={skipNextGeocodeRef}
            />
            {/*
              * One grid for the whole header block rather than a stack
              * of independent flex rows. Three flex rows each divided
              * the width by however many fields they happened to hold,
              * so a 3-field row and a 5-field row produced completely
              * different column edges and the longer labels were
              * squeezed until they truncated. A fixed four-column grid
              * gives every field the same width on every row.
              *
              * The two pairs that read as one answer — age from/to and
              * time from/to — each occupy a single column, which is what
              * makes all three rows come out to exactly four columns.
              */}
          <VolunteerFieldGrid
            values={values}
            setFieldValue={setFieldValue}
            setFieldTouched={setFieldTouched}
            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);
            }}
            titleColSpanClass={titleColSpanClass}
            showOpportunitySection={showOpportunitySection}
            volunteerCategoryOptions={volunteerCategoryOptions}
            opportunityPrivacyOptions={opportunityPrivacyOptions}
            genderOptions={genderOptions}
            genderLoading={genderLoading}
            autoSetTimeOnClick={autoSetTimeOnClick}
          />

          <VolunteerContextSections
            values={values}
            setFieldValue={setFieldValue}
            setFieldTouched={setFieldTouched}
            selectedLanguage={selectedLanguage}
            showMapPicker={showMapPicker}
            onUseMapPicker={() => setMapPickerToggle(true)}
            onUseLocationLink={() => setMapPickerToggle(false)}
            skipNextGeocodeRef={skipNextGeocodeRef}
            selectedCheckBoxes={selectedCheckBoxes}
            handleCheckboxChange={handleCheckboxChange}
          />
          <VolunteerDescriptionFields
            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);
            }}
          />
          <VolunteerAttachmentSections
            values={values}
            errors={errors}
            touched={touched}
            setFieldValue={setFieldValue}
            setFieldTouched={setFieldTouched}
            form={form}
          />
            <div className="publish-form-actions flex justify-center gap-3 pt-6">
              <Button
                type="button"
                variant="primary"
                size="medium"
                disabled={submitLoading || updateLoading || isSubmitting}
                onClick={handleFormSubmit}
              >
                {id && !isRepublish
                  ? opportunityData?.approval_status === "rejected"
                    ? t("COMMON.EDIT_AND_RESUBMIT")
                    : t("COMMON.SAVE")
                  : isRepublish
                    ? t("COMMON.REPOST")
                    : t("COMMON.PUBLISH")}
              </Button>
            </div>
          </Form>
        );
      }}
    </Formik>
  );
}
