"use client";

import React, { useState, useRef, useEffect } from "react";
import { useField } from "formik";
import { useLanguageStore } from "@/store/languageStore";
import { clampAudienceAge } from "@/features/shared/opportunityFormRules";

/**
 * The age-range field, read from and written to one Formik value holding
 * `[start, end]`.
 *
 * Formik is the only owner. There used to be a local `startAge` / `endAge`
 * pair as well, mirrored *into* by an effect and *out of* by every handler,
 * with two `updatingFrom*Ref` flags to stop the two directions re-triggering
 * each other — that mutual re-triggering is what the flags were for, and it
 * only existed because the value was stored twice.
 *
 * Deriving both numbers from `field.value` removes the effect (and with it a
 * `react-hooks/set-state-in-effect` report), both flags, and a real failure
 * mode: `handleStartInputChange` wrote `updateFormValue(value, endAge)` with
 * `endAge` read from the local copy, so a programmatic change to the *end* age
 * that the mirroring effect had not yet applied was silently written back over
 * with the stale one. `isEndAgeValid` is likewise a pure function of the pair
 * rather than state refreshed by hand at each write.
 */
export function useAgeRange(name: string) {
  const [field, meta, helpers] = useField(name);
  const [isFocusedStart, setIsFocusedStart] = useState(false);
  const [isFocusedEnd, setIsFocusedEnd] = useState(false);

  const [startAge, endAge]: [number | null, number | null] = Array.isArray(
    field.value
  )
    ? [field.value[0] ?? null, field.value[1] ?? null]
    : [null, null];

  /* An end age below the start age is the one invalid combination; either side
     being blank is not an error here (the required rule lives in the schema). */
  const isEndAgeValid =
    endAge === null || startAge === null || startAge <= endAge;
  const selectedLanguage = useLanguageStore((s) => s.language);
  const isRtl = selectedLanguage === "ar";
  const containerRef = useRef<HTMLDivElement | null>(null);

  const hasStartError = meta.touched && meta.error && startAge === null;
  const hasEndError = meta.touched && ((!isEndAgeValid) || (meta.error && endAge === null));

  const updateFormValue = (newStart: number | null, newEnd: number | null) => {
    helpers.setValue([newStart, newEnd]);
  };

  useEffect(() => {
    const style = document.createElement("style");
    style.textContent = `
      input[type=number]::-webkit-inner-spin-button,
      input[type=number]::-webkit-outer-spin-button {
        -webkit-appearance: none;
        margin: 0;
      }
      input[type=number] {
        -moz-appearance: textfield;
      }
      input::placeholder {
        color: #6B7280;
      }
    `;
    document.head.appendChild(style);
    return () => style.remove();
  }, []);

  const handleStartInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(e.target.value, 10);
    updateFormValue(isNaN(value) ? null : value, endAge);
  };

  const handleEndInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(e.target.value, 10);
    updateFormValue(startAge, isNaN(value) ? null : value);
  };

  const handleStartInputBlur = () => {
    setIsFocusedStart(false);
    helpers.setTouched(true);
    if (startAge !== null) {
      updateFormValue(clampAudienceAge(startAge), endAge);
    }
  };

  const handleEndInputBlur = () => {
    setIsFocusedEnd(false);
    helpers.setTouched(true);
    if (endAge !== null) {
      updateFormValue(startAge, clampAudienceAge(endAge));
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (["ArrowUp", "ArrowDown", "e", "E"].includes(e.key)) {
      e.preventDefault();
    }
  };

  const handleStartInputFocus = () => {
    setIsFocusedStart(true);
  };

  const handleEndInputFocus = () => {
    setIsFocusedEnd(true);
  };

  return {
    meta,
    isFocusedStart,
    isFocusedEnd,
    startAge,
    endAge,
    isEndAgeValid,
    isRtl,
    containerRef,
    hasStartError,
    hasEndError,
    handleStartInputChange,
    handleEndInputChange,
    handleStartInputBlur,
    handleEndInputBlur,
    handleStartInputFocus,
    handleEndInputFocus,
    handleKeyDown,
  };
}
