"use client";

import React, { useRef, useState } from "react";
import DatePicker, { DateObject } from "react-multi-date-picker";
import { format, parseISO } from "date-fns";
import { useTranslation } from "react-i18next";
import AssetIcon from "@/components/ui/AssetIcon";

interface DateRangePickerProps {
  selectedDate: string;
  startDate: string;
  endDate: string;
  onDateChange: (date: string) => void;
  placeholder?: string;
}

/**
 * Single-date picker constrained to an opportunity's window. Named "range"
 * because the *selectable* span is a range — the value itself is one day.
 */
const DateRangePicker: React.FC<DateRangePickerProps> = ({
  selectedDate,
  startDate,
  endDate,
  onDateChange,
  placeholder,
}) => {
  const { t } = useTranslation();
  /*
   * Both derived from the `selectedDate` prop, not mirrored into state.
   *
   * They used to be two `useState`s kept in step by an effect, which made the
   * prop and the local copy two sources of truth for the same value: `commitDate`
   * wrote both *and* called `onDateChange`, so the parent's update then raced
   * the effect to set them again. Deriving removes the race and the one-frame
   * window where the input showed the previous date.
   *
   * A malformed stored value yields an empty input rather than throwing — the
   * `try` the effect wrapped this in is now the `isNaN` guard.
   */
  const internalValue = (() => {
    if (!selectedDate) return null;
    const parsed = parseISO(selectedDate);
    return isNaN(parsed.getTime()) ? null : parsed;
  })();
  const displayValue = internalValue
    ? format(internalValue, "dd-MM-yyyy")
    : "";
  // Bumped on every pick so the picker re-mounts and re-selecting the same
  // day still registers.
  const [forceRenderKey, setForceRenderKey] = useState<number>(0);
  const datePickerRef = useRef<{
    openCalendar: () => void;
    closeCalendar: () => void;
  }>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  const commitDate = (jsDate: Date) => {
    const normalizedDate = new Date(jsDate);
    normalizedDate.setHours(0, 0, 0, 0);

    /* `onDateChange` is the only write: the two displayed values are derived
       from the prop it updates, so setting them here as well is what made them
       a second source of truth. */
    onDateChange(format(normalizedDate, "yyyy-MM-dd"));
    setForceRenderKey((prev) => prev + 1);
    datePickerRef.current?.closeCalendar();
  };

  const handleDateSelect = (
    date: Date | DateObject | DateObject[] | null
  ) => {
    if (!date) return;
    const singleDate = Array.isArray(date) ? date[0] : date;
    if (!singleDate) return;
    commitDate(singleDate instanceof Date ? singleDate : singleDate.toDate());
  };

  const mapDays = ({ date }: { date: DateObject }) => {
    const thisDate = date.toDate();
    const startDateObj = parseISO(startDate);
    const endDateObj = parseISO(endDate);

    thisDate.setHours(0, 0, 0, 0);
    startDateObj.setHours(0, 0, 0, 0);
    endDateObj.setHours(0, 0, 0, 0);

    if (thisDate < startDateObj || thisDate > endDateObj) {
      return { disabled: true };
    }

    return { onClick: () => commitDate(thisDate) };
  };

  return (
    <div className="relative" ref={containerRef}>
      <DatePicker
        value={internalValue}
        onChange={handleDateSelect}
        minDate={parseISO(startDate)}
        maxDate={parseISO(endDate)}
        format="DD-MM-YYYY"
        mapDays={mapDays}
        onlyShowInRangeDates={false}
        ref={datePickerRef}
        key={`${selectedDate}-${forceRenderKey}`}
        render={(_value: unknown, openCalendar: () => void) => (
          <div className="searchitms flex items-center bg-white border border-primary-5/20 rounded-full px-4 py-2 md:h-[40px] h-[40px] laptopmain:h-[40px] mobilescreen:h-[48px] xss:rounded-[20px] w-[687px] 2xl:w-[687px] laptopmain:w-[580px] 2xl:h-[55px] lg:w-[450px] md:w-[350px] mobilescreen:w-full cursor-pointer">
            {/* 30x30 is the SVG's own `width`/`height`, so the browser
                reserves the right aspect box before it arrives; the classes
                still decide the rendered size. */}
            <AssetIcon
              src="/assets/profile/searchicn.svg"
              size={30}
              className="lg:w-auto md:w-5"
            />
            <input
              type="text"
              value={displayValue}
              onClick={openCalendar}
              placeholder={placeholder || t("COMMON.DATES")}
              className="flex-1 outline-none bg-transparent px-2 2xl:text-[25px] lg:text-lg xss:text-base laptopmain:text-xl lg:w-auto md:w-[150px] w-[150px] placeholder:text-[#181822]/80 cursor-pointer"
              readOnly
              aria-label={placeholder || t("COMMON.DATES")}
            />
            <button
              type="button"
              aria-label={t("COMMON.OPEN_CALENDAR")}
              onClick={openCalendar}
              className="cursor-pointer p-1"
            >
              {/* 18x22 — the icon is not square; both come from the SVG. */}
              <AssetIcon
                src="/assets/homepage/dateicon.svg"
                width={18}
                height={22}
                className="lg:w-auto md:w-5"
              />
            </button>
          </div>
        )}
      />
    </div>
  );
};

export default DateRangePicker;
