"use client";

import { forwardRef } from "react";
import DatePicker, { DateObject } from "react-multi-date-picker";

import { cn } from "@/lib/helpers";

import DateFieldAdornments from "./DateFieldAdornments";
import { useDateField } from "./useDateField";

interface DatePickerProps {
  name: string;
  label?: string;
  minDate?: Date;
  maxDate?: Date;
  rmdpClassname?: string;
  disabled?: boolean;
  showDueDate?: boolean;
  enforceStartDate?: Date;
  /**
   * Show a button that empties the field. Opt-in, because on a required date
   * there is nothing useful to clear *to* — it only makes sense where an empty
   * value is a real answer, and an edit screen otherwise has no way to undo a
   * date once one has been picked.
   */
  clearable?: boolean;
}

const DatePickerInput = forwardRef<HTMLInputElement, DatePickerProps>(
  (
    {
      name,
      label,
      minDate,
      maxDate,
      rmdpClassname = "",
      disabled = false,
      showDueDate = false,
      enforceStartDate,
      clearable = false,
      ...props
    },
    ref,
  ) => {
    const {
      pickerValue,
      setFieldValue,
      validateField,
      field,
      meta,
      helpers,
      isFocused,
      effectiveMinDate,
      displayValue,
      setDisplayValue,
      datePickerRef,
      isRtl,
      handleInputChange,
      handleFocus,
      handleBlur,
      handleIconClick,
      handleChange,
      mapDays,
    } = useDateField({ name, minDate, enforceStartDate });

    const inputClassName = cn(
      "w-full p-3 border rounded-2xl h-[48px] bg-[#29246D]/[0.03] text-primary-5 focus:outline-none",
      isRtl ? "text-right pr-3" : "text-left pl-[19px]",
      meta.touched && meta.error ? "border-red-500" : "border-[#29246D1A]/10",
      isFocused || displayValue ? "pt-6" : "pt-3",
      rmdpClassname,
    );

    return (
      <div
        className={cn("relative w-full mb-4", rmdpClassname)}
        dir={isRtl ? "rtl" : "ltr"}
      >
        {/* Floating Label */}
        {label && (
          <label
            htmlFor={name}
            className={`absolute transition-all duration-200 text-primary-5
              ${isRtl ? "right-[9px]" : "left-[15px]"}
              ${
                isFocused || displayValue
                  ? "text-[10px] top-[5px] bg-white px-1 text-primary-5/70"
                  : "lg:text-base md:text-sm text-sm top-3"
              }
            `}
            onClick={handleIconClick}
          >
            {label}
          </label>
        )}

        <div
          className={`relative flex items-center ${
            isRtl ? "flex-row-reverse" : ""
          }`}
        >
          {/* Date Picker Input */}
          <DatePicker
            {...field}
            {...props}
            value={pickerValue}
            format="DD-MM-YYYY"
            onChange={(date: Date | DateObject | DateObject[] | null) =>
              handleChange(date, true)
            }
            onOpen={handleFocus}
            onClose={handleBlur}
            minDate={effectiveMinDate}
            maxDate={maxDate}
            calendarPosition="bottom-center"
            disabled={disabled}
            // Leaflet's own internal panes/controls go up to z-index 1000
            // (see leaflet.css), so the calendar popup needs to clear that.
            zIndex={1100}
            containerClassName="w-full !h-full"
            inputClass={inputClassName}
            ref={datePickerRef}
            onOpenPickNewDate={false}
            mapDays={mapDays}
            inputMode="numeric"
            /* `_value` is the library's formatted string, which this field does
             not use — it renders `summary` instead. Typed `unknown` because it
             is deliberately ignored. */
          render={(_value: unknown, openCalendar: () => void) => (
              <input
                ref={ref}
                /* On the input, not on `<DatePicker>`: a `render` prop
                   replaces the picker's own input, so the id passed to the
                   picker left the floating `<label htmlFor={name}>` pointing
                   at nothing — an unlabelled text box to a screen reader, and
                   a label whose click moved no focus, which is why it carries
                   its own `onClick` as a mouse workaround. */
                id={name}
                type="text"
                value={displayValue}
                onChange={handleInputChange}
                onFocus={handleFocus}
                onBlur={handleBlur}
                onClick={openCalendar}
                disabled={disabled}
                className={cn(
                  inputClassName,
                  disabled ? "cursor-not-allowed bg-opacity-70" : "",
                )}
                placeholder={isFocused || displayValue ? "" : undefined}
              />
            )}
          />

          <DateFieldAdornments
            clearable={clearable}
            displayValue={displayValue}
            disabled={disabled}
            showDueDate={showDueDate}
            isRtl={isRtl}
            onClear={() => {
              setFieldValue(name, "");
              setDisplayValue("");
              helpers.setTouched(true);
              setTimeout(() => validateField(name), 0);
            }}
            onIconClick={handleIconClick}
          />
        </div>

        {/* Error Message */}
        {meta.touched && meta.error && (
          <div className="text-red-500 text-sm mt-1">{meta.error}</div>
        )}
      </div>
    );
  },
);

DatePickerInput.displayName = "DatePickerInput";

export default DatePickerInput;
