"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";

import { type ScheduleMode } from "@/features/opportunities/components/OpportunityScheduleDates";
import { getDropdownChoicesRequest } from "@/features/auth/services/authApi";
import { checkLicenseRequirement, getOpportunityById } from "@/features/opportunities/services/opportunities";
import { type ErrorFieldSelectors } from "@/features/shared/scrollToFirstError";
import { richTextToPlain } from "@/features/opportunities/forms/richTextToPlain";
import { buildVolunteerValidationSchema } from "./volunteerValidation";
import { buildVolunteerInitialValues } from "./volunteerInitialValues";
import { useVolunteerSubmit } from "./useVolunteerSubmit";
import { useOpportunityMedia } from "@/features/opportunities/forms/useOpportunityMedia";
import { useOpportunitySponsors, type SavedSponsor } from "@/features/opportunities/forms/useOpportunitySponsors";
import { VolunteerFormNavState } from "./volunteerFormTypes";

import { opportunityPrivacyOptions, volunteerCategoryOptions } from "@/data/Constants";
import { NAV_STATE_KEYS, useConsumedNavState } from "@/lib/navigationState";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { useRoleModalStore } from "@/store/roleModalStore";
import {
  choiceFormValue,
  toChoiceOptions,
  toChoiceTagOptions,
} from "@/lib/choices";
import { announcementImages } from "@/features/shared/uploadedImage";
import { includeHeldGeneralTag } from "@/lib/interests";

/**
 * Assembles everything the volunteering form needs, so the component itself is
 * composition and markup.
 *
 * Mirrors `useLearnServeForm`: each concern already has its own hook — media,
 * sponsors, the optional panels, the save — and this is the wiring between
 * them, including which of them needs the loaded record and in what order.
 */
/** Everything the form markup reads, assembled by {@link useVolunteerForm}. */
export type VolunteerFormState = ReturnType<typeof useVolunteerForm>;

