import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useRef, useEffect } from 'react';
import styled from 'styled-components';
import FormField from '../../FormField';
import Select, { Option } from '../../Select';
import Flex from '../../Flex';
import { createClassName, range, withTestIds } from '../../../utils';
import { useConfiguration, useConsolidatedRef, useFocusWithin, useI18n, useTestIds } from '../../../hooks';
import { StyledSelect } from '../../Select/Select';
import { defaultThemeProp } from '../../../theme';
import { StyledFormControl } from '../../FormControl';
import { getQuarterInputTestIds } from '../DateTime.test-ids';
import { StyledFormField } from '../../FormField/FormField';
import { getQuarter, parseToDate } from './utils';
import StyledDateTime from './DateTime.styles';
export const StyledQuarterInput = styled(StyledDateTime) `
  padding: 0;
  border: 0;

  ${StyledFormField}:enabled > &:focus-within {
    box-shadow: none;
  }

  ${StyledSelect} {
    min-width: 0;

    &:focus {
      z-index: 1;
    }

    &:first-child {
      border-start-end-radius: 0;
      border-end-end-radius: 0;
    }

    &:last-child {
      max-width: max-content;
      margin-inline-start: -0.0625rem;
      border-start-start-radius: 0;
      border-end-start-radius: 0;
    }
  }
`;
StyledQuarterInput.defaultProps = defaultThemeProp;
const convertToCallbackParameter = (date, parts) => {
    if ([parts.quarter, parts.year].every(Boolean)) {
        const quarterStartMonth = [0, 3, 6, 9][Number(parts.quarter) - 1];
        const resultDate = new Date(date);
        resultDate.setUTCFullYear(Number(parts.year), quarterStartMonth, 1);
        return {
            valueAsISOString: resultDate.toISOString(),
            valueAsTimestamp: resultDate.getTime()
        };
    }
    if ([parts.year, parts.quarter].every(p => !p)) {
        return {
            valueAsISOString: undefined,
            valueAsTimestamp: undefined
        };
    }
    return {
        valueAsISOString: '',
        valueAsTimestamp: NaN,
        state: 'incomplete'
    };
};
const QuarterInput = forwardRef(function QuarterInput(props, ref) {
    const { testId, value, min, max, id, label, labelHidden, info, status, required, readOnly, disabled, onChange, onFocus, onBlur, autoFocus, additionalInfo, className, ...restProps } = props;
    const testIds = useTestIds(testId, getQuarterInputTestIds);
    const { locale } = useConfiguration();
    const date = value ? parseToDate(value) : undefined;
    const currentYear = date ? date.getUTCFullYear() : new Date().getFullYear();
    const minYear = min ? parseToDate(min).getUTCFullYear() : currentYear - 10;
    const maxYear = max ? parseToDate(max).getUTCFullYear() : currentYear + 10;
    const years = range(minYear, maxYear);
    const quarterSelectRef = useRef(null);
    const yearSelectRef = useRef(null);
    useEffect(() => {
        if (quarterSelectRef.current && yearSelectRef.current) {
            quarterSelectRef.current.value = date ? getQuarter(date).toString() : '';
            yearSelectRef.current.value = date?.getUTCFullYear().toString() ?? '';
        }
    }, [date?.toDateString()]);
    const pickParts = () => {
        return {
            quarter: quarterSelectRef.current?.value || '',
            year: yearSelectRef.current?.value || ''
        };
    };
    const onFocusChange = (focused) => {
        const callbackParam = convertToCallbackParameter(date ? new Date(date) : new Date(), pickParts());
        if (onFocus && focused)
            onFocus(callbackParam);
        else if (onBlur && !focused)
            onBlur(callbackParam);
    };
    const onSelectChange = () => {
        onChange?.(convertToCallbackParameter(date ? new Date(date) : new Date(), pickParts()));
    };
    const containerRef = useConsolidatedRef(ref);
    useFocusWithin([containerRef], onFocusChange);
    const t = useI18n();
    const quarters = [1, 2, 3, 4];
    const quarterOptions = quarters.map(quarterNumber => (_jsx(Option, { value: quarterNumber.toString(), children: t(`date_quarter_q${quarterNumber}`).trim() }, t(`date_quarter_q${quarterNumber}`).trim())));
    const yearOptions = years.map(year => (_jsx(Option, { value: year.toString(), children: year.toString() }, year.toString())));
    const displayNames = new Intl.DisplayNames(locale, { style: 'long', type: 'dateTimeField' });
    const Quarter = (_jsxs(Select, { "data-testid": testIds.controlQuarter, ref: quarterSelectRef, "aria-label": displayNames.of('quarter'), readOnly: readOnly, required: required, onChange: onSelectChange, status: status, disabled: disabled, autoFocus: autoFocus, children: [!required && _jsx(Option, { children: " " }, 'null'), quarterOptions] }, 'quarter'));
    const Year = (_jsxs(Select, { "data-testid": testIds.controlYear, ref: yearSelectRef, "aria-label": displayNames.of('year'), readOnly: readOnly, required: required, onChange: onSelectChange, status: status, disabled: disabled, children: [!required && _jsx(Option, { children: " " }, 'null'), yearOptions] }, 'year'));
    const Comp = (_jsxs(Flex, { "data-testid": label ? undefined : testIds.root, ...restProps, as: StyledQuarterInput, className: createClassName('quarter-input', className), forwardedAs: StyledFormControl, container: { alignItems: 'center' }, ref: containerRef, status: status, disabled: disabled, readOnly: readOnly, children: [Quarter, Year] }));
    return label ? (_jsx(FormField, { testId: testIds, as: 'fieldset', labelAs: 'legend', label: label, labelHidden: labelHidden, id: id, info: info, status: status, required: required, disabled: disabled, additionalInfo: additionalInfo, children: Comp })) : (Comp);
});
export default withTestIds(QuarterInput, getQuarterInputTestIds);
//# sourceMappingURL=QuarterInput.js.map