import { compareAsc, compareDesc, format, isSameMonth, setYear, } from "date-fns";
import React, { useEffect, useRef } from "react";
import { cl } from "../../../utils/helpers/index.js";
import { dateIsInCurrentMonth, isMatch } from "../../date-utils/index.js";
import { useMonthPickerContext } from "../MonthPicker.context.js";
import { nextEnabled } from "../MonthPicker.util.js";
const disableMonth = (month, fromDate, toDate) => {
    if (fromDate && toDate) {
        return ((compareAsc(month, fromDate) === -1 && !isSameMonth(month, fromDate)) ||
            (compareDesc(month, toDate) === -1 && !isSameMonth(month, toDate)));
    }
    if (fromDate) {
        return compareAsc(month, fromDate) === -1 && !isSameMonth(month, fromDate);
    }
    if (toDate) {
        return compareDesc(month, toDate) === -1 && !isSameMonth(month, toDate);
    }
    return false;
};
export const MonthButton = ({ month, months, focus, setFocus, tabRoot, setTabRoot, }) => {
    const ref = useRef(null);
    const { fromDate, toDate, locale, selected, disabled, year, onYearChange, onMonthSelect, caption, } = useMonthPickerContext();
    const isSelected = selected && isSameMonth(month, selected);
    useEffect(() => {
        var _a;
        if (focus) {
            isSameMonth(month, focus) && ((_a = ref.current) === null || _a === void 0 ? void 0 : _a.focus());
            setFocus();
        }
    }, [focus, month, setFocus]);
    const isDisabled = isMatch(setYear(month, year.getFullYear()), disabled) ||
        disableMonth(month, fromDate, toDate);
    const isThisMonth = dateIsInCurrentMonth(month, year);
    return (React.createElement("button", { ref: ref, type: "button", onClick: () => onMonthSelect === null || onMonthSelect === void 0 ? void 0 : onMonthSelect(isSelected ? undefined : month), disabled: isDisabled, "aria-pressed": !!isSelected, "data-current-month": isThisMonth, className: cl("aksel-date__month-button", {
            "rdp-day_today": isThisMonth,
            "rdp-day_selected": isSelected,
            "rdp-day_disabled": isDisabled,
        }), tabIndex: tabRoot && isSameMonth(month, setYear(tabRoot, year.getFullYear()))
            ? 0
            : -1, onKeyDown: (e) => {
            const next = nextEnabled(months, e.key, disabled, month, onYearChange, year, caption === "dropdown", fromDate, toDate);
            setFocus(next);
            setTabRoot(next);
        }, onFocus: () => {
            setTabRoot(focus);
        } },
        React.createElement("div", { className: "rdp-day__inner" },
            React.createElement("span", { "aria-hidden": "true" }, format(new Date(month), "LLL", { locale })
                .replace(".", "")
                .substring(0, 3)),
            React.createElement("span", { className: "aksel-sr-only" }, format(new Date(month), "LLLL", { locale })))));
};
export default MonthButton;
//# sourceMappingURL=MonthPicker.Button.js.map