"use client";

import { useField } from "formik";
import { useEffect, useRef, useState, useMemo } from "react";
import { useLanguageStore } from "@/store/languageStore";
import {
  convertTo24Hour,
  formatTimeForDisplay,
  normalizeScrollTime,
  parseTimeString,
  typedTimeDraft,
} from "./timeValue";
import { toWesternDigits } from "@/lib/digits";

export interface TimePickerProps {
  name: string;
  label?: string;
  className?: string;
  disabled?: boolean;
  autoSetTime?: boolean;
}

/**
 * The time picker's behaviour: the 12-hour parts, typed entry, the looping
 * scroll wheels and the click-outside close.
 *
 * The conversions themselves are pure and live in `timeValue.ts`.
 */
export function useTimePicker({
  name,
  autoSetTime = false,
  disabled = false,
}: {
  name: string;
  autoSetTime?: boolean;
  /* Two of the handlers below refuse to open the dropdown when disabled. */
  disabled?: boolean;
}) {
  const [field, meta, helpers] = useField(name);
  /* Hoisted out of `helpers` so the click-outside effect can depend on it —
     see the note on that effect's dependency list. */
  const { setTouched } = helpers;
  const [isFocused, setIsFocused] = useState(false);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [isManualInput, setIsManualInput] = useState(false);

  /*
   * Formik owns the time; the 12-hour parts are read back out of it.
   *
   * There used to be a `selectedHour` / `selectedMinute` / `selectedPeriod`
   * triple in local state, written by every handler *and* re-synced from
   * `field.value` by an effect — the `react-hooks/set-state-in-effect` report
   * this removes. The triple was redundant rather than merely duplicated:
   * every one of the three places that set it also called
   * `helpers.setValue()` with the equivalent 24-hour string, so parsing that
   * string back is the same answer by construction, one render sooner, and
   * with no way for the two copies to disagree while the effect had not run
   * yet.
   *
   * The defaults are the ones the old `useState` carried, so a field with no
   * value still opens the wheels on 12:00 PM.
   */
  const parsed = field.value ? parseTimeString(field.value) : null;
  const selectedHour = parsed?.hour ?? 12;
  const selectedMinute = parsed?.minute ?? 0;
  const selectedPeriod: "AM" | "PM" = parsed?.period ?? "PM";

  /** The committed value, shown whenever the reader is not mid-entry. */
  const displayValue = parsed
    ? formatTimeForDisplay(parsed.hour, parsed.minute)
    : "";

  /*
   * What is in the box *while typing* does stay local: it has to hold
   * incomplete input ("1", "13:") that is not a time yet and so cannot live in
   * the form value. Outside manual entry the box shows the committed value, so
   * an external change to the field is reflected without an effect.
   */
  const [typedValue, setInputValue] = useState("");
  const inputValue = isManualInput ? typedValue : displayValue;

  const selectedLanguage = useLanguageStore((s) => s.language);
  const isRtl = selectedLanguage === "ar";
  const dropdownRef = useRef<HTMLDivElement>(null);
  const visibleInputRef = useRef<HTMLInputElement>(null);

  // Repeat the base lists so the columns scroll "infinitely"
  /*
   * `useMemo` on all four, which is what lets the scroll effect below declare
   * its dependencies instead of suppressing them.
   *
   * Rebuilt on every render, `baseHours` / `baseMinutes` could not be listed —
   * the effect would have re-run (and re-scrolled the wheels) on every render.
   * That was the whole reason for its `exhaustive-deps` directive.
   *
   * It is also 1,200 array entries per render that nothing was changing:
   * `hours` and `minutes` repeat the base lists fifty times so the columns
   * scroll "infinitely", and the contents never depend on anything.
   */
  const baseHours = useMemo(
    () => Array.from({ length: 12 }, (_, i) => i + 1),
    []
  );
  const hours = useMemo(
    () => Array.from({ length: 50 }, () => baseHours).flat(),
    [baseHours]
  );
  const baseMinutes = useMemo(
    () => Array.from({ length: 60 }, (_, i) => i),
    []
  );
  const minutes = useMemo(
    () => Array.from({ length: 50 }, () => baseMinutes).flat(),
    [baseMinutes]
  );

  // Refs for scrolling to selected items
  const hoursScrollRef = useRef<HTMLDivElement>(null);
  const minutesScrollRef = useRef<HTMLDivElement>(null);
  const periodScrollRef = useRef<HTMLDivElement>(null);

  // State to track if we're programmatically scrolling
  const [isScrolling, setIsScrolling] = useState(false);

  // Track whether focus came from a click on this component
  const [wasExplicitlyFocused, setWasExplicitlyFocused] = useState(false);

  // Handle time selection from dropdown
  const handleTimeChange = (
    hour: number,
    minute: number,
    period: "AM" | "PM"
  ) => {
    const { hour: normalizedHour, minute: normalizedMinute } =
      normalizeScrollTime(hour, minute);

    /* `setInputValue` keeps the typing draft aligned with the committed value,
       so switching to manual entry starts from what is on screen. */
    setInputValue(formatTimeForDisplay(normalizedHour, normalizedMinute));

    helpers.setValue(
      convertTo24Hour(normalizedHour, normalizedMinute, period)
    );
  };

  // Handle dropdown toggle - only used for clock icon click
  const handleDropdownToggle = (e: React.MouseEvent) => {
    e.stopPropagation(); // Prevent the event from bubbling up
    if (disabled) return;

    setIsManualInput(false);
    setWasExplicitlyFocused(true);

    if (autoSetTime && !field.value) {
      handleTimeChange(12, 0, "PM");
    }

    setIsDropdownOpen(!isDropdownOpen);
    setIsFocused(true);
  };

  // Enable manual input mode when clicking the input area
  const handleInputAreaClick = (e?: React.MouseEvent) => {
    e?.stopPropagation();
    if (disabled) return;

    setIsDropdownOpen(false);
    // Start typing from the stored value, in the 24-hour form typing uses.
    if (!isManualInput) setInputValue(typedTimeDraft(field.value));
    setIsManualInput(true);
    setIsFocused(true);
    setWasExplicitlyFocused(true);

    if (autoSetTime && !field.value) {
      handleTimeChange(12, 0, "PM");
    }

    visibleInputRef.current?.focus();
  };

  /** Push a hh:mm pair into the form value when it is a valid time. */
  const commitTypedTime = (hours: string, mins: string) => {
    if (!hours || !mins) return;
    const hour = parseInt(hours, 10);
    const minute = parseInt(mins, 10);

    if (
      isNaN(hour) ||
      isNaN(minute) ||
      hour < 0 ||
      hour > 23 ||
      minute < 0 ||
      minute > 59
    ) {
      return;
    }

    helpers.setValue(
      `${hour.toString().padStart(2, "0")}:${minute
        .toString()
        .padStart(2, "0")}`
    );
  };

  // Handle manual input, preserving exactly what is typed
  const handleManualInputChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    // Arabic-Indic digits from an Arabic keyboard are converted, not rejected.
    const value = toWesternDigits(e.target.value);

    // Allow digits and colon only
    if (!/^[\d:]*$/.test(value)) return;

    if (value.includes(":")) {
      const parts = value.split(":");
      if (parts.length === 2) {
        const hours = parts[0].slice(0, 2);
        const mins = parts[1].slice(0, 2);
        // Preserve exactly what the user typed — don't reformat mid-entry
        setInputValue(`${hours}:${mins}`);
        commitTypedTime(hours, mins);
      }
      return;
    }

    const digitsOnly = value.replace(/\D/g, "");
    if (digitsOnly.length <= 2) {
      setInputValue(digitsOnly);
    } else {
      const hours = digitsOnly.slice(0, 2);
      const mins = digitsOnly.slice(2, 4);
      setInputValue(`${hours}:${mins}`);
      commitTypedTime(hours, mins);
    }
  };

  // Handle blur of manual input
  const handleManualInputBlur = (e: React.FocusEvent) => {
    // Ignore blurs caused by clicking elsewhere inside this component
    if (dropdownRef.current?.contains(e.relatedTarget as Node)) return;

    setIsFocused(false);
    setIsManualInput(false);
    helpers.setTouched(true);
    setWasExplicitlyFocused(false);

    // Only pad once the input is complete
    if (inputValue.includes(":")) {
      const [hours, mins] = inputValue.split(":");
      if (hours?.length === 2 && mins?.length === 2) {
        const hour = parseInt(hours, 10);
        const minute = parseInt(mins, 10);
        if (
          !isNaN(hour) &&
          !isNaN(minute) &&
          hour >= 0 &&
          hour <= 23 &&
          minute >= 0 &&
          minute <= 59
        ) {
          setInputValue(
            `${hour.toString().padStart(2, "0")}:${minute
              .toString()
              .padStart(2, "0")}`
          );
        }
      }
    }
  };

  // Scroll to selected item in dropdown
  useEffect(() => {
    if (!isDropdownOpen) return;

    const timer = setTimeout(() => {
      // Land in the middle repetition so scrolling has room both ways
      if (hoursScrollRef.current) {
        const index = 25 * baseHours.length + (selectedHour - 1);
        const el = hoursScrollRef.current.children[index] as HTMLElement;
        if (el) {
          hoursScrollRef.current.scrollTop =
            el.offsetTop -
            hoursScrollRef.current.clientHeight / 2 +
            el.clientHeight / 2;
        }
      }

      if (minutesScrollRef.current) {
        const baseMinuteIndex = baseMinutes.indexOf(selectedMinute);
        if (baseMinuteIndex !== -1) {
          const index = 25 * baseMinutes.length + baseMinuteIndex;
          const el = minutesScrollRef.current.children[index] as HTMLElement;
          if (el) {
            minutesScrollRef.current.scrollTop =
              el.offsetTop -
              minutesScrollRef.current.clientHeight / 2 +
              el.clientHeight / 2;
          }
        }
      }

      if (periodScrollRef.current) {
        const periodIndex = ["AM", "PM"].indexOf(selectedPeriod);
        if (periodIndex !== -1) {
          const el = periodScrollRef.current.children[
            periodIndex
          ] as HTMLElement;
          if (el) {
            periodScrollRef.current.scrollTop =
              el.offsetTop -
              periodScrollRef.current.clientHeight / 2 +
              el.clientHeight / 2;
          }
        }
      }
    }, 50);

    return () => clearTimeout(timer);
    /* `baseHours` and `baseMinutes` are listed rather than suppressed — both
       are memoized above, so they are referentially stable and cannot make
       this re-run. The rule reported exactly these two. */
  }, [
    isDropdownOpen,
    selectedHour,
    selectedMinute,
    selectedPeriod,
    baseHours,
    baseMinutes,
  ]);

  /** Jump back to the middle repetition when a column nears either end. */
  const handleLoopingScroll = (
    e: React.UIEvent<HTMLDivElement>,
    totalItems: number,
    baseLength: number
  ) => {
    if (isScrolling) return;

    const scrollContainer = e.currentTarget;
    const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
    const itemHeight = scrollHeight / totalItems;
    const singleLoopHeight = itemHeight * baseLength;

    if (scrollTop < singleLoopHeight) {
      setIsScrolling(true);
      scrollContainer.scrollTop = scrollTop + singleLoopHeight * 20;
      setTimeout(() => setIsScrolling(false), 50);
    } else if (scrollTop > scrollHeight - clientHeight - singleLoopHeight) {
      setIsScrolling(true);
      scrollContainer.scrollTop = scrollTop - singleLoopHeight * 20;
      setTimeout(() => setIsScrolling(false), 50);
    }
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsDropdownOpen(false);

        if (wasExplicitlyFocused) {
          setIsFocused(false);
          setIsManualInput(false);
          setTouched(true);
          setWasExplicitlyFocused(false);
        }
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
    /* `setTouched`, not the whole `helpers` object — which is what the rule
       reported. Formik 2.4.9 wraps each helper in `useEventCallback`
       (`node_modules/formik/dist/formik.cjs.development.js:713`), so the
       function is referentially stable while the object around it is not:
       listing the object would have re-subscribed this listener on every
       render. Verified by removing the directive and reading what the rule
       asked for. */
  }, [wasExplicitlyFocused, setTouched]);


  return {
    field,
    meta,
    helpers,
    isFocused,
    setIsFocused,
    isDropdownOpen,
    setIsDropdownOpen,
    isManualInput,
    setIsManualInput,
    selectedHour,
    selectedMinute,
    selectedPeriod,
    inputValue,
    setInputValue,
    selectedLanguage,
    isRtl,
    dropdownRef,
    visibleInputRef,
    baseHours,
    hours,
    baseMinutes,
    minutes,
    hoursScrollRef,
    minutesScrollRef,
    periodScrollRef,
    isScrolling,
    setIsScrolling,
    wasExplicitlyFocused,
    setWasExplicitlyFocused,
    handleTimeChange,
    handleDropdownToggle,
    handleInputAreaClick,
    commitTypedTime,
    handleManualInputChange,
    handleManualInputBlur,
    handleLoopingScroll,
    parsed,
    displayValue,
  };
}
