"use client";

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

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

/**
 * `BirthDateField`'s state: the text the custom input shows, the calendar's
 * open/close handle, and keeping both in step with Formik.
 *
 * The typed-entry rules live in `birthDateValue.ts` and are tested there.
 */
export function useBirthDateField(name: string) {
  const { setFieldValue, values, validateField } =
    useFormikContext<FormValues>();
  const [field, meta, helpers] = useField(name);
  const [isFocused, setIsFocused] = useState(false);
  // Seeded from the stored value: a form that mounts with a saved date (the
  // profile editor) must show it, and the re-sync below only fires on a change.
  const [displayValue, setDisplayValue] = useState<string>(() =>
    displayDateValue(values[name])
  );
  const datePickerRef = useRef<{
    openCalendar: () => void;
    closeCalendar: () => void;
  }>(null);
  const selectedLanguage = useLanguageStore((s) => s.language);
  const isRtl = selectedLanguage === "ar";

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const next = birthDateInputValue(e.target.value);
    setDisplayValue(next.display);
    // This edit already owns the displayed draft; do not reformat it on rerender.
    setPrevStored(next.value);
    setFieldValue(name, next.value);
    helpers.setTouched(true, false);
  };

  /*
   * Follow the stored value during render, not from an effect.
   *
   * The box is edited locally while the user types (`formatDateInput` above),
   * so the displayed string cannot simply be derived — but it must re-sync
   * whenever the stored value changes underneath, e.g. when the calendar is
   * used or the form is reset. The effect version of this painted the old
   * string for one frame on every such change; React's documented
   * adjust-during-render pattern re-renders before the paint instead.
   */
  const storedValue = values[name];
  const [prevStored, setPrevStored] = useState(storedValue);
  if (storedValue !== prevStored) {
    setPrevStored(storedValue);
    setDisplayValue(displayDateValue(storedValue));
  }

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

  const handleBlur = () => {
    setIsFocused(false);
    helpers.setTouched(true);
  };

  const handleIconClick = (): void => {
    datePickerRef.current?.openCalendar();
  };

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

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

    if (singleDate) {
      const parsedDate =
        singleDate instanceof Date ? singleDate : singleDate.toDate();
      const formattedDate =
        name === "dob"
          ? format(parsedDate, "yyyy-MM-dd")
          : parsedDate.toISOString();
      setFieldValue(name, formattedDate);
      helpers.setTouched(true);
      setTimeout(() => {
        validateField(name);
      }, 0);
    }

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

  // The picker wants a Date; Formik holds the serialized string. Parsed here
  // rather than in the view so every conversion for this field is in one file.
  const storedDateIsComplete = name !== "dob" || /^\d{4}-\d{2}-\d{2}$/.test(values[name] ?? "");
  const parsedPickerValue = values[name] && storedDateIsComplete ? parseISO(values[name]) : null;
  const pickerValue = parsedPickerValue && !isNaN(parsedPickerValue.getTime()) ? parsedPickerValue : "";

  return {
    field,
    pickerValue,
    meta,
    isFocused,
    displayValue,
    datePickerRef,
    isRtl,
    handleInputChange,
    handleFocus,
    handleBlur,
    handleIconClick,
    handleChange,
  };
}
