"use client";

import { useRef, useState } from "react";
import { useField, useFormikContext } from "formik";
import { DateObject } from "react-multi-date-picker";
import { format, parseISO } from "date-fns";
import { useLanguageStore } from "@/store/languageStore";
import {
  formatDateInput,
  isCalendarDayDisabled,
  parseTypedDate,
  serializeSelectedDate,
} from "./dateInputValue";
import { displayDateValue } from "./dateInputValue";

interface FormValues {
  [key: string]: string;
}

/**
 * `DateField`'s state: the displayed text, the effective minimum date, and
 * keeping both in step with Formik.
 *
 * The typed-entry rules are shared with `BirthDateField` and tested in
 * `dateInputValue.ts`.
 */
export function useDateField({
  name,
  minDate,
  enforceStartDate,
}: {
  name: string;
  minDate?: Date;
  enforceStartDate?: Date;
}) {
  const { setFieldValue, values, validateField } =
    useFormikContext<FormValues>();
  const [field, meta, helpers] = useField(name);
  const [isFocused, setIsFocused] = useState(false);
  const [displayValue, setDisplayValue] = useState("");
  const datePickerRef = useRef<{
    openCalendar: () => void;
    closeCalendar: () => void;
  }>(null);
  const selectedLanguage = useLanguageStore((s) => s.language);
  const isRtl = selectedLanguage === "ar";

  const fieldValue = values[name];

  /*
   * Purely derived from the stored value, so computed rather than stored.
   *
   * It was `useState` + an effect, which meant the first render used the
   * initial value and the correct minimum only arrived on the following
   * commit. Nothing ever sets it other than that effect, so there is no local
   * editing to preserve and the state could go entirely.
   *
   * A saved date in the past stays selectable — otherwise editing an old
   * record would reject its own current value — while a new pick is floored
   * at today.
   */
  /*
   * Computed inline rather than memoised.
   *
   * It is two `Date` constructions and a comparison, and callers pass
   * `minDate={new Date()}` inline — so the object identity changes every
   * render and any dependency array would either recompute anyway or lie.
   * Plain computation is both cheaper to read and impossible to get wrong.
   *
   * `minDate` is honoured as the floor. The effect this replaces recomputed
   * from today and discarded the prop after the first commit, which made
   * `minDate` a no-op — harmless today, since every caller passes today, but a
   * trap for the first one that passes anything else. Cloned, because
   * `setHours` mutates.
   *
   * A saved date in the past stays selectable, so editing an old record does
   * not reject its own current value.
   */
  const effectiveMinDate = (() => {
    const floor = minDate ? new Date(minDate) : new Date();
    floor.setHours(0, 0, 0, 0);
    if (!fieldValue) return floor;
    const existingDate = parseISO(fieldValue);
    existingDate.setHours(0, 0, 0, 0);
    return existingDate < floor ? existingDate : floor;
  })();

  // Format date as user types (DD-MM-YYYY)
  // Handle manual input
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formattedInput = formatDateInput(e.target.value);
    setDisplayValue(formattedInput);

    // A complete, real date — `parseTypedDate` rejects rollovers like 31-02.
    const typed = parseTypedDate(formattedInput);
    if (typed) {
      setFieldValue(name, serializeSelectedDate(name, typed));
      helpers.setTouched(true);
      setTimeout(() => validateField(name), 0);
    }
  };

  /*
   * Follow the stored value during render, not from an effect — the box is
   * edited locally as the user types, so it cannot simply be derived, but it
   * must re-sync when the calendar or a form reset changes the stored value.
   * The effect version painted the previous string for one frame first.
   */
  const [prevFieldValue, setPrevFieldValue] = useState(fieldValue);
  if (fieldValue !== prevFieldValue) {
    setPrevFieldValue(fieldValue);
    setDisplayValue(displayDateValue(fieldValue));
  }

  const handleFocus = () => setIsFocused(true);

  const handleBlur = () => {
    setIsFocused(false);
    helpers.setTouched(true); // Mark as touched on blur
    setTimeout(() => validateField(name), 0);
  };

  const handleIconClick = () => datePickerRef.current?.openCalendar();

  const handleChange = (
    date: Date | DateObject | DateObject[] | null,
    manualInput?: boolean
  ): void => {
    if (date === null) {
      setFieldValue(name, "");
      setDisplayValue("");
      helpers.setTouched(true);
      validateField(name); // Trigger validation after clearing
      return;
    }

    const singleDate = Array.isArray(date) ? date[0] : date;

    if (singleDate) {
      const parsedDate =
        singleDate instanceof Date ? singleDate : singleDate.toDate();
      setFieldValue(
        name,
        name === "dob"
          ? format(parsedDate, "yyyy-MM-dd")
          : parsedDate.toISOString()
      );
      setDisplayValue(format(parsedDate, "dd-MM-yyyy"));
      helpers.setTouched(true); // Mark as touched after value change
      setTimeout(() => validateField(name), 0);
    }

    if (!manualInput) {
      datePickerRef.current?.closeCalendar();
      handleBlur();
    }
  };

  // Helper for disabling days
  // The rule lives in `dateInputValue.ts` (tested); it honours `minDate` and
  // never mutates the caller's `enforceStartDate`.
  const mapDays = ({ date }: { date: DateObject }) =>
    isCalendarDayDisabled(date.toDate(), {
      enforceStartDate,
      minDate,
      selected: fieldValue ? parseISO(fieldValue) : null,
    })
      ? { disabled: true }
      : {};

  // The picker wants a Date; Formik holds the serialized string. Parsed here
  // so every conversion for this field lives in one file.
  const pickerValue = fieldValue ? parseISO(fieldValue) : null;

  return {
    pickerValue,
    setFieldValue,
    values,
    validateField,
    field,
    meta,
    helpers,
    isFocused,
    setIsFocused,
    effectiveMinDate,
    displayValue,
    setDisplayValue,
    datePickerRef,
    selectedLanguage,
    isRtl,
    fieldValue,
    handleInputChange,
    handleFocus,
    handleBlur,
    handleIconClick,
    handleChange,
    mapDays,
  };
}
