import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef } from 'react';
import styled, { css } from 'styled-components';
import { mix } from 'polished';
import { defaultThemeProp } from '../../../theme';
import Button from '../../Button';
import { useArrows, useConfiguration, useElement } from '../../../hooks';
import { is12HClockFormat } from '../Input/utils';
import { tryCatch } from '../../../utils';
import { getIntlDateTimeFormatFromCache } from '../utils';
import { getIntervalGenerator } from './utils';
const StyledTimePicker = styled.ul `
  list-style: none;
  max-height: 10rem;
  overflow: auto;
  width: 100%;
`;
StyledTimePicker.defaultProps = defaultThemeProp;
const StyledTimeButton = styled.button(({ theme: { base, components }, selected }) => {
    const activeColor = tryCatch(() => mix(0.85, base.palette['primary-background'], base.palette.interactive));
    return css `
      color: ${base.palette['foreground-color']};
      width: 100%;
      border-radius: inherit;
      overflow: hidden;
      text-align: start;
      text-overflow: ellipsis;
      white-space: nowrap;
      border-width: 0;
      justify-content: start;
      padding: 0;
      background-color: ${selected ? activeColor : 'transparent'};

      > span {
        margin-inline-end: 0.125rem;
        &:first-child {
          margin-inline-start: ${components['form-control']['border-width']};
        }
        &:nth-child(2) {
          margin-inline-start: 0.125rem;
        }
        &:first-child,
        &:nth-child(3) {
          padding-inline-start: 0.5rem;
        }
      }

      &:enabled:focus,
      &:not([disabled]):focus {
        box-shadow: ${base.shadow['focus-inset']};
      }
    `;
});
StyledTimeButton.defaultProps = defaultThemeProp;
const StyledTimeItem = styled.li `
  border-radius: 0;
`;
StyledTimeItem.defaultProps = defaultThemeProp;
const TimePicker = (props) => {
    const { locale } = useConfiguration();
    const { testId, selected = new Date(0), interval = 30, clockFormat, onSelect, ...restProps } = props;
    const intervalInMS = interval * 60000;
    const { hourCycle: defaultHourCycle } = useMemo(() => getIntlDateTimeFormatFromCache(locale, {
        hour: '2-digit',
        hour12: clockFormat ? clockFormat === 12 : is12HClockFormat(locale)
    }).resolvedOptions(), [clockFormat, locale]);
    const actionsList = Array.from(getIntervalGenerator(intervalInMS), time => {
        const date = selected ? new Date(new Date().setUTCHours(0, 0, 0, 0)) : new Date(selected);
        date.setUTCHours(time.getUTCHours(), time.getUTCMinutes());
        return {
            id: date.getTime().toString(),
            text: Intl.DateTimeFormat(locale, {
                hour: '2-digit',
                minute: '2-digit',
                timeZone: 'UTC',
                /** Use this to fix Chrome https://bugs.chromium.org/p/chromium/issues/detail?id=1045791 */
                hourCycle: defaultHourCycle === 'h24' ? 'h23' : defaultHourCycle
            }).format(date)
        };
    });
    const isSelected = (date) => {
        return (selected?.getUTCHours() === date.getUTCHours() &&
            selected?.getUTCMinutes() === date.getUTCMinutes());
    };
    const [buttonEl, setButtonEl] = useElement();
    const menuRef = useRef(null);
    useArrows(menuRef, {
        selector: 'button',
        cycle: true,
        dir: 'up-down',
        allowTabFocus: false
    });
    const renderTime = (text) => {
        const [hour, minute, meridiem] = text.split(/:| /);
        return (_jsxs(_Fragment, { children: [_jsx("span", { children: hour }), ":", _jsx("span", { children: minute }), meridiem && _jsx("span", { children: meridiem })] }));
    };
    const setTabIndexes = useCallback(() => {
        const focusEl = menuRef.current;
        if (!focusEl)
            return;
        const focusableElements = Array.from(focusEl.querySelectorAll('button'));
        if (focusableElements.length > 0) {
            let isChecked = false;
            focusableElements.slice(1).forEach(item => {
                const checked = item.checked;
                if (checked) {
                    isChecked = true;
                    item.tabIndex = 0;
                }
                else
                    item.tabIndex = -1;
            });
            if (!isChecked) {
                focusableElements[0].tabIndex = 0;
                focusableElements[0].focus();
            }
        }
    }, [selected]);
    useEffect(() => {
        buttonEl?.focus();
        setTabIndexes();
    }, [buttonEl]);
    return (_jsx(StyledTimePicker, { "data-testid": testId, role: 'menu', tabIndex: -1, ref: menuRef, ...restProps, children: actionsList.map(({ text, id }) => {
            const item = new Date(Number(id));
            return (_jsx(StyledTimeItem, { role: 'presentation', children: _jsx(StyledTimeButton, { role: 'menuitem', as: Button, variant: 'simple', ref: isSelected(item) ? setButtonEl : null, "aria-label": text, selected: isSelected(item), "aria-current": isSelected(item) ? 'time' : undefined, checked: isSelected(item), onClick: () => {
                        onSelect?.(item);
                    }, tabIndex: '-1', children: renderTime(text) }) }, id));
        }) }));
};
export default TimePicker;
//# sourceMappingURL=TimePicker.js.map