"use client";

import type { LearnServeTimeSlotRecord } from "@/features/opportunities/opportunityRecord";
import { learnServeSlotsToDrafts } from "@/features/opportunities/learnServeSlotDraft";
import { useEffect } from "react";
import { fetchAddress, fetchCoordinates } from "@/lib/helpers";
import { useTimeSlotsStore } from "@/store/timeSlotsStore";
import type { TimeSlot } from "@/features/shared";
import type { LearnServeFormValues } from "./learnServeFormTypes";
import { useLatest } from "@/hooks/useLatest";

/** Choice labels the form branches on, per language. */
/**
 * Side effects that need Formik's bag. Kept out of the render prop so the hooks
 * aren't declared inside a callback.
 */
export default function LearnServeFormEffects({
  values,
  touched,
  validateForm,
  setFieldValue,
  opportunityData,
  id,
  selectedLanguage,
  timeSlotModalOpen,
  setInitialTimeSlots,
  skipNextGeocodeRef,
}: {
  values: LearnServeFormValues;
  touched: Record<string, unknown>;
  validateForm: () => Promise<unknown>;
  setFieldValue: (field: string, value: unknown) => void;
  /**
   * The record being edited. Only the four fields this component actually
   * syncs are declared — a wider type here would claim knowledge of a payload
   * this file never reads.
   */
  opportunityData?: {
    latitude?: number | string | null;
    longitude?: number | string | null;
    map_desc?: string | null;
    timeslots_display?: LearnServeTimeSlotRecord[] | null;
  } | null;
  id?: string;
  selectedLanguage: string;
  timeSlotModalOpen: boolean;
  setInitialTimeSlots: (slots: TimeSlot[]) => void;
  skipNextGeocodeRef: { current: boolean };
}) {
  const timeSlots = useTimeSlotsStore((s) => s.timeSlots);
  const setTimeSlots = useTimeSlotsStore((s) => s.setTimeSlots);
  const clearTimeSlots = useTimeSlotsStore((s) => s.clearTimeSlots);

  // Sync location once opportunityData arrives (it loads after mount).
  // `map_desc` is a single language-agnostic field — no per-language lookup.
  useEffect(() => {
    if (!opportunityData || !id) return;
    if (opportunityData.map_desc) {
      skipNextGeocodeRef.current = true;
      setFieldValue("location", opportunityData.map_desc);
    }
    if (opportunityData.latitude) {
      setFieldValue("latitude", opportunityData.latitude.toString());
    }
    if (opportunityData.longitude) {
      setFieldValue("longitude", opportunityData.longitude.toString());
    }
  }, [opportunityData, setFieldValue, id, skipNextGeocodeRef]);

  /* The organizer's current location text, for the post-await read below. */
  const latestLocation = useLatest(values.location);

  // When editing with coordinates but no stored location text, reverse-geocode
  // them so the field isn't left empty.
  useEffect(() => {
    const getAddress = async () => {
      if (
        opportunityData?.latitude &&
        opportunityData?.longitude &&
        !opportunityData?.map_desc
      ) {
        const result = await fetchAddress(
          Number(opportunityData.latitude),
          Number(opportunityData.longitude),
          selectedLanguage
        );
        /*
         * Don't overwrite anything the organizer has typed — read through
         * `latestLocation`, not the closure.
         *
         * Two reasons, and the first is a correctness one: this line runs
         * *after* an `await`, so the closure's `values.location` is the value
         * from before the geocode round trip and could be several keystrokes
         * stale. The second is the dependency list — listing `values.location`
         * would restart the effect (and re-issue the geocode request) on every
         * keystroke, which is what its `exhaustive-deps` suppression was
         * hiding. See `useLatest`.
         */
        if (!latestLocation.current) {
          skipNextGeocodeRef.current = true;
          setFieldValue("location", result);
        }
      }
    };

    if (id) void getAddress();
  }, [
    id,
    opportunityData?.latitude,
    opportunityData?.longitude,
    opportunityData?.map_desc,
    selectedLanguage,
    setFieldValue,
    skipNextGeocodeRef,
    latestLocation,
  ]);

  // Forward-geocode the typed address into coordinates so the map follows
  // what the user types, debounced so it doesn't fire on every keystroke.
  // Skipped once whenever `location` was just filled in programmatically
  // (map pick or the syncs above) — those already carry exact coordinates.
  useEffect(() => {
    if (skipNextGeocodeRef.current) {
      skipNextGeocodeRef.current = false;
      return;
    }
    const address = values.location?.trim();
    if (!address || address.length < 3) return;

    const timer = setTimeout(async () => {
      const result = await fetchCoordinates(address, selectedLanguage);
      if (result) {
        setFieldValue("latitude", result.lat.toString());
        setFieldValue("longitude", result.lng.toString());
      }
    }, 800);

    return () => clearTimeout(timer);
    /* `setFieldValue` and `skipNextGeocodeRef` are listed rather than suppressed.
       Formik 2.4.9 wraps `setFieldValue` in `useEventCallback`
       (`node_modules/formik/dist/formik.cjs.development.js:713`), so it is
       referentially stable, and a `useRef` object never changes identity — so
       listing both cannot make this effect re-run. Verified by removing the
       directive: those two were the only dependencies the rule reported. */
  }, [values.location, selectedLanguage, setFieldValue, skipNextGeocodeRef]);

  // Re-validate when a touched field gains a value
  useEffect(() => {
    const touchedFields = Object.keys(touched).filter(
      (fieldName) =>
        touched[fieldName] && !!values[fieldName as keyof LearnServeFormValues]
    );
    if (touchedFields.length > 0) {
      validateForm();
    }
  }, [values, touched, validateForm]);

  // Seed the shared draft store from the saved schedule when editing
  useEffect(() => {
    const saved = opportunityData?.timeslots_display;
    if (!saved) return;
    /* Converted, not passed through: the API row has no `isSaved` and can
       carry a null date. See `learnServeSlotsToDrafts`. */
    const drafts = learnServeSlotsToDrafts(saved);
    if (drafts.length > 0) {
      setTimeSlots(drafts);
    } else {
      clearTimeSlots();
    }
  }, [opportunityData?.timeslots_display, setTimeSlots, clearTimeSlots]);

  /*
   * Snapshot the slots when the modal opens, so edits can be detected on close.
   *
   * `latestTimeSlots`, not the closure: the snapshot must be the list as it
   * stands *at the moment the modal opens*, and listing `timeSlots` would
   * re-snapshot on every edit — overwriting the baseline with the edited list
   * and making every close look unchanged. That is what the
   * `exhaustive-deps` suppression here was for; the ref says "latest" and
   * lets the list be complete. See `useLatest`.
   */
  const latestTimeSlots = useLatest(timeSlots);
  useEffect(() => {
    if (timeSlotModalOpen) {
      setInitialTimeSlots([...latestTimeSlots.current]);
    }
  }, [timeSlotModalOpen, setInitialTimeSlots, latestTimeSlots]);

  return null;
}
