import React, { Fragment, useCallback, useEffect, useRef } from "react";
import { useQuarters } from "../../hooks";
import { innerTokens, tokens } from "../../Calendar.tokens";
import { ROW_QUARTER_STEP, canSelectDate, getInRange, getSideInRange, isSameDay, isSelectProcess } from "../../utils";
import { DateStructureItem } from "../DateStructureItem/DateStructureItem";
import { StyledCalendarQuarters } from "./CalendarQuarters.styles";
/**
 * Компонент кварталов в календаре.
 */ export const CalendarQuarters = ({ date: currentDate, value, selectIndexes, eventList, disabledList, min, max, outerRefs, isDouble, isSecond, hoveredQuarter, onChangeQuarter, onHoverQuarter, onSetSelected, onTriggerEventTooltip, onKeyDown })=>{
    const minDate = min ? new Date(min.getFullYear(), min.getMonth(), 1) : undefined;
    const maxDate = max ? new Date(max.getFullYear(), max.getMonth() + 1, 0) : undefined;
    const [quarters, selected] = useQuarters({
        date: currentDate,
        value,
        eventList,
        disabledList,
        min: minDate,
        max: maxDate
    });
    const selectedRef = useRef(selected);
    const onSetSelectedRef = useRef(onSetSelected);
    const noopRef = useRef(null);
    const offset = isSecond ? ROW_QUARTER_STEP : 0;
    const quarterItemTokens = {
        [`${innerTokens.dateStructureFontFamily}`]: `var(${tokens.calendarQuarterFontFamily})`,
        [`${innerTokens.dateStructureFontSize}`]: `var(${tokens.calendarQuarterFontSize})`,
        [`${innerTokens.dateStructureFontWeight}`]: `var(${tokens.calendarQuarterFontWeight})`,
        [`${innerTokens.dateStructureFontLineHeight}`]: `var(${tokens.calendarQuarterFontLineHeight})`,
        [`${innerTokens.dateStructureFontLetterSpacing}`]: `var(${tokens.calendarQuarterFontLetterSpacing})`,
        [`${innerTokens.dateStructureFontStyle}`]: `var(${tokens.calendarQuarterFontStyle})`,
        [`${innerTokens.dateStructureSelectedFontWeight}`]: `var(${tokens.calendarQuarterSelectedFontWeight})`,
        [`${innerTokens.dateStructureBorderRadius}`]: `var(${tokens.calendarQuarterItemBorderRadius})`
    };
    const getSelectedDate = useCallback((event)=>{
        const { day, monthIndex, year } = event.currentTarget.dataset;
        const selectedDate = {
            day: Number(day),
            monthIndex: Number(monthIndex),
            year: Number(year)
        };
        if (!canSelectDate(selectedDate, value, disabledList)) {
            return;
        }
        return selectedDate;
    }, [
        disabledList,
        value
    ]);
    const handleOnChangeQuarter = useCallback((i, j, quarterName)=>(event)=>{
            /**
             * нужно вызвать stopImmediatePropagation для случаев, когда
             * обработчик события onClick навешивается снаружи.
             * Как, например, в компоненте Popup
             */ event.nativeEvent.stopImmediatePropagation();
            const selectedDate = getSelectedDate(event);
            if (!selectedDate) {
                return;
            }
            onChangeQuarter(selectedDate, [
                i + offset,
                j
            ], quarterName);
            if (isSelectProcess(value)) {
                onHoverQuarter?.(undefined);
            }
        }, [
        getSelectedDate,
        onChangeQuarter,
        offset,
        value,
        onHoverQuarter
    ]);
    const handleOnHoverQuarter = useCallback((event)=>{
        const selectedDate = getSelectedDate(event);
        const isSelectedDone = Array.isArray(value) && value[0] && value[1];
        if (!selectedDate || !Array.isArray(value) || isSelectedDone) {
            return;
        }
        onHoverQuarter?.(selectedDate);
    }, [
        getSelectedDate,
        onHoverQuarter,
        value
    ]);
    const handleMouseOutGrid = ()=>{
        onHoverQuarter?.(undefined);
        onTriggerEventTooltip?.(noopRef, []);
    };
    const getRefs = useCallback((element, i, j)=>{
        if (!outerRefs.current[i + offset]) {
            outerRefs.current[i + offset] = [];
        }
        outerRefs.current[i + offset][j] = element;
    }, [
        offset,
        outerRefs
    ]);
    useEffect(()=>{
        if (selectedRef.current) {
            onSetSelectedRef.current?.(selectedRef.current);
        }
    }, []);
    return /*#__PURE__*/ React.createElement(StyledCalendarQuarters, {
        role: "grid",
        "aria-labelledby": "id-grid-label",
        onKeyDown: onKeyDown,
        onMouseLeave: handleMouseOutGrid
    }, quarters.map((quarter, i)=>/*#__PURE__*/ React.createElement(Fragment, {
            key: i
        }, quarter.map(({ quarterName, isSelected, isCurrent, date, events, isOutOfMinMaxRange, inRange, disabled, disabledArrowKey, disabledDates }, j)=>{
            return /*#__PURE__*/ React.createElement(DateStructureItem, {
                ref: (element)=>getRefs(element, i, j),
                style: quarterItemTokens,
                eventList: events,
                disabled: disabled,
                day: date.day,
                year: date.year,
                monthIndex: date.monthIndex,
                isFocused: i + offset === selectIndexes?.[0] && j === selectIndexes?.[1] && !isOutOfMinMaxRange,
                isSelected: isSelected,
                isCurrent: isCurrent,
                isDouble: isDouble,
                isHovered: isSameDay(date, hoveredQuarter),
                inRange: getInRange(value, date, hoveredQuarter, inRange),
                sideInRange: getSideInRange(value, date, hoveredQuarter, isSelected),
                onClick: disabled ? undefined : handleOnChangeQuarter(i, j, String(quarterName)),
                onMouseOver: disabled ? undefined : handleOnHoverQuarter,
                onTriggerEventTooltip: onTriggerEventTooltip,
                key: `StyledQuarter-${i}-${j}`,
                role: "gridcell",
                "aria-label": quarterName,
                disabledArrowKey: disabledArrowKey,
                disabledMonths: disabledDates,
                isDayInCurrentMonth: true
            }, quarterName);
        }))));
};
