import { jsxs, jsx } from "react/jsx-runtime";
import { useState, useEffect, useCallback } from "react";
import moment from "moment";
import { getAssetUrl } from "../../utils/assetBase.js";
const calendarIcon = getAssetUrl("icons/calendar.svg");
const NUMBER_POSITIONS = [0, 1, 3, 4, 6, 7, 8, 9];
const FORMAT_MAP = {
  "DD-MM-YYYY": { day: [0, 2], month: [3, 5], year: [6, 10] },
  "MM-DD-YYYY": { day: [3, 5], month: [0, 2], year: [6, 10] },
  "YYYY-MM-DD": { day: [8, 10], month: [5, 7], year: [0, 4] }
};
function DateRangePickerInput({
  inputContainerRef,
  startDateString = "",
  onStartDateFocus,
  startDateInputRef,
  startDateInputProps,
  endDateString = "",
  onEndDateFocus,
  endDateInputRef,
  endDateInputProps,
  isDisabled,
  isError,
  displayFormat = "DD-MM-YYYY",
  onStartDateStringChange,
  onEndDateStringChange,
  minDate,
  maxDate,
  readOnly = false,
  isOutsideRange,
  onErrorStateChange,
  clearErrorsTrigger = 0,
  resetTrigger = 0,
  customIcon
}) {
  const [startInputValue, setStartInputValue] = useState("");
  const [endInputValue, setEndInputValue] = useState("");
  const [startErrorState, setStartErrorState] = useState(false);
  const [endErrorState, setEndErrorState] = useState(false);
  const [startPendingCursorPosition, setStartPendingCursorPosition] = useState(null);
  const [endPendingCursorPosition, setEndPendingCursorPosition] = useState(null);
  useEffect(() => {
    setStartInputValue(startDateString ?? "");
  }, [startDateString]);
  useEffect(() => {
    setEndInputValue(endDateString ?? "");
  }, [endDateString]);
  useEffect(() => {
    if (clearErrorsTrigger > 0) {
      setStartErrorState(false);
      setEndErrorState(false);
    }
  }, [clearErrorsTrigger]);
  useEffect(() => {
    if (resetTrigger > 0) {
      setStartErrorState(false);
      setEndErrorState(false);
      setStartInputValue("");
      setEndInputValue("");
      onStartDateStringChange == null ? void 0 : onStartDateStringChange(null);
      onEndDateStringChange == null ? void 0 : onEndDateStringChange(null);
    }
  }, [resetTrigger, onStartDateStringChange, onEndDateStringChange]);
  useEffect(() => {
    const hasErrors = startErrorState || endErrorState;
    onErrorStateChange == null ? void 0 : onErrorStateChange(hasErrors);
  }, [startErrorState, endErrorState, onErrorStateChange]);
  useEffect(() => {
    if (startPendingCursorPosition != null && startDateInputRef.current) {
      startDateInputRef.current.setSelectionRange(
        startPendingCursorPosition,
        startPendingCursorPosition
      );
      setStartPendingCursorPosition(null);
    }
  }, [startInputValue, startPendingCursorPosition, startDateInputRef]);
  useEffect(() => {
    if (endPendingCursorPosition != null && endDateInputRef.current) {
      endDateInputRef.current.setSelectionRange(endPendingCursorPosition, endPendingCursorPosition);
      setEndPendingCursorPosition(null);
    }
  }, [endInputValue, endPendingCursorPosition, endDateInputRef]);
  const validateDate = useCallback(
    (date, isStartDate) => {
      if (minDate != null && date.isBefore(minDate, "day")) return false;
      if (maxDate != null && date.isAfter(maxDate, "day")) return false;
      const formatInfo = FORMAT_MAP[displayFormat] ?? FORMAT_MAP["DD-MM-YYYY"];
      if (!formatInfo) return false;
      const inputVal = isStartDate ? startInputValue : endInputValue;
      const day = parseInt(inputVal.substring(formatInfo.day[0], formatInfo.day[1]), 10) || 0;
      const month = parseInt(inputVal.substring(formatInfo.month[0], formatInfo.month[1]), 10) || 0;
      const year = parseInt(inputVal.substring(formatInfo.year[0], formatInfo.year[1]), 10) || 0;
      if (month < 1 || month > 12) return false;
      const lastDay = moment(`${year}-${month}`, "YYYY-M").daysInMonth();
      if (day < 1 || day > lastDay) return false;
      if (isStartDate && endInputValue) {
        const endDateParsed = moment(endInputValue, displayFormat, true);
        if (endDateParsed.isValid() && date.isAfter(endDateParsed, "day")) return false;
      }
      if (!isStartDate && startInputValue) {
        const startDateParsed = moment(startInputValue, displayFormat, true);
        if (startDateParsed.isValid() && date.isBefore(startDateParsed, "day")) return false;
      }
      if (isOutsideRange == null ? void 0 : isOutsideRange(date)) return false;
      return true;
    },
    [displayFormat, minDate, maxDate, startInputValue, endInputValue, isOutsideRange]
  );
  const handleStartFocus = () => {
    if (!startInputValue) {
      setStartInputValue(displayFormat);
      setTimeout(() => {
        var _a;
        (_a = startDateInputRef.current) == null ? void 0 : _a.setSelectionRange(0, 0);
      }, 0);
    }
    onStartDateFocus();
  };
  const handleEndFocus = () => {
    if (!endInputValue) {
      setEndInputValue(displayFormat);
      setTimeout(() => {
        var _a;
        (_a = endDateInputRef.current) == null ? void 0 : _a.setSelectionRange(0, 0);
      }, 0);
    }
    onEndDateFocus();
  };
  const handleStartBlur = () => {
    const parsed = moment(startInputValue, displayFormat, true);
    if (parsed.isValid()) {
      const valid = validateDate(parsed, true);
      setStartErrorState(!valid);
      if (valid) onStartDateStringChange == null ? void 0 : onStartDateStringChange(parsed);
    } else {
      setStartErrorState(true);
    }
    if (!startInputValue || startInputValue === displayFormat) {
      setStartInputValue("");
      setStartErrorState(false);
      onStartDateStringChange == null ? void 0 : onStartDateStringChange(null);
    }
  };
  const handleEndBlur = () => {
    const parsed = moment(endInputValue, displayFormat, true);
    if (parsed.isValid()) {
      const valid = validateDate(parsed, false);
      setEndErrorState(!valid);
      if (valid) onEndDateStringChange == null ? void 0 : onEndDateStringChange(parsed);
    } else {
      setEndErrorState(true);
    }
    if (!endInputValue || endInputValue === displayFormat) {
      setEndInputValue("");
      setEndErrorState(false);
      onEndDateStringChange == null ? void 0 : onEndDateStringChange(null);
    }
  };
  const handleStartChange = (e) => {
    const input = e.target;
    const value = input.value;
    const cursorPosition = input.selectionStart ?? 0;
    if (cursorPosition < 1) return;
    const newChar = value[cursorPosition - 1];
    if (newChar == null || !/^\d$/.test(newChar)) return;
    const pos = cursorPosition - 1;
    if (!NUMBER_POSITIONS.includes(pos)) {
      e.preventDefault();
      const next = NUMBER_POSITIONS.find((p) => p > pos) ?? NUMBER_POSITIONS[NUMBER_POSITIONS.length - 1];
      setStartPendingCursorPosition(next ?? null);
      return;
    }
    const newValue = startInputValue.slice(0, pos) + newChar + startInputValue.slice(pos + 1);
    if (newValue.length > displayFormat.length) return;
    setStartInputValue(newValue);
    onStartDateStringChange == null ? void 0 : onStartDateStringChange(newValue);
    const idx = NUMBER_POSITIONS.indexOf(pos);
    if (idx < NUMBER_POSITIONS.length - 1) {
      setStartPendingCursorPosition(NUMBER_POSITIONS[idx + 1] ?? null);
    } else {
      const parsed = moment(newValue, displayFormat, true);
      const valid = parsed.isValid() && validateDate(parsed, true);
      setStartErrorState(!valid);
      onStartDateStringChange == null ? void 0 : onStartDateStringChange(valid ? parsed : newValue);
    }
  };
  const handleEndChange = (e) => {
    const input = e.target;
    const value = input.value;
    const cursorPosition = input.selectionStart ?? 0;
    if (cursorPosition < 1) return;
    const newChar = value[cursorPosition - 1];
    if (newChar == null || !/^\d$/.test(newChar)) return;
    const pos = cursorPosition - 1;
    if (!NUMBER_POSITIONS.includes(pos)) {
      e.preventDefault();
      const next = NUMBER_POSITIONS.find((p) => p > pos) ?? NUMBER_POSITIONS[NUMBER_POSITIONS.length - 1];
      setEndPendingCursorPosition(next ?? null);
      return;
    }
    const newValue = endInputValue.slice(0, pos) + newChar + endInputValue.slice(pos + 1);
    if (newValue.length > displayFormat.length) return;
    setEndInputValue(newValue);
    onEndDateStringChange == null ? void 0 : onEndDateStringChange(newValue);
    const idx = NUMBER_POSITIONS.indexOf(pos);
    if (idx < NUMBER_POSITIONS.length - 1) {
      setEndPendingCursorPosition(NUMBER_POSITIONS[idx + 1] ?? null);
    } else {
      const parsed = moment(newValue, displayFormat, true);
      const valid = parsed.isValid() && validateDate(parsed, false);
      setEndErrorState(!valid);
      onEndDateStringChange == null ? void 0 : onEndDateStringChange(valid ? parsed : newValue);
    }
  };
  const handleStartKeyDown = (e) => {
    var _a;
    if (["ArrowLeft", "ArrowRight", "Tab"].includes(e.key)) return;
    if (e.key === "Backspace") {
      e.preventDefault();
      const caret = ((_a = startDateInputRef.current) == null ? void 0 : _a.selectionStart) ?? 0;
      const deletePos = [...NUMBER_POSITIONS].reverse().find((p) => p < caret);
      if (deletePos == null) return;
      const sep = displayFormat[deletePos] ?? "";
      const newValue = startInputValue.slice(0, deletePos) + sep + startInputValue.slice(deletePos + 1);
      setStartInputValue(newValue);
      onStartDateStringChange == null ? void 0 : onStartDateStringChange(newValue);
      let nextCaret = deletePos;
      while (nextCaret > 0 && !NUMBER_POSITIONS.includes(nextCaret - 1)) nextCaret--;
      setStartPendingCursorPosition(nextCaret);
      return;
    }
    if (!/^\d$/.test(e.key)) e.preventDefault();
  };
  const handleEndKeyDown = (e) => {
    var _a;
    if (["ArrowLeft", "ArrowRight", "Tab"].includes(e.key)) return;
    if (e.key === "Backspace") {
      e.preventDefault();
      const caret = ((_a = endDateInputRef.current) == null ? void 0 : _a.selectionStart) ?? 0;
      const deletePos = [...NUMBER_POSITIONS].reverse().find((p) => p < caret);
      if (deletePos == null) return;
      const sep = displayFormat[deletePos] ?? "";
      const newValue = endInputValue.slice(0, deletePos) + sep + endInputValue.slice(deletePos + 1);
      setEndInputValue(newValue);
      onEndDateStringChange == null ? void 0 : onEndDateStringChange(newValue);
      let nextCaret = deletePos;
      while (nextCaret > 0 && !NUMBER_POSITIONS.includes(nextCaret - 1)) nextCaret--;
      setEndPendingCursorPosition(nextCaret);
      return;
    }
    if (!/^\d$/.test(e.key)) e.preventDefault();
  };
  const handleStartClick = () => {
    var _a, _b, _c;
    const cursor = ((_a = startDateInputRef.current) == null ? void 0 : _a.selectionStart) ?? 0;
    const lastPos = (NUMBER_POSITIONS[NUMBER_POSITIONS.length - 1] ?? 0) + 1;
    if (cursor >= lastPos) {
      (_b = startDateInputRef.current) == null ? void 0 : _b.setSelectionRange(lastPos, lastPos);
      return;
    }
    if (!NUMBER_POSITIONS.includes(cursor)) {
      const next = NUMBER_POSITIONS.find((p) => p >= cursor) ?? NUMBER_POSITIONS[NUMBER_POSITIONS.length - 1] ?? 0;
      (_c = startDateInputRef.current) == null ? void 0 : _c.setSelectionRange(next, next);
    }
  };
  const handleEndClick = () => {
    var _a, _b, _c;
    const cursor = ((_a = endDateInputRef.current) == null ? void 0 : _a.selectionStart) ?? 0;
    const lastPos = (NUMBER_POSITIONS[NUMBER_POSITIONS.length - 1] ?? 0) + 1;
    if (cursor >= lastPos) {
      (_b = endDateInputRef.current) == null ? void 0 : _b.setSelectionRange(lastPos, lastPos);
      return;
    }
    if (!NUMBER_POSITIONS.includes(cursor)) {
      const next = NUMBER_POSITIONS.find((p) => p >= cursor) ?? NUMBER_POSITIONS[NUMBER_POSITIONS.length - 1] ?? 0;
      (_c = endDateInputRef.current) == null ? void 0 : _c.setSelectionRange(next, next);
    }
  };
  const showError = Boolean(isError ?? startErrorState ?? endErrorState);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: inputContainerRef,
      className: `dateRangePicker-input-container ${isDisabled ? "dateRangePicker-input-disabled" : ""} ${showError ? "impact-dateRangePicker-error" : ""}`.trim(),
      children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            ref: startDateInputRef,
            className: "dateRangePicker-input-start-date",
            placeholder: "Start Date",
            readOnly,
            type: "text",
            value: startInputValue,
            onBlur: handleStartBlur,
            onChange: handleStartChange,
            onClick: handleStartClick,
            onFocus: handleStartFocus,
            onKeyDown: handleStartKeyDown,
            ...startDateInputProps
          }
        ),
        /* @__PURE__ */ jsx(
          "input",
          {
            ref: endDateInputRef,
            className: "dateRangePicker-input-end-date",
            placeholder: "End Date",
            readOnly,
            type: "text",
            value: endInputValue,
            onBlur: handleEndBlur,
            onChange: handleEndChange,
            onClick: handleEndClick,
            onFocus: handleEndFocus,
            onKeyDown: handleEndKeyDown,
            ...endDateInputProps
          }
        ),
        customIcon != null ? /* @__PURE__ */ jsx(
          "span",
          {
            className: "end-date-icon",
            style: {
              position: "absolute",
              right: 10,
              top: "50%",
              transform: "translateY(-50%)",
              cursor: isDisabled ? "" : "pointer",
              opacity: isDisabled ? 0.5 : 1
            },
            children: customIcon
          }
        ) : /* @__PURE__ */ jsx(
          "span",
          {
            "aria-hidden": true,
            className: "end-date-icon",
            style: {
              position: "absolute",
              right: 10,
              top: "50%",
              transform: "translateY(-50%)",
              cursor: isDisabled ? "" : "pointer",
              width: 14,
              height: 14,
              background: `url(${calendarIcon}) no-repeat center/contain`,
              opacity: isDisabled ? 0.5 : 1
            },
            onClick: (e) => {
              var _a;
              e.stopPropagation();
              if (!isDisabled) (_a = startDateInputRef.current) == null ? void 0 : _a.focus();
            }
          }
        )
      ]
    }
  );
}
export {
  DateRangePickerInput
};
