"use client";
import { applyFormApiErrors } from "@/features/shared/formApiErrors";
import { includeHeldGeneralTag } from "@/lib/interests";
import { useAuthoringWriteGuard } from "@/features/shared/useAuthoringWriteGuard";

import React, { useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import {
  FormikHelpers,
  FormikProps,
  FormikValues,
} from "formik";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { invalidateEventReads } from "../eventQueryKeys";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import * as Yup from "yup";
import { shouldLoadNextMenuPageFromEvent } from "@/features/shared/menuPaging";
import { usePageCursor, usePagedItems } from "@/features/shared/pagedList";
import { getDropdownChoicesRequest } from "@/features/auth/services/authApi";
import {
  createEvent,
  getEventById,
  republishEvent,
  updateEvent,
} from "@/features/events/services/eventsApi";
import { getAllOrganizations } from "@/features/shared/services/directory";
import {
  type ErrorFieldSelectors,
} from "@/features/shared/scrollToFirstError";
import { getApiErrorMessages } from "@/lib/api/errors";
import { submitRequiredInterests } from "@/features/shared/submitRequiredInterests";
import { appendEventOptionalPayload } from "../eventOptionalPayload";
import { withWebScheme } from "../eventLifecycle";
import i18n from "@/lib/i18n/config";
import { formatDateToYYYYMMDD } from "@/lib/helpers";
import { NAV_STATE_KEYS, setPostingOutcome, useConsumedNavState } from "@/lib/navigationState";
import { YupFlexibleUrl, YupOptionalUrl, YupRequiredString, YupStringMaxLength } from "@/features/shared/schemas";
import { audienceAgeSchema, authoringCalendarDay, isAuthoringDayNotPast } from "@/features/shared/opportunityFormRules";
import {
  choiceFormValue,
  choiceLabel,
  toChoiceOptions,
  toChoiceTagOptions,
  type ChoiceItem,
} from "@/lib/choices";
import type { DirectoryOrganization } from "@/features/shared/services/directory";
import { useAuthStore } from "@/store/authStore";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { useLanguageStore } from "@/store/languageStore";
import { buildEventInitialValues, offeredInterestIds } from "./eventFormInitialValues";
import { useOptionalFormPanels } from "@/features/opportunities/components/useOptionalFormPanels";
import { appendImageKeepSet } from "@/features/shared/imageKeepSet";
import type {
  EventFormNavState,
  EventFormValues,
} from "./eventFormTypes";

/** Server field names → the form fields that show their errors. */
const API_ERROR_FIELDS = { images: "event_images", cover_image: "card_image", license_image: "card_image", sponsor_organization_ids: "sponsors" };

/** Every new file is JPEG/PNG/WebP and at most 10 MB (PDF p.22). */
const isAllowedImageList = (value: unknown) =>
  !Array.isArray(value) || value.every((file) => !(file instanceof File) || (["image/jpeg", "image/png", "image/webp"].includes(file.type) && file.size <= 10 * 1024 * 1024));

/** Extracted from the component of the same name. */
/**
 * Everything the event form needs apart from its markup: the stashed nav
 * payload, the lookups the selects are built from, the validation schema and
 * the submit/update handlers.
 *
 * It takes no arguments — `autoSetTimeOnClick` is a rendering choice and stays
 * with the fields that honour it.
 */
export function useEventForm() {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const router = useRouter();
  /* A remount counter for Formik, bumped when the saved record arrives so
     `initialValues` are rebuilt from it. The language is handled by the
     key at the call site instead — it needed no counter. */
  const [formKey, setFormKey] = useState(0);

  const [showUpdateConfirmModal, setShowUpdateConfirmModal] = useState(false);
  const [pendingFormData, setPendingFormData] = useState<FormData | null>(null);
  const authToken = useAuthStore((s) => s.user?.auth_token);
  // Set right before a map pick / a data sync fills `location` in
  // programmatically, so the forward-geocode effect skips that one change.
  const skipNextGeocodeRef = useRef(false);

  // Edit / repost target arrives via sessionStorage (React Router `location.state`).
  const navState = useConsumedNavState<EventFormNavState>(
    NAV_STATE_KEYS.eventForm
  );
  const id = navState?.id;
  const isRepublish = navState?.isRepublish;

  /*
   * The sponsor picker searches (client, 2026-10-15 — there can be hundreds of
   * organizations). What is typed goes to `/list-organizations/?name=`, which
   * matches the company name or the nickname; each new search restarts the
   * paging, so the reset signature carries it.
   */
  const [sponsorSearch, setSponsorSearch] = useState("");
  const debouncedSponsorSearch = useDebouncedValue(sponsorSearch.trim());
  const sponsorResetSignature = `all-organizations|${debouncedSponsorSearch}`;
  const { page: currentPage, nextPage } = usePageCursor(sponsorResetSignature);
  /* Names of sponsors picked from an earlier search, so a row keeps showing its
     choice after the search moves on to other results. */
  const [pickedSponsorLabels, setPickedSponsorLabels] = useState<
    Record<string, string>
  >({});
  const rememberSponsor = (option: { value: string; label: string } | null) => {
    if (!option?.value) return;
    setPickedSponsorLabels((previous) =>
      previous[option.value] === option.label
        ? previous
        : { ...previous, [option.value]: option.label }
    );
  };
  const [existingImageIds, setExistingImageIds] = useState<number[]>([]);
  const [modifiedEventImages, setModifiedEventImages] = useState<
    Array<{ id: number; image: string }>
  >([]);
  /* The saved card image (`cover_image`) of the event being edited, until the
     organizer removes or replaces it. */
  const [existingCover, setExistingCover] = useState<string | null>(null);
  /* Set from the first submit until it fails, so a second click — or Enter —
     cannot publish the same event twice while the first request is out. */
  const submittingRef = useRef(false);


  const { data: apiResponse, isLoading, isError: sourceFailed, error: sourceError, refetch: refetchSource } = useQuery({
    queryKey: ["event-details", id],
    queryFn: () => getEventById({ id: id as string }),
    enabled: Boolean(id),
  });
  const eventData = apiResponse?.data;
  const canWrite = useAuthoringWriteGuard({ id, isRepublish, source: eventData });

  /*
   * Same as the opportunity forms: the English title and the map picker are
   * each a second way to answer something the form already asks, so they
   * stay hidden until asked for — and open on their own when editing an event
   * that already carries one.
   */
  const panels = useOptionalFormPanels(eventData);

  const queryClient = useQueryClient();
  const refreshEventReads = () => { void invalidateEventReads(queryClient); };
  const createEventMutation = useMutation({ mutationFn: createEvent, onSuccess: refreshEventReads });
  const republishEventMutation = useMutation({ mutationFn: republishEvent, onSuccess: refreshEventReads });
  const updateEventMutation = useMutation({ mutationFn: updateEvent, onSuccess: refreshEventReads });

  /*
   * The sponsors already attached to the event being edited or reposted — a
   * `map` over the loaded payload, so a `useMemo` rather than state written by
   * an effect.
   *
   * `event_sponsor_images[].organization` is `$image->organization ? [...]
   * : null` in `WebsiteEventResource` — always a nested object or null, never
   * a bare id. The id-only branch this effect used to carry (and the
   * `sponsorIdsToFetch` round trip behind it) could therefore never run; see
   * `EventSponsorImageRecord`.
   *
   * The effect also copied these into `sponsorList`, which was redundant:
   * `sponsorOptions` below already writes `preLoadedSponsors` into the map
   * first and lets them win ties, so the copy could only ever be dropped as a
   * duplicate.
   */
  const preLoadedSponsors = useMemo(
    () =>
      (eventData?.event_sponsor_images ?? [])
        .map((item) => item.organization)
        .filter((org): org is NonNullable<typeof org> => org != null)
        .map((org) => ({ id: String(org.id), full_name: org.full_name || "" })),
    [eventData]
  );

  /*
   * Seed the form from the loaded record.
   *
   * React's adjust-on-change pattern keyed on the payload's identity, which is
   * exactly what the effect depended on — so a refetch still rebuilds the form
   * and re-seeds the image picker, as before. The difference is that the
   * remount and the seed now happen in the same render that first sees the
   * data: the effect let one frame paint an empty form over the loaded record.
   */
  const [seededEvent, setSeededEvent] = useState<typeof eventData>(undefined);
  if (eventData && eventData !== seededEvent) {
    setSeededEvent(eventData);
    // Refresh the form with the loaded data
    setFormKey((prevKey) => prevKey + 1);
    // A repost is a NEW run of the event. Its images were shot during the
    // previous one — Fursa has no after-completion flag on event media, so the
    // poster and the day-of photos sit in the same `event_images` array — and
    // none of them describe the new date. Start the picker empty so the
    // required-images rule forces a fresh upload.
    const eventImages = isRepublish
      ? []
      : (eventData.event_images
          ?.filter(
            (img): img is { id: number; image: string } => img.image != null
          )
          .map((img) => ({ id: img.id, image: img.image })) || []);
    setModifiedEventImages(eventImages);
    setExistingImageIds(eventImages.map((img) => img.id));
    // Same reason: a repost asks for a card image of its own.
    setExistingCover(isRepublish ? null : eventData.cover_image ?? null);
  }

  const { data: eventTypeData, isLoading: eventTypeLoading } = useQuery({
    queryKey: ["event-type-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("event_type"),
    enabled: !!selectedLanguage,
  });
  const { data: participationTypeData, isLoading: participationTypeLoading } =
    useQuery({
      queryKey: ["event-participation-type-choices", selectedLanguage],
      queryFn: () => getDropdownChoicesRequest("event_participation_type"),
      enabled: !!selectedLanguage,
    });
  const { data: genderData, isLoading: genderLoading } = useQuery({
    queryKey: ["opportunity-gender-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("opportunity_gender"),
    enabled: !!selectedLanguage,
  });
  const { data: tagsData, isLoading: tagsLoading } = useQuery({
    queryKey: ["event-interest-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("event_interest"),
    enabled: !!selectedLanguage,
  });

  const tagOptions = includeHeldGeneralTag(toChoiceTagOptions(
    tagsData?.data,
    selectedLanguage,
    choiceFormValue
  ), id && !isRepublish ? eventData?.interests : undefined, selectedLanguage);

  const genderOptions = toChoiceOptions(
    genderData?.data,
    selectedLanguage,
    choiceFormValue
  );

  const {
    data: sponsorsData,
    isLoading: sponsorsLoading,
    isFetching: sponsorsFetching,
  } = useQuery({
    queryKey: ["all-organizations", debouncedSponsorSearch, currentPage],
    queryFn: () =>
      getAllOrganizations({
        name: debouncedSponsorSearch || undefined,
        // The backend's own rule: sponsor pickers leave volunteer teams out.
        for_sponsorship: 1,
        page: currentPage,
        limit: 10,
      }),
    enabled: Boolean(authToken),
  });

  /*
   * Was `scrollHeight - scrollTop === clientHeight` with no last-page guard —
   * the same pair of faults the volunteering form's copy had. See
   * `shouldLoadNextMenuPage`.
   */
  const handleMenuScroll = (e: React.UIEvent<HTMLDivElement>) => {
    if (
      shouldLoadNextMenuPageFromEvent(
        e,
        sponsorsFetching || sponsorSearch.trim() !== debouncedSponsorSearch,
        sponsorsData?.meta?.pagination
      )
    ) {
      nextPage(); // Fetch next page
    }
  };

  // Each scrolled page, accumulated by the shared reducer rather than an
  // effect appending to a `sponsorList` mirror — see `features/shared/pagedList`.
  const { items: pagedSponsors } = usePagedItems<DirectoryOrganization>({
    resetSignature: sponsorResetSignature,
    response: sponsorsData,
    isFetching: sponsorsFetching,
    limit: 10,
    dedupeById: true,
    keepPreviousWhileFetching: true,
  });

  const sponsorList = useMemo(
    () =>
      pagedSponsors.map((organization) => ({
        id: String(organization.id),
        full_name: organization.full_name || "",
      })),
    [pagedSponsors]
  );

  /* A second "resolve these sponsors by id" query used to sit here, fed by the
     id-only branch of the sponsor-extraction effect. It was unreachable twice
     over: that branch cannot run (the payload always nests the organization),
     and `/list-organizations/` has no `ids` filter — it would have ignored the
     parameter and returned the first page of every organization instead. */
  const sponsorOptions = useMemo(() => {
    const sponsorMap = new Map<string, { label: string; value: string }>();

    // Pre-loaded sponsors (from the event being edited) win
    preLoadedSponsors.forEach((sponsor) => {
      sponsorMap.set(sponsor.id, {
        label: sponsor.full_name,
        value: sponsor.id,
      });
    });

    sponsorList.forEach((sponsor) => {
      if (!sponsorMap.has(sponsor.id)) {
        sponsorMap.set(sponsor.id, {
          label: sponsor.full_name,
          value: sponsor.id,
        });
      }
    });

    return Array.from(sponsorMap.values());
  }, [preLoadedSponsors, sponsorList]);

  const eventTypeOptions = useMemo(() => {
    const data = eventTypeData?.data || [];
    const isHub = (item: ChoiceItem) => item.value_en === "Hub";
    // "Hub" is pinned to the top of the list
    const ordered = [...data.filter(isHub), ...data.filter((i) => !isHub(i))];
    return ordered.map((item) => ({
      label: choiceLabel(item, selectedLanguage),
      value: String(item.id),
    }));
  }, [eventTypeData, selectedLanguage]);

  const participationTypeOrder = [
    "Free Event",
    "Free Event (Registration Required)",
    "Paid Event",
  ];

  const participationTypeOptions =
    participationTypeData?.data
      ?.map((item) => ({
        label: choiceLabel(item, selectedLanguage),
        value: choiceFormValue(item),
        value_en: item.value_en,
      }))
      .sort(
        (a, b) =>
          participationTypeOrder.indexOf(a.value_en) -
          participationTypeOrder.indexOf(b.value_en)
      ) || [];

  const initialValues = buildEventInitialValues(
    eventData,
    panels.hasDistinctEnglishTitle
  );

  const notInPast = (value?: string) => {
    // Editing an already-scheduled event in place may legitimately keep its
    // original date even if that date has since passed — only a brand-new
    // event or a republish (a fresh copy, scheduled anew) must be future-dated.
    if (id && !isRepublish) return true;
    return isAuthoringDayNotPast(value);
  };

  // Shared by both the Arabic and English description fields.
  const descriptionSchema = Yup.string()
    .concat(YupRequiredString)
    .test(
      "is-not-empty-html",
      i18n.t("COMMON.REQUIRED.FIELD"),
      function (value) {
        if (!value) return false;
        // Strip markup and entities — an empty <p></p> is not real content
        const textContent = value
          .replace(/<[^>]*>/g, "")
          .replace(/&nbsp;/g, " ")
          .trim();
        return textContent.length > 0;
      }
    )
    .test(
      "description-min-length",
      i18n.t("COMMON.DESCRIPTION_MIN_LENGTH"),
      function (value) {
        if (!value) return true; // emptiness is the required rule's business
        // Count visible text, not raw HTML — tags and entities are not content
        const textContent = value
          .replace(/<[^>]*>/g, "")
          .replace(/&nbsp;/g, " ")
          .trim();
        return textContent.length >= 10;
      }
    );

  const validationSchema = Yup.object({
    title_ar: YupStringMaxLength(100).concat(YupRequiredString),
    /* Optional, as on the opportunity form: an empty one is sent as the
       Arabic title (the API requires `title_en`). Built from scratch because
       `YupStringMaxLength` descends from a required rule. */
    title_en: Yup.string().notRequired(),
    startDate: Yup.string()
      .concat(YupRequiredString)
      .test("start-date-in-future", i18n.t("COMMON.DATE_MUST_BE_FUTURE"), notInPast),
    endDate: Yup.string()
      .concat(YupRequiredString)
      .test("end-date-in-future", i18n.t("COMMON.DATE_MUST_BE_FUTURE"), notInPast)
      .test(
        "end-date-after-start-date",
        i18n.t("COMMON.END_DATE_AFTER_START"),
        function (value) {
          const startDate = this.parent.startDate;
          if (!startDate || !value) return true;
          return authoringCalendarDay(value) >= authoringCalendarDay(startDate);
        }
      ),
    startTime: Yup.string(),
    endTime: Yup.string()
      .test(
        "end-time-after-start-time",
        i18n.t("COMMON.END_TIME_AFTER_START"),
        function (value) {
          const startTime = this.parent.startTime;
          if (!startTime || !value) return true;
          const [startHour, startMinute] = startTime.split(":").map(Number);
          const [endHour, endMinute] = value.split(":").map(Number);
          return endHour * 60 + endMinute > startHour * 60 + startMinute;
        }
      ),
    event_type: Yup.string().concat(YupRequiredString),
    participation_type: Yup.string().concat(YupRequiredString),
    registration_link: Yup.string().when("participation_type_value_en", {
      is: "Free Event",
      then: (schema) => schema.nullable(),
      otherwise: () => YupFlexibleUrl,
    }),

    location_url: YupOptionalUrl.concat(YupRequiredString),
    location: Yup.string().notRequired(),
    description_ar: descriptionSchema,
    age: audienceAgeSchema(false),
    _interests: Yup.array()
      .of(Yup.string())
      .min(1, i18n.t("COMMON.REQUIRED.FIELD"))
      // A repost needs a tag the picker offers; a hidden held «عام» does not count (A13).
      .test("offered-interest", i18n.t("COMMON.REQUIRED.FIELD"), (value) =>
        !isRepublish || offeredInterestIds((value ?? []).filter((id): id is string => Boolean(id)), tagOptions).length > 0),
    /* PDF p.22: the card image is mandatory, the event images optional
       (JPEG/PNG/WebP up to 10 MB each). They used to be one picker whose
       first photo doubled as the cover — which made photos mandatory and left
       no way to replace the card image while keeping the gallery. */
    card_image: Yup.mixed().test("image-size", () => i18n.t("COMMON.REVIEW_IMAGE_LIMIT"), isAllowedImageList).test(
      "has-card-image",
      i18n.t("COMMON.REQUIRED.FIELD"),
      // A repost starts with no media (see `appendImageKeepSet` below).
      (value) => (Array.isArray(value) && value.some((file) => file instanceof File)) || Boolean(id && !isRepublish && existingCover)
    ),
    event_images: Yup.mixed().test("image-size", () => i18n.t("COMMON.REVIEW_IMAGE_LIMIT"), isAllowedImageList),
  });

  // Scroll to the first field with an error
  // Fields whose inputs don't carry a matching name attribute
  const errorFieldSelectors: ErrorFieldSelectors = {
    description_ar: ".descritpionitm-ar", // rich text editor
    _interests: ".TagsCheckbox",
    card_image: ".event-card-image-field",
    event_images: ".event-images-field",
  };

  const fieldErrorTarget = useRef<{ fields: string[]; setFieldError: FormikHelpers<EventFormValues>["setFieldError"] } | null>(null);
  const handleSubmit = async (
    values: EventFormValues,
    { resetForm, setFieldError }: FormikHelpers<EventFormValues>
  ) => {
    if (submittingRef.current || !canWrite()) return;
    submittingRef.current = true;
    fieldErrorTarget.current = { fields: Object.keys(values), setFieldError };
    try {
      const formData = new FormData();

      // The API requires `title_en`; an organizer who wrote only Arabic gets
      // it in both columns, as on the opportunity form.
      const arabicTitle = values.title_ar.trim();
      formData.append("title_ar", arabicTitle);
      formData.append("title_en", arabicTitle);
      // One description, written in Arabic, fills both columns (client,
      // 2026-10-15) — the API requires `description_en` as well.
      formData.append("description_ar", values.description_ar);
      formData.append("description_en", values.description_ar);
      formData.append("start_date", formatDateToYYYYMMDD(values.startDate));
      formData.append("end_date", formatDateToYYYYMMDD(values.endDate));
      formData.append("start_time", values.startTime);
      formData.append("end_time", values.endTime);
      formData.append("latitude", values.latitude);
      formData.append("longitude", values.longitude);
      formData.append("primary_language", selectedLanguage);
      // The form keeps concise UI field names, but the API accepts relation
      // ids under their explicit `*_id` contract.
      formData.append("event_type_id", values.event_type);
      formData.append("participation_type_id", values.participation_type);

      appendEventOptionalPayload(formData, values);

      formData.append(
        "from_age",
        values.age[0] !== null ? values.age[0].toString() : ""
      );
      formData.append(
        "to_age",
        values.age[1] !== null ? values.age[1].toString() : ""
      );
      formData.append("map_desc", values.location);
      // Sent even when empty, so swapping a link for a map pin clears it.
      formData.append("location_url", withWebScheme(values.location_url));
      (id && isRepublish ? offeredInterestIds(values._interests, tagOptions) : values._interests).forEach((interest) => {
        formData.append("interest_ids[]", interest);
      });
      // Republish: the new event starts with no media at all. The key MUST be
      // present — EventController::republish() always hands the source to
      // RepublishMedia::apply(), which clones the WHOLE source gallery when
      // `existing_image_ids` is absent. `existing_image_ids[]` sent zero times
      // has no multipart representation, so the empty keep-set travels as the
      // scalar "none" sentinel that MediaKeepSet::normalizeEmptySignal()
      // rewrites to an empty array before validation.
      if (id && isRepublish) {
        appendImageKeepSet(formData, []);
      } else if (id) {
        /* On update, tell the backend which existing images to keep — always,
           even when none are. The previous guard
           (`eventData?.event_images?.length > 0` plus an implicit empty loop)
           sent no key once the organizer had removed every image, and an
           absent key means "keep everything". See `appendImageKeepSet`. */
        appendImageKeepSet(formData, existingImageIds);
      }

      const newImages = values.event_images.filter(
        (file): file is File => file instanceof File
      );
      newImages.forEach((file) => formData.append("images[]", file));
      /* The card image travels as `cover_image`, stored apart from the gallery;
         an edit that leaves it alone sends nothing and the saved one stays. */
      const cardImage = values.card_image.find((file): file is File => file instanceof File);
      if (cardImage) formData.append("cover_image", cardImage);


      if (id && !isRepublish) {
        // Update existing event — ask for confirmation first
        setPendingFormData(formData);
        setShowUpdateConfirmModal(true);
        // The confirm dialog guards the save itself (its button disables).
        submittingRef.current = false;
        return; // Opening confirmation must not reset the user's unsaved changes.
      } else if (id && isRepublish) {
        const { result: republished, interestsDropped } =
          await submitRequiredInterests(formData, (payload) =>
            republishEventMutation.mutateAsync({ id, formData: payload })
          );
        setPostingOutcome(republished?.data);
        toast.success(t("COMMON.TOAST.CREATE_EVENT_SUCCESS"));
        if (interestsDropped) {
          toast.info(t("COMMON.TOAST.INTEREST_TAGS_NOT_SAVED"));
        }
        router.push("/event-post-thankyou");
      } else {
        // Create a brand-new event
        const { result: created, interestsDropped } =
          await submitRequiredInterests(formData, (payload) =>
            createEventMutation.mutateAsync(payload)
          );
        setPostingOutcome(created?.data);
        toast.success(t("COMMON.TOAST.CREATE_EVENT_SUCCESS"));
        if (interestsDropped) {
          toast.info(t("COMMON.TOAST.INTEREST_TAGS_NOT_SAVED"));
        }
        router.push("/event-post-thankyou");
      }
      resetForm();
    } catch (err) {
      submittingRef.current = false;
      const target = fieldErrorTarget.current;
      if (target) applyFormApiErrors(err, selectedLanguage, target.fields, target.setFieldError, API_ERROR_FIELDS);
      const messages = getApiErrorMessages(err, selectedLanguage);
      const fallback =
        id && !isRepublish
          ? t("COMMON.TOAST.EVENT_FAILED")
          : t("COMMON.TOAST.CREATE_EVENT_FAILED");
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(fallback);
      }
    }
  };

  const handleUpdateConfirm = async () => {
    if (!pendingFormData || !id || !canWrite()) return;
    try {
      const { interestsDropped } = await submitRequiredInterests(
        pendingFormData,
        (payload) => updateEventMutation.mutateAsync({ id, formData: payload })
      );
      toast.success(t("COMMON.TOAST.UPDATE_EVENT_SUCCESS"));
      if (interestsDropped) {
        toast.info(t("COMMON.TOAST.INTEREST_TAGS_NOT_SAVED"));
      }
      router.push(`/event-details/${id}`);
      setPendingFormData(null);
    } catch (err) {
      const target = fieldErrorTarget.current;
      if (target) applyFormApiErrors(err, selectedLanguage, target.fields, target.setFieldError, API_ERROR_FIELDS);
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(t("COMMON.TOAST.UPDATE_EVENT_FAILED"));
      }
      throw err;
    }
  };

  const handleRemoveExistingFile = (
    index: number,
    isExistingFile: boolean,
    fieldName: string,
    setFieldValue: FormikProps<EventFormValues>["setFieldValue"],
    values: FormikValues
  ) => {
    if (fieldName === "card_image") {
      if (isExistingFile) setExistingCover(null);
      else setFieldValue("card_image", []);
      return;
    }
    if (fieldName !== "event_images") return;

    if (isExistingFile) {
      const removedImageId = modifiedEventImages[index]?.id;
      setModifiedEventImages((prev) => prev.filter((_, i) => i !== index));
      setExistingImageIds((prev) =>
        prev.filter((imageId) => imageId !== removedImageId)
      );
      // Keep only the newly uploaded files in the Formik value (no URLs)
      const currentFiles = Array.isArray(values[fieldName])
        ? values[fieldName]
        : [];
      setFieldValue(
        fieldName,
        currentFiles.filter((file: unknown) => file instanceof File)
      );
    } else {
      const currentFiles = Array.isArray(values[fieldName])
        ? [...values[fieldName]]
        : [];
      currentFiles.splice(index, 1);
      setFieldValue(fieldName, currentFiles);
    }
  };

  return {
    t,
    sponsorsLoading,
    sponsorsFetching,
    selectedLanguage,
    router,
    showUpdateConfirmModal,
    setShowUpdateConfirmModal,
    pendingFormData,
    setPendingFormData,
    authToken,
    skipNextGeocodeRef,
    showEnglishTitle: panels.showEnglishTitle,
    setEnglishTitleToggle: panels.setEnglishTitleToggle,
    showMapPicker: panels.showMapPicker,
    setMapPickerToggle: panels.setMapPickerToggle,
    navState,
    id,
    isRepublish,
    formKey,
    setFormKey,
    sponsorList,
    preLoadedSponsors,
    currentPage,
    existingImageIds,
    setExistingImageIds,
    modifiedEventImages,
    setModifiedEventImages,
    existingCover,
    isSubmitting:
      createEventMutation.isPending ||
      republishEventMutation.isPending ||
      updateEventMutation.isPending,
    apiResponse,
    isLoading,
    sourceFailed,
    sourceError,
    refetchSource,
    eventData,
    createEventMutation,
    republishEventMutation,
    updateEventMutation,
    eventTypeData,
    eventTypeLoading,
    participationTypeData,
    participationTypeLoading,
    genderData,
    genderLoading,
    tagsData,
    tagsLoading,
    tagOptions,
    genderOptions,
    handleMenuScroll,
    sponsorOptions,
    setSponsorSearch,
    rememberSponsor,
    /** The name to show for a chosen sponsor the current results lack. */
    sponsorLabelFor: (id: string) =>
      pickedSponsorLabels[id] ??
      preLoadedSponsors.find((sponsor) => sponsor.id === id)?.full_name ??
      null,
    eventTypeOptions,
    participationTypeOrder,
    participationTypeOptions,
    initialValues,
    notInPast,
    descriptionSchema,
    validationSchema,
    errorFieldSelectors,
    handleSubmit,
    handleUpdateConfirm,
    handleRemoveExistingFile,
  };
}
