"use client";

import { type FormikErrors, type FormikTouched } from "formik";
import { useTranslation } from "react-i18next";
import TagsCheckbox from "@/components/ui/TagsCheckbox";
import UploadDocument from "@/components/ui/UploadDocument";
import { FormikProps, FormikValues } from "formik";
import { VolunteerFormState } from "./useVolunteerForm";
import VolunteerSponsorFields from "./VolunteerSponsorFields";
import { VolunteerFormValues } from "./volunteerFormTypes";

interface VolunteerAttachmentSectionsProps {
  values: VolunteerFormValues;
  errors: FormikErrors<VolunteerFormValues>;
  touched: FormikTouched<VolunteerFormValues>;
  setFieldValue: FormikProps<FormikValues>["setFieldValue"];
  setFieldTouched: React.ComponentProps<typeof TagsCheckbox>["setFieldTouched"];
  /**
   * The assembled form state. Taken whole because this section forwards six of
   * its fields unchanged — the media bookkeeping, the interest choices and the
   * sponsor picker's paging — and naming them individually here would be a
   * second copy of the hook's return type.
   */
  form: Pick<
    VolunteerFormState,
    | "id"
    | "media"
    | "tagOptions"
    | "tagsLoading"
    | "sponsorOptions"
    | "sponsorsLoading"
    | "sponsorsFetching"
    | "handleMenuScroll"
    | "setSponsorSearch"
    | "rememberSponsor"
  >;
}

/**
 * What is attached to the opportunity: interests, sponsors, and its images.
 */
export default function VolunteerAttachmentSections({
  values,
  errors,
  touched,
  setFieldValue,
  setFieldTouched,
  form,
}: VolunteerAttachmentSectionsProps) {
  const { t } = useTranslation();
  const {
    media,
    tagOptions,
    tagsLoading,
    sponsorOptions,
    sponsorsLoading,
    sponsorsFetching,
    handleMenuScroll,
    setSponsorSearch,
    rememberSponsor,
  } = form;
  const {
    modifiedOpportunityImages,
    modifiedLicenseImage,
    removeFile: handleRemoveExistingFile,
  } = media;
  return (
    <>
    <TagsCheckbox
      name="_interests"
      label={t("COMMON.ENTER_TAGS")}
      setFieldValue={setFieldValue}
      setFieldTouched={setFieldTouched}
      values={values._interests}
      errors={errors._interests as string | undefined}
      touched={touched._interests as boolean | undefined}
      options={tagOptions}
      disabled={tagsLoading}
    />

      <VolunteerSponsorFields
        values={values}
        errors={errors}
        touched={touched}
        setFieldValue={setFieldValue}
        sponsorOptions={sponsorOptions}
        sponsorsLoading={sponsorsLoading}
        sponsorsFetching={sponsorsFetching}
        handleMenuScroll={handleMenuScroll}
        setSponsorSearch={setSponsorSearch}
        rememberSponsor={rememberSponsor}
      />

    <div className="pb-4">
      <UploadDocument
        name="opportunity_images"
        label={t("COMMON.UPLOAD_IMAGE")}
        accept="image/jpeg, image/png"
        multiple
        /* One image per opportunity — the picker, the previews and the
           submitted array are all capped at one. `multiple` stays so the
           value keeps its array shape; `singleFileArray` is the cap. */
        singleFileArray
        setFieldValue={setFieldValue}
        existingFiles={modifiedOpportunityImages.map((file) => ({
          id: file.id,
          image: file.image,
        }))}
        onRemove={(index, isExisting) =>
          handleRemoveExistingFile(
            index,
            isExisting,
            "opportunity_images",
            setFieldValue,
            values
          )
        }
        enableCropping
        cropAspectRatio={1}
        cropShape="rect"
        cropDisplayMode="opportunity"
        cropWidth={600}
        cropHeight={600} // 1:1 — matches the square the cards render
      />
    </div>

    <div>
      <UploadDocument
        name="license_image"
        label={t("COMMON.UPLOAD_LICENSE_IMAGE")}
        multiple={false}
        accept="image/jpeg, image/png"
        setFieldValue={setFieldValue}
        existingFiles={modifiedLicenseImage.map((file) => ({
          id: file.id,
          image: file.image,
        }))}
        onRemove={(index, isExisting) =>
          handleRemoveExistingFile(
            index,
            isExisting,
            "license_image",
            setFieldValue,
            values
          )
        }
        enableCropping={false} // License images are uploaded as-is
        onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
          event.preventDefault();
          const file = event.target.files
            ? event.target.files[0]
            : null;
          setFieldValue("license_image", file);
          // Picking a new file cancels a pending removal
          if (file) {
            setFieldValue("license_image_removed", false);
          }
        }}
      />
      {/* The stored licence reaches its owner again
          (`adminLicenseImageUrl`), so it appears in `existingFiles` on edit. */}
    </div>
    </>
  );
}