export function useVolunteerForm() {
  const selectedLanguage = useLanguageStore((s) => s.language);
  const router = useRouter();
  const user = useAuthStore((s) => s.user);
  const authToken = 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);

  const formOpportunityId = useRoleModalStore((s) => s.opportunityId);
  const roleModalState = useRoleModalStore((s) => s.roleModalState);
  const openRoleModal = useRoleModalStore((s) => s.openRoleModal);
  const closeRoleModal = useRoleModalStore((s) => s.closeRoleModal);
  const setVolunteerOpportunityId = useRoleModalStore(
    (s) => s.setVolunteerOpportunityId
  );

  // Check if license is required for the logged-in user
  const { data: licenseRequirementData } = useQuery({
    queryKey: ["check-license-requirement"],
    queryFn: checkLicenseRequirement,
    enabled: Boolean(authToken),
  });
  const isLicenseRequired =
    licenseRequirementData?.data?.license_required ?? true;

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

  /* 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 [showMismatchModal, setShowMismatchModal] = useState(false);
  const [roleModalRef, setRoleModalRef] = useState<{
    checkParticipantsMismatch: () => boolean;
  } | null>(null);

  const [showOpportunitySection] = useState(true);

  /*
   * The title is asked for once, in Arabic. English is an optional extra the
   * organizer opens only if they want a different wording — when they don't,
   * the submit handler sends the Arabic title in both fields, because the API
   * requires `title_en` and a record with an empty one renders as a blank
   * heading on every English-language screen.
   *
   * `null` means "the organizer hasn't decided", which lets the panel follow
   * the record: open when editing an opportunity that already carries a
   * genuinely different English title, closed otherwise. Once they click
   * either way, their choice wins. Resolved against `opportunityData` further
   * down, where it is in scope.
   */
  const [englishTitleToggle, setEnglishTitleToggle] = useState<boolean | null>(
    null
  );
  /** The description asks the same question, and answers it the same way. */
  const [englishDescriptionToggle, setEnglishDescriptionToggle] = useState<
    boolean | null
  >(null);

  // Force Formik to remount when the language changes

  const {
    data: apiResponse,
    isLoading,
    isError: sourceFailed,
    error: sourceError,
    refetch,
  } = useQuery({
    queryKey: ["opportunity-details", id],
    queryFn: () => getOpportunityById(id as string),
    enabled: Boolean(id),
  });

  const opportunityData = apiResponse?.data;

  /*
   * Only a *different* English title counts as one the organizer wrote. An
   * opportunity created through this form without opening the English panel
   * stores the Arabic title in both columns, so treating any non-empty
   * `title_en` as deliberate would re-open the panel on every edit and show
   * the Arabic text in a field labelled English.
   */
  const hasDistinctEnglishTitle = useMemo(() => {
    const arabic = (opportunityData?.title_ar || "").trim();
    const english = (opportunityData?.title_en || "").trim();
    return english !== "" && english !== arabic;
  }, [opportunityData?.title_ar, opportunityData?.title_en]);
  const showEnglishTitle = englishTitleToggle ?? hasDistinctEnglishTitle;

  const hasDistinctEnglishDescription = useMemo(() => {
    const arabic = (opportunityData?.description_ar || "").trim();
    const english = (opportunityData?.description_en || "").trim();
    return richTextToPlain(english) !== "" && english !== arabic;
  }, [opportunityData?.description_ar, opportunityData?.description_en]);
  const showEnglishDescription =
    englishDescriptionToggle ?? hasDistinctEnglishDescription;

  /*
   * `time_slots` is how the API records a non-consecutive schedule: one row
   * per day the opportunity actually runs. Its presence is therefore the only
   * reliable signal that the organiser chose scattered days — `start_date` and
   * `end_date` look identical either way, since they are the first and last
   * day in both modes.
   */
  const storedScheduleDates: string[] = useMemo(() => {
    const slots = opportunityData?.time_slots;
    if (!Array.isArray(slots) || slots.length === 0) {
      return [
        opportunityData?.start_date,
        opportunityData?.end_date,
        // A single-day opportunity stores the same date twice; dedupe so the
        // range picker doesn't open with a phantom second selection.
      ]
        .filter((day: unknown): day is string => typeof day === "string" && !!day)
        .map((day) => day.slice(0, 10))
        .filter((day, index, all) => all.indexOf(day) === index);
    }
    return [
      ...new Set(
        slots
          /* `date` is `string | null` on the resource (`optional($slot->date)
             ->toDateString()`), not `string | undefined` — so this reads
             through `??` rather than `?.` alone. */
          .map((slot: { date?: string | null }) => slot?.date?.slice(0, 10))
          .filter((day: string | undefined): day is string => Boolean(day))
      ),
    ].sort();
  }, [opportunityData?.time_slots, opportunityData?.start_date, opportunityData?.end_date]);

  const storedScheduleMode: ScheduleMode = Array.isArray(
    opportunityData?.time_slots
  )
    ? opportunityData.time_slots.length > 0
      ? "scattered"
      : "consecutive"
    : "consecutive";

  /*
   * The map search and picker are the second way to answer "where", kept out
   * of sight until asked for so the common case — paste a maps link — is a
   * single field. Same tri-state as the English title: `null` means the
   * organiser hasn't chosen, so an opportunity already pinned on the map opens
   * with the picker showing rather than hiding the answer it already has.
   */
  const [mapPickerToggle, setMapPickerToggle] = useState<boolean | null>(null);
  const hasStoredMapLocation = Boolean(
    opportunityData?.latitude && opportunityData?.longitude
  );
  const showMapPicker = mapPickerToggle ?? hasStoredMapLocation;

  /*
   * Row 1 of the grid has two optional cells — the English title, and the
   * public/private choice that only organizations see. CSS grid flows the next
   * item into any gap they leave, so without this the due date would slide up
   * into row 1 and every row below would be off by one. Widening the title
   * absorbs whatever is missing and keeps the row exactly four columns.
   *
   * Written out as whole class names on purpose: Tailwind scans the source for
   * literals, so an interpolated `lg:col-span-${n}` would never be generated.
   */
  const titleColSpanClass = [
    "lg:col-span-1",
    "lg:col-span-2",
    "lg:col-span-3",
  ][2 - (showEnglishTitle ? 1 : 0) - (showOpportunitySection ? 1 : 0)];

  useEffect(() => {
    if (id) refetch();
  }, [id, refetch]);

  const [selectedCheckBoxes, setSelectedCheckBoxes] = useState<string[]>([]);
  /*
   * The role editor's open flag lives in `roleModalStore` — this was a local
   * copy seeded from it and overwritten by an effect on every change, so the
   * dialog opened one render after `openRoleModal()`. Nothing else ever wrote
   * the copy, so reading the store is the whole of it.
   */
  const open = roleModalState;

  const {
    sponsorOptions,
    sponsorsLoading,
    sponsorsFetching,
    handleMenuScroll,
    setSponsorSearch,
    rememberSponsor,
    seedFromSponsors,
  } = useOpportunitySponsors(authToken);
  /*
   * Likewise a mirror of the store, not state. The effect that maintained it
   * wrote only when the store value was non-null, which looked like
   * "remember the last real id" — but the store's `opportunityId` only ever
   * goes null -> id: its one writer is `useVolunteerSubmit`, already behind an
   * `outcome.opportunityId != null` guard, and `clearRoleModal` (the only
   * thing that would null it again) has no callers. So the guard never
   * suppressed a write and this is the same value, one render earlier.
   */
  const opportunityId: string | null = formOpportunityId;
  const media = useOpportunityMedia();
  const {
    modifiedOpportunityImages,
    modifiedLicenseImage,
    existingImageIds,
    removedImageIds,
    seedFromOpportunity,
    clearRemoved: clearRemovedImages,
  } = media;

  /*
   * Seed the form from the loaded opportunity: the Formik remount key, the
   * image pickers, the accessibility checkboxes and the attached sponsors.
   *
   * One block rather than two effects, and React's adjust-on-change pattern
   * rather than an effect at all. Both effects keyed on the same thing —
   * `opportunityData`'s identity — and both ran after paint, which is why the
   * editor rendered one frame with an empty image picker and no checkboxes
   * ticked over a record that has them. (`seedFromOpportunity` and
   * `seedFromSponsors` set state belonging to sibling hooks of this same
   * component, which is what makes calling them during the render legal.)
   */
  const [seededOpportunity, setSeededOpportunity] =
    useState<typeof opportunityData>(undefined);
  if (opportunityData && opportunityData !== seededOpportunity) {
    setSeededOpportunity(opportunityData);
    // Rebuild `initialValues` from the record.
    setFormKey((prevKey) => prevKey + 1);

    // A repost copies the announcement, while completed-run gallery photos stay behind.
    const oppImages = announcementImages(opportunityData.opportunity_images);

    seedFromOpportunity(oppImages, opportunityData.license_image);

    setSelectedCheckBoxes([
      ...(opportunityData.is_relief ? ["relief"] : []),
      ...(opportunityData.is_urgent ? ["urgent"] : []),
      ...(opportunityData.is_emergency ? ["emergency"] : []),
      ...(opportunityData.is_supports_disabled ? ["disabled"] : []),
    ]);

    // Pre-selected sponsors: the backend returns either nested objects or IDs
    if (opportunityData.opportunity_sponsor_images?.length > 0) {
      seedFromSponsors(
        opportunityData.opportunity_sponsor_images.map(
          (item: { organization?: SavedSponsor }) => item.organization ?? null
        )
      );
    }
  }

  const { data: tagsData, isLoading: tagsLoading } = useQuery({
    queryKey: ["volunteer-opportunity-interest-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("volunteer_opportunity_interest"),
    enabled: !!selectedLanguage,
  });

  const tagOptions: Array<{ id: string; label: string }> =
    // This form keys interests on the stringified id; see CHOICE_ID_COERCION.
    includeHeldGeneralTag(toChoiceTagOptions(tagsData?.data, selectedLanguage, (item) =>
      String(item.id)
    ), id && !isRepublish ? opportunityData?.interests : undefined, selectedLanguage);

  const handleCheckboxChange = (value: string, checked: boolean) => {
    setSelectedCheckBoxes((prev) =>
      checked ? [...prev, value] : prev.filter((item) => item !== value)
    );
  };

  const { data: genderData, isLoading: genderLoading } = useQuery({
    queryKey: ["opportunity-gender-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("opportunity_gender"),
    enabled: !!selectedLanguage,
  });


  const genderOptions =
    /* Stringified to match `VolunteerFormValues.gender`, which is declared a
       string. The pair must move together with the initial value in
       `volunteerInitialValues` or the edit form stops preselecting; the
       payload is `FormData`, so the submitted bytes do not change. */
    toChoiceOptions(genderData?.data, selectedLanguage, choiceFormValue);

  const initialValues = buildVolunteerInitialValues({
    opportunityData,
    hasDistinctEnglishTitle,
    hasDistinctEnglishDescription,
    storedScheduleDates,
    storedScheduleMode,
    tagOptions,
    id,
  });

  const validationSchema = useMemo(
    () =>
      buildVolunteerValidationSchema({
        isLicenseRequired,
        modifiedLicenseImage,
        modifiedOpportunityImages,
        showOpportunitySection,
        id,
      }),
    [
      isLicenseRequired,
      modifiedLicenseImage,
      modifiedOpportunityImages,
      showOpportunitySection,
      id,
    ]
  );

  const {
    handleSubmit,
    handleUpdateConfirm,
    pendingFormData,
    setPendingFormData,
    showUpdateConfirmModal,
    setShowUpdateConfirmModal,
    createOpportunityMutation,
    updateOpportunityMutation,
  } = useVolunteerSubmit({
    id,
    isRepublish,
    existingImageIds,
    removedImageIds,
    clearRemovedImages,
    showOpportunitySection,
    selectedCheckBoxes,
    setSelectedCheckBoxes,
    selectedLanguage,
    opportunityData,
    setVolunteerOpportunityId,
    openRoleModal,
  });

  const submitLoading = createOpportunityMutation.isPending;
  const updateLoading = updateOpportunityMutation.isPending;
  const errorFieldSelectors: ErrorFieldSelectors = {
    description_ar: ".descritpionitm-ar", // rich text editor
    description_en: ".descritpionitm-en",
    // All three live in the one schedule field, which renders no input
    // carrying their names.
    startDate: "#scheduleDates",
    endDate: "#scheduleDates",
    scheduleDates: "#scheduleDates",
    _interests: ".TagsCheckbox",
    opportunity_images: ".uploaddocfiles",
    license_image: "input[type=file]",
  };

  const handleRoleModalClose = () => {
    if (roleModalRef?.checkParticipantsMismatch()) {
      setShowMismatchModal(true);
      return;
    }
    closeRoleModal();
    router.push("/posting-thankyou");
  };

  return {
    formKey,
    // Route / record
    id,
    isRepublish,
    navState,
    opportunityData,
    isLoadingOpportunity: isLoading,
    sourceFailed,
    sourceError,
    refetchSource: refetch,
    selectedLanguage,

    // Formik inputs
    initialValues,
    validationSchema,
    errorFieldSelectors,

    // Grouped layers
    media,

    // Dropdowns
    tagOptions,
    tagsLoading,
    genderOptions,
    genderLoading,
    volunteerCategoryOptions,
    opportunityPrivacyOptions,
    showOpportunitySection,
    titleColSpanClass,

    // Sponsors
    sponsorOptions,
    sponsorsLoading,
    sponsorsFetching,
    handleMenuScroll,
    setSponsorSearch,
    rememberSponsor,

    // Optional panels
    showEnglishTitle,
    showEnglishDescription,
    showMapPicker,
    setEnglishTitleToggle,
    setEnglishDescriptionToggle,
    setMapPickerToggle,

    // The accessibility flags
    selectedCheckBoxes,
    handleCheckboxChange,

    // The role editor
    open,
    closeRoleModal,
    handleRoleModalClose,
    opportunityId,

    // Saving
    handleSubmit,
    handleUpdateConfirm,
    pendingFormData,
    setPendingFormData,
    showUpdateConfirmModal,
    setShowUpdateConfirmModal,
    submitLoading,
    updateLoading,
    showMismatchModal,
    setShowMismatchModal,

    skipNextGeocodeRef,
    setRoleModalRef,
    router,
  };
}
