"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useConsumedNavState, NAV_STATE_KEYS } from "@/lib/navigationState";
import { getPublishPermissions } from "@/lib/publishPermissions";
import { checkLicenseRequirement } from "@/features/opportunities/services/opportunities";
import { getLearnServeOpportunityById } from "@/features/opportunities/services/learnServe";
import { getTimeSlots } from "@/features/opportunities/services/registrations";
import { getOwnPlatformFee } from "@/features/profile/services/platformFee";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { ErrorFieldSelectors } from "@/features/shared/scrollToFirstError";
import { buildLearnServeInitialValues } from "./learnServeInitialValues";
import { buildLearnServeValidationSchema } from "./learnServeValidation";
import { useLearnServeOptions } from "./useLearnServeOptions";
import { useOpportunityMedia } from "@/features/opportunities/forms/useOpportunityMedia";
import { useOpportunitySponsors, type SavedSponsor } from "@/features/opportunities/forms/useOpportunitySponsors";
import { useOptionalFormPanels } from "./useOptionalFormPanels";
import { useInProgressOpportunity } from "./useInProgressOpportunity";
import { useTimeSlotModals } from "./useTimeSlotModals";
import { useLearnServeSubmit } from "./useLearnServeSubmit";
import { LearnServeFormNavState, LearnServeFormValues } from "./learnServeFormTypes";
import { FormikHelpers } from "formik";
import { parsePlatformFee } from "@/features/opportunities/platformFee";
import { announcementImages } from "@/features/shared/uploadedImage";

/**
 * Assembles everything the development-opportunity form needs, so the component
 * itself is composition and markup.
 *
 * Each concern already has its own hook — options, media, sponsors, the
 * optional panels, the in-progress record, the timings dialogs, the save. This
 * is the wiring between them: which of them needs the loaded record, which
 * feeds the validation schema, and in what order they have to run.
 */
/** Everything the form's markup reads, assembled by {@link useLearnServeForm}. */
export type LearnServeFormState = ReturnType<typeof useLearnServeForm>;

