"use client";

import { useEffect } from "react";
import { fetchAddress, fetchCoordinates } from "@/lib/helpers";
import type { EventFormValues } from "./eventFormTypes";

/**
 * Re-runs validation whenever a touched field gains a value, and keeps the
 * location field in sync with the loaded event.
 */
export default function EventFormEffects({
  values,
  touched,
  validateForm,
  setFieldValue,
  eventData,
  id,
  selectedLanguage,
  skipNextGeocodeRef,
}: {
  values: EventFormValues;
  touched: Record<string, unknown>;
  validateForm: () => Promise<unknown>;
/* `unknown` rather than `any`: these components only *write* field values,
     never read them back, and Formik's own `setFieldValue` accepts anything.
     Anything is assignable to `unknown`, so every caller is unaffected. */
  setFieldValue: (field: string, value: unknown) => void;
  /*
   * Only the three fields this component syncs are declared — a wider type
   * here would claim knowledge of a payload it never reads. `latitude` /
   * `longitude` are the unconverted columns (string on the detail resources,
   * which is why the writes below stringify), and `map_desc` falls back to
   * `location_ar || location_en` server-side.
   */
  eventData?: {
    latitude?: string | number | null;
    longitude?: string | number | null;
    map_desc?: string | null;
  } | null;
  id?: string;
  selectedLanguage: string;
  skipNextGeocodeRef: { current: boolean };
}) {
  useEffect(() => {
    const touchedFields = Object.keys(touched).filter(
      (fieldName) =>
        touched[fieldName] && !!values[fieldName as keyof EventFormValues]
    );
    if (touchedFields.length > 0) {
      validateForm();
    }
  }, [values, touched, validateForm]);

  // When editing with coordinates but no stored location text, reverse-geocode
  // them so the field isn't left empty.
  useEffect(() => {
    const getAddress = async () => {
      if (eventData?.latitude && eventData?.longitude && !eventData?.map_desc) {
        /* `Number(...)`: the columns are `decimal`, which Laravel
           serializes as a string, and `fetchAddress` takes numbers. */
        const result = await fetchAddress(
          Number(eventData.latitude),
          Number(eventData.longitude),
          selectedLanguage
        );
        skipNextGeocodeRef.current = true;
        setFieldValue("location", result); // Sync with Formik state
      }
    };
    getAddress();
    /* The ref is listed because the rule asks and a ref object is
       referentially stable for the component's lifetime — including it costs
       nothing and makes the list complete rather than trimmed. */
  }, [
    eventData?.latitude,
    eventData?.longitude,
    eventData?.map_desc,
    selectedLanguage,
    setFieldValue,
    skipNextGeocodeRef,
  ]);

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

  // 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]);

  return null;
}
