"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const DatePicker_1 = require("../../DatePicker");
const useForwardedRef_1 = require("../../useForwardedRef");
const usePopover_1 = require("../../usePopover");
const date_1 = require("../../utils/date");
const hooks_1 = require("./hooks");
const utils_1 = require("./utils");
const useLogic = ({ value, minDate = DatePicker_1.DEFAULT_MIN_DATE, maxDate = DatePicker_1.DEFAULT_MAX_DATE, mask = DatePicker_1.DEFAULT_DATE_MASK, onChange, onOpen, onClose, onBlur, }, forwardedRef) => {
    const ref = (0, useForwardedRef_1.useForwardedRef)(forwardedRef);
    const startInputRef = (0, react_1.useRef)(null);
    const endInputRef = (0, react_1.useRef)(null);
    const [hoveredDayDate, setHoveredDayDate] = (0, react_1.useState)();
    /**
     * Была ли выбрана start/end-дата после открытия поповера
     */
    const [isStartDateSelected, setIsStartDateSelected] = (0, react_1.useState)(false);
    const [isEndDateSelected, setIsEndDateSelected] = (0, react_1.useState)(false);
    const [activeInput, setActiveInput] = (0, react_1.useState)();
    const [isPopoverHovered, setIsPopoverHovered] = (0, react_1.useState)(false);
    const { isOpen, actions } = (0, usePopover_1.usePopover)();
    const { open, close } = actions;
    (0, react_1.useEffect)(() => {
        setIsStartDateSelected(false);
        setIsEndDateSelected(false);
    }, [isOpen]);
    const selectedStartBaseDate = (0, DatePicker_1.useSelectedBaseDate)({
        currentValue: value?.start,
        minDate,
        maxDate,
    });
    const selectedEndBaseDate = (0, DatePicker_1.useSelectedBaseDate)({
        currentValue: value?.end,
        minDate,
        maxDate,
    });
    const { startBaseDate, endBaseDate } = (0, hooks_1.useBaseRangeDates)({
        minDate,
        maxDate,
        shouldReturnPrevValues: isOpen,
        selectedStartDate: selectedStartBaseDate,
        selectedEndDate: selectedEndBaseDate,
    });
    const handleChangeStartDate = (startDateValue, startMaskString) => {
        const isStartComplete = startDateValue != null &&
            startMaskString != null &&
            (0, date_1.isMaskedDateSyntacticallyComplete)(startMaskString, mask);
        if (isStartComplete &&
            value?.end &&
            startDateValue &&
            startDateValue > value.end) {
            onChange?.({ start: startDateValue, end: undefined });
            return;
        }
        onChange?.({ ...value, start: startDateValue });
    };
    const handleChangeEndDate = (endDateValue, endMaskString) => {
        const isEndComplete = endDateValue != null &&
            endMaskString != null &&
            (0, date_1.isMaskedDateSyntacticallyComplete)(endMaskString, mask);
        if (isEndComplete &&
            value?.start &&
            endDateValue &&
            endDateValue < value.start) {
            onChange?.({ start: undefined, end: endDateValue });
            return;
        }
        onChange?.({ ...value, end: endDateValue });
    };
    const { maskedValue: startMaskedValue, onMaskedValueChange: onMaskedStartValueChange, onMaskedValueBlur: onMaskedStartValueBlur, onMaskedDateChange: onMaskedStartDateChange, } = (0, DatePicker_1.useMaskedValue)({
        currentValue: value?.start,
        mask,
        onChangeValue: handleChangeStartDate,
    });
    const { maskedValue: endMaskedValue, onMaskedValueChange: onMaskedEndValueChange, onMaskedValueBlur: onMaskedEndValueBlur, onMaskedDateChange: onMaskedEndDateChange, } = (0, DatePicker_1.useMaskedValue)({
        currentValue: value?.end,
        mask,
        onChangeValue: handleChangeEndDate,
    });
    const handleOpen = (event) => {
        onOpen?.();
        open(event);
    };
    const flushActiveMaskedValueOnClose = () => {
        if (activeInput === 'startDate') {
            onMaskedStartValueBlur();
        }
        if (activeInput === 'endDate') {
            onMaskedEndValueBlur();
        }
    };
    const handleClose = () => {
        flushActiveMaskedValueOnClose();
        onBlur?.();
        onClose?.();
        close();
    };
    const handleStartInputBlur = () => {
        if (isOpen) {
            return;
        }
        onMaskedStartValueBlur();
    };
    const handleEndInputBlur = () => {
        if (isOpen) {
            return;
        }
        onMaskedEndValueBlur();
    };
    const handleClickStartInput = (e) => {
        setActiveInput('startDate');
        startInputRef.current?.focus();
        if (!isOpen) {
            handleOpen(e);
        }
    };
    const handleClickEndInput = (e) => {
        setActiveInput('endDate');
        endInputRef.current?.focus();
        if (!isOpen) {
            handleOpen(e);
        }
    };
    const pickStartDate = (pickedDate) => {
        onMaskedStartDateChange(pickedDate);
        setIsStartDateSelected(true);
        setActiveInput('endDate');
        endInputRef.current?.focus();
        if (isEndDateSelected) {
            handleClose();
        }
    };
    const pickEndDate = (pickedDate) => {
        onMaskedEndDateChange(pickedDate);
        setIsEndDateSelected(true);
        setActiveInput('startDate');
        startInputRef.current?.focus();
        if (isStartDateSelected) {
            handleClose();
        }
    };
    const handleDayPick = (pickedDate) => {
        if (activeInput === 'startDate') {
            pickStartDate(pickedDate);
        }
        if (activeInput === 'endDate') {
            pickEndDate(pickedDate);
        }
    };
    const handleAcceptStart = (_, maskRef) => {
        onMaskedStartValueChange(maskRef.value);
    };
    const handleAcceptEnd = (_, maskRef) => {
        onMaskedEndValueChange(maskRef.value);
    };
    const handlePopoverMouseEnter = () => setIsPopoverHovered(true);
    const handlePopoverMouseLeave = () => setIsPopoverHovered(false);
    return {
        ref,
        startDatePickerInputProps: {
            ref: startInputRef,
            value: startMaskedValue,
            onAccept: handleAcceptStart,
            onBlur: handleStartInputBlur,
            onClick: handleClickStartInput,
        },
        endDatePickerInputProps: {
            ref: endInputRef,
            value: endMaskedValue,
            onAccept: handleAcceptEnd,
            onBlur: handleEndInputBlur,
            onClick: handleClickEndInput,
        },
        popoverHoveredContextProviderProps: {
            popoverHovered: isPopoverHovered,
        },
        datePickerPopoverProps: {
            open: isOpen,
            anchorEl: ref.current,
            onMouseEnter: handlePopoverMouseEnter,
            onMouseLeave: handlePopoverMouseLeave,
            onClose: handleClose,
        },
        minMaxDateContextProviderProps: {
            minDate: isStartDateSelected
                ? (0, utils_1.getBoundaryDate)({
                    reserve: minDate,
                    target: value?.start,
                })
                : minDate,
            maxDate: isEndDateSelected
                ? (0, utils_1.getBoundaryDate)({
                    reserve: maxDate,
                    target: value?.end,
                })
                : maxDate,
        },
        startYearMonthDayPickerProps: {
            selectedDate: selectedStartBaseDate || selectedEndBaseDate,
            rangeDate: value?.end || value?.start,
            date: startBaseDate,
            hoveredDayDate,
            onDayHover: setHoveredDayDate,
            onChange: handleDayPick,
        },
        endYearMonthDayPickerProps: {
            selectedDate: selectedStartBaseDate || selectedEndBaseDate,
            rangeDate: value?.end || value?.start,
            date: endBaseDate,
            hoveredDayDate,
            onDayHover: setHoveredDayDate,
            onChange: handleDayPick,
        },
    };
};
exports.useLogic = useLogic;