export function useLearnServeForm(editOpportunityId?: string) {
  const selectedLanguage = useLanguageStore((s) => s.language);
  const user = useAuthStore((s) => s.user);
  const authToken = user?.auth_token;
  /*
   * The client's matrix (`lib/publishPermissions.ts`): internships are for
   * organizations only and always free; a volunteer team's development
   * opportunities are free only. It decides which types are offered and
   * whether the paid option appears at all.
   */
  // 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);


  // 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<LearnServeFormNavState>(
    NAV_STATE_KEYS.learnServeForm
  );
  // The route param wins; nav state is the fallback for repost and for any
  // caller still pushing the bare form path.
  const id = editOpportunityId ?? navState?.id;
  const isRepublish = !editOpportunityId && navState?.isRepublish === true;
  const publishPermissions = getPublishPermissions(user, id && !isRepublish ? "edit" : isRepublish ? "repost" : "create");

  /* 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 [confirmModalOpen, setConfirmModalOpen] = useState(false);
  const [showUpdateConfirmModal, setShowUpdateConfirmModal] = useState(false);
  const [pendingFormData, setPendingFormData] = useState<{
    values: LearnServeFormValues;
    helpers: FormikHelpers<LearnServeFormValues>;
  } | null>(null);


  const {
    sponsorOptions,
    sponsorsLoading,
    sponsorsFetching,
    handleMenuScroll,
    setSponsorSearch,
    rememberSponsor,
    seedFromSponsors,
  } = useOpportunitySponsors(authToken);

  const media = useOpportunityMedia();
  const {
    modifiedOpportunityImages,
    modifiedLicenseImage,
    existingImageIds,
    removedImageIds,
    seedFromOpportunity,
    reset: resetMedia,
    clearRemoved: clearRemovedImages,
  } = media;


  // Force Formik to remount when the language changes


  const { data: apiResponse, isLoading: isLoadingOpportunity, isError: sourceFailed, error: sourceError, refetch: refetchSource } = useQuery({
    queryKey: ["learn-serve-opportunity-form", id],
    queryFn: () => getLearnServeOpportunityById(id as string),
    enabled: Boolean(id),
  });

  const opportunityData = apiResponse?.data;

  // `GET /account/` carries no rate; the publisher's own profile does (organization or trainer).
  const { data: feeRate } = useQuery({
    queryKey: ["account-platform-fee", user?.id, user?.user_type],
    queryFn: () => getOwnPlatformFee(user?.user_type),
    enabled: Boolean(authToken),
    retry: false,
  });

  const {
    hasDistinctEnglishTitle,
    hasDistinctEnglishDescription,
    showEnglishTitle,
    showEnglishDescription,
    showMapPicker,
    setEnglishTitleToggle,
    setEnglishDescriptionToggle,
    setMapPickerToggle,
  } = useOptionalFormPanels(opportunityData);

  /*
   * Rebuild `initialValues` once the saved record arrives — React's
   * adjust-on-change pattern, keyed on the payload's identity, which is what
   * the effect depended on. Doing it during the render that first sees the
   * data means the form is never painted empty over a loaded record.
   */
  const [seededOpportunity, setSeededOpportunity] =
    useState<typeof opportunityData>(undefined);
  if (opportunityData && opportunityData !== seededOpportunity) {
    setSeededOpportunity(opportunityData);
    setFormKey((prevKey) => prevKey + 1);
  }


  const {
    opportunityId,
    setOpportunityId,
    opportunityDetails,
    setOpportunityDetails,
  } = useInProgressOpportunity({ navState, id, isRepublish, opportunityData });

  const { refetch: refetchTimeSlots } = useQuery({
    queryKey: ["opportunity-time-slots", opportunityId],
    queryFn: () => getTimeSlots(opportunityId as number),
    enabled: Boolean(opportunityId),
  });

  const {
    open,
    setOpen,
    opentime,
    setOpentime,
    showConfirmModal,
    setShowConfirmModal,
    disableSaveButton,
    setInitialTimeSlots,
    handleCloseTimeModal,
    handleConfirmAction,
    handleTimeSlotModalClose,
  } = useTimeSlotModals({
    opportunityId,
    refetchTimeSlots,
    savedSlots: opportunityData?.timeslots_display,
  });

  // Mirror the loaded opportunity into local image / sponsor state
  useEffect(() => {
    if (!opportunityData) {
      resetMedia();
      return;
    }

    // Copy announcement media only; the previous run's gallery is never a new cover.
    const oppImages = announcementImages(opportunityData.opportunity_images);

    seedFromOpportunity(oppImages, opportunityData.license_image);

    // 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
        )
      );
    }
  }, [opportunityData, isRepublish, resetMedia, seedFromOpportunity, seedFromSponsors]);

  const options = useLearnServeOptions(selectedLanguage, publishPermissions, id && !isRepublish ? opportunityData?.interests : undefined);
  // Only the ids the validation schema compares against; the lists themselves
  // are forwarded to the field components as one `options` prop.
  const {
    tagOptions,
    internshipTypeId,
    courseTypeId,
    inPersonFormatId,
    onlineFormatId,
  } = options;


  const initialValues = buildLearnServeInitialValues({
    opportunityData,
    selectedLanguage,
    hasDistinctEnglishTitle,
    hasDistinctEnglishDescription,
    tagOptions,
  });

  const platformFeePercent =
    parsePlatformFee(feeRate) ??
    parsePlatformFee(opportunityData?.platform_fee_percentage);

  const validationSchema = useMemo(
    () =>
      buildLearnServeValidationSchema({
        inPersonFormatId,
        onlineFormatId,
        internshipTypeId,
        courseTypeId,
        existingEnglishTitle: opportunityData?.title_en,
        developmentPaid: publishPermissions.developmentPaid,
        isLicenseRequired,
        id,
        modifiedLicenseImage,
        modifiedOpportunityImages,
      }),
    [
      inPersonFormatId,
      onlineFormatId,
      internshipTypeId,
      courseTypeId,
      opportunityData?.title_en,
      publishPermissions.developmentPaid,
      isLicenseRequired,
      id,
      modifiedLicenseImage,
      modifiedOpportunityImages,
    ]
  );

  const {
    createOpportunityMutation,
    updateOpportunityMutation,
    handleSubmit,
    handleConfirmDeleteTimeSlots,
    handleCancelDeleteTimeSlots,
    handleUpdateConfirm,
  } = useLearnServeSubmit({
    id,
    isRepublish,
    publishPermissions,
    internshipTypeId,
    courseTypeId,
    onlineFormatId,
    existingImageIds,
    removedImageIds,
    clearRemovedImages,
    opportunityData,
    setOpportunityId,
    setOpportunityDetails,
    pendingFormData,
    setPendingFormData,
    setConfirmModalOpen,
    setShowUpdateConfirmModal,
    selectedLanguage,
  });

  const submitLoading = createOpportunityMutation.isPending;
  const updateLoading = updateOpportunityMutation.isPending;
  // 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
    description_en: ".descritpionitm-en",
    _interests: ".TagsCheckbox",
    opportunity_images: ".uploaddocfiles",
    age: "[name='age[0]']",
    sponsors: ".sponsors",
    license_image: "input[type=file]",
  };

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

    // Formik inputs
    initialValues,
    validationSchema,
    errorFieldSelectors,
    platformFeePercent,

    // Grouped layers
    options,
    media,

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

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

    // The in-progress record and its timings dialogs
    opportunityId,
    opportunityDetails,
    refetchTimeSlots,
    open,
    setOpen,
    opentime,
    showConfirmModal,
    disableSaveButton,
    setInitialTimeSlots,
    handleCloseTimeModal,
    handleConfirmAction,
    handleTimeSlotModalClose,
    setOpentime,
    setShowConfirmModal,

    // Saving
    handleSubmit,
    handleConfirmDeleteTimeSlots,
    handleCancelDeleteTimeSlots,
    handleUpdateConfirm,
    submitLoading,
    updateLoading,
    confirmModalOpen,
    showUpdateConfirmModal,
    pendingFormData,
    setPendingFormData,
    setShowUpdateConfirmModal,

    skipNextGeocodeRef,
  };
}
