"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NewDateInput = void 0;
const react_1 = __importStar(require("react"));
const components_1 = require("../../components");
const icons_1 = require("../../icons");
const utils_1 = require("../../utils");
const inlines_1 = require("inlines");
const varsUtilities_1 = require("../../varsUtilities");
const Picker_1 = require("./Picker");
const NewTimeInput_1 = require("./NewTimeInput");
const DateRangeDoubleInput_1 = require("../DateRange/DateRangeDoubleInput");
const Popover = __importStar(require("@radix-ui/react-popover"));
const hover = {
    '&:hover': {
        backgroundColor: (0, varsUtilities_1.color)('action', 'neutral', 'subtleHover'),
    },
};
const NewDateInput = ({ value, setValue, time, style, autoFocus, numbered = false, }) => {
    const dayRef = (0, react_1.useRef)(null);
    const monthRef = (0, react_1.useRef)(null);
    const yearRef = (0, react_1.useRef)(null);
    const inputRef = (0, react_1.useRef)(null);
    // try this
    const DateObjVal = new Date(value);
    const newDay = DateObjVal.getDate();
    const newMonth = DateObjVal.getMonth() + 1;
    const newYear = DateObjVal.getFullYear();
    const [day, setDay] = (0, react_1.useState)(newDay || '');
    const [month, setMonth] = (0, react_1.useState)(newMonth || '');
    const [year, setYear] = (0, react_1.useState)(newYear || '');
    const [open, setOpen] = (0, react_1.useState)(false);
    const [focusField, setFocusField] = (0, react_1.useState)('');
    const fullDateString = `${day < 10 ? `0${day}` : day}/${month < 10 ? `0${month}` : month}/${year}`;
    // get the time as string format 00:00
    const [timeString, setTimeString] = (0, react_1.useState)(new Date(value).toString()?.split(' ')[4]?.split(':').slice(0, -1).join(':'));
    const stringToMilliseconds = (str, time) => {
        const dateString = `${str?.split('/').reverse().join('-')}T${time || '00:00'}`;
        const outputMs = new Date(dateString).getTime();
        return outputMs || 0;
    };
    (0, react_1.useEffect)(() => {
        if (day &&
            month &&
            year.toString().length > 3 &&
            stringToMilliseconds(fullDateString, timeString) !== value) {
            setValue(stringToMilliseconds(fullDateString, timeString));
        }
    }, [day, month, year, timeString]);
    (0, react_1.useEffect)(() => {
        setDay(newDay || '');
        setMonth(newMonth || '');
        setYear(newYear || '');
    }, [value]);
    const daysInMonth = (month, year) => {
        return new Date(year, month, 0).getDate();
    };
    return (react_1.default.createElement(Popover.Root, { open: open },
        react_1.default.createElement(inlines_1.styled.div, { style: { display: 'flex' } },
            react_1.default.createElement(inlines_1.styled.div, { onClick: (e) => e.preventDefault(), style: {
                    opacity: 0,
                    position: 'absolute',
                    pointerEvents: 'none',
                    //  marginTop: -32,
                } },
                react_1.default.createElement("input", { type: "number", style: { maxWidth: 40, border: '1px solid red' }, ref: dayRef, value: day, onChange: (e) => {
                        // should get last day of the month
                        if (+e.target.value < 1 ||
                            +e.target.value > daysInMonth(newMonth, newYear)) {
                            setDay(1);
                        }
                        else {
                            setDay(+e.target.value);
                        }
                    }, onKeyDown: (e) => {
                        if (e.key === 'Backspace') {
                            setDay('');
                        }
                        if (e.key === 'ArrowDown' && +e.currentTarget.value === 1) {
                            setDay(day);
                            setYear(year);
                            setMonth(month);
                        }
                    }, onKeyUp: (e) => {
                        if (+e.key > 3) {
                            monthRef.current?.select();
                        }
                        if (e.currentTarget.value.length > 1 &&
                            e.key !== 'ArrowDown' &&
                            e.key !== 'ArrowUp' &&
                            e.key !== 'ArrowLeft') {
                            monthRef.current?.select();
                        }
                        if (e.key === 'ArrowRight') {
                            monthRef.current?.select();
                        }
                    }, onFocus: () => setFocusField('dayFocus'), onBlur: () => setFocusField('') }),
                react_1.default.createElement("input", { type: "number", style: { maxWidth: 40, border: '1px solid purple' }, ref: monthRef, value: month, onChange: (e) => {
                        if (+e.target.value < 1 || +e.target.value > 12) {
                            setMonth(1);
                        }
                        else {
                            setMonth(+e.target.value);
                        }
                    }, onKeyDown: (e) => {
                        if (e.key === 'Backspace') {
                            setMonth('');
                        }
                        if (e.key === 'ArrowDown' && +e.currentTarget.value < 1) {
                            setMonth(13);
                            setYear(year);
                            setDay(day);
                        }
                    }, onKeyUp: (e) => {
                        if (+e.key > 1 && +e.currentTarget.value > 1) {
                            yearRef.current?.select();
                        }
                        if (e.currentTarget.value.length > 1 &&
                            e.key !== 'ArrowDown' &&
                            e.key !== 'ArrowUp' &&
                            e.key !== 'ArrowLeft') {
                            yearRef.current?.select();
                        }
                        if (e.key === 'ArrowRight') {
                            yearRef.current?.select();
                        }
                        if (e.key === 'ArrowLeft') {
                            dayRef.current?.focus();
                            dayRef.current?.select();
                        }
                    }, onFocus: () => setFocusField('monthFocus'), onBlur: () => setFocusField('') }),
                react_1.default.createElement("input", { type: "number", style: { maxWidth: 40, border: '1px solid green' }, ref: yearRef, value: year, onChange: (e) => {
                        if (day === 29 && month === 2) {
                            // Set year to schikkeljaar
                            console.log('leap year 🐸');
                        }
                        else {
                            setYear(+e.target.value);
                        }
                    }, onKeyDown: (e) => {
                        if (day === 29 && month === 2 && e.key === 'ArrowUp') {
                            setYear(year + 4);
                        }
                        if (day === 29 && month === 2 && e.key === 'ArrowDown') {
                            setYear(year - 4);
                        }
                        if (e.key === 'Backspace') {
                            setYear('');
                        }
                    }, onKeyUp: (e) => {
                        if (e.key === 'ArrowLeft') {
                            monthRef.current?.select();
                        }
                    }, onFocus: () => setFocusField('yearFocus'), onBlur: () => setFocusField('') })),
            react_1.default.createElement(Popover.Anchor, { asChild: true },
                react_1.default.createElement("div", { ref: inputRef },
                    react_1.default.createElement(inlines_1.styled.div, { style: {
                            border: '2px solid transparent',
                        } },
                        react_1.default.createElement(inlines_1.styled.div, { style: {
                                display: 'flex',
                                alignItems: 'center',
                                cursor: 'pointer',
                                height: '40px',
                                padding: '0px 12px',
                                gap: 2,
                                mindWidth: '296px',
                                borderRadius: '8px',
                                border: `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralNormal')}`,
                                '&:hover': {
                                    border: `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralHover')}`,
                                },
                                [utils_1.BpTablet]: {
                                    '&:hover': null,
                                },
                                '&:active': {
                                    border: `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralActive')}`,
                                },
                                '&:focus': {
                                    border: `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralSelected')}`,
                                },
                                ...style,
                            }, onClick: (e) => {
                                e.preventDefault();
                                setOpen(true);
                                // openPicker(e)
                            } },
                            react_1.default.createElement(icons_1.IconCalendar, { style: { marginRight: 8 } }),
                            numbered ? (react_1.default.createElement(react_1.default.Fragment, null,
                                react_1.default.createElement(components_1.Text, { style: {
                                        padding: '0px 1px',
                                        fontSize: 14,
                                        backgroundColor: focusField === 'dayFocus'
                                            ? (0, varsUtilities_1.color)('action', 'neutral', 'subtleActive')
                                            : '',
                                        borderRadius: 4,
                                        ...hover,
                                    }, onClick: () => {
                                        dayRef.current?.focus();
                                        dayRef.current?.select();
                                    } }, day === '' ? 'dd' : day < 10 ? `0${day}` : day),
                                react_1.default.createElement(components_1.Text, null, "/"),
                                react_1.default.createElement(components_1.Text, { style: {
                                        padding: '0px 1px',
                                        fontSize: 14,
                                        backgroundColor: focusField === 'monthFocus'
                                            ? (0, varsUtilities_1.color)('action', 'neutral', 'subtleActive')
                                            : '',
                                        borderRadius: 4,
                                        ...hover,
                                    }, onClick: () => {
                                        monthRef.current?.focus();
                                        monthRef.current?.select();
                                    } }, month === '' ? 'mm' : month < 10 ? `0${month}` : month),
                                react_1.default.createElement(components_1.Text, null, "/"),
                                react_1.default.createElement(components_1.Text, { style: {
                                        fontSize: 14,
                                        padding: '0px 1px',
                                        backgroundColor: focusField === 'yearFocus'
                                            ? (0, varsUtilities_1.color)('action', 'neutral', 'subtleActive')
                                            : '',
                                        borderRadius: 4,
                                        ...hover,
                                    }, onClick: () => {
                                        yearRef.current?.focus();
                                        yearRef.current?.select();
                                    } }, year === '' ? 'yyyy' : year))) : (react_1.default.createElement(react_1.default.Fragment, null,
                                react_1.default.createElement(components_1.Text, { style: {
                                        padding: '0px 1px',
                                        fontSize: 14,
                                        marginRight: '2px',
                                        backgroundColor: focusField === 'monthFocus'
                                            ? (0, varsUtilities_1.color)('action', 'neutral', 'subtleActive')
                                            : '',
                                        borderRadius: 4,
                                        ...hover,
                                    }, onClick: () => {
                                        monthRef.current?.focus();
                                        monthRef.current?.select();
                                    } }, month === '' ? 'mm' : DateRangeDoubleInput_1.monthArr[month - 1]),
                                react_1.default.createElement(components_1.Text, { style: {
                                        padding: '0px 1px',
                                        fontSize: 14,
                                        backgroundColor: focusField === 'dayFocus'
                                            ? (0, varsUtilities_1.color)('action', 'neutral', 'subtleActive')
                                            : '',
                                        borderRadius: 4,
                                        ...hover,
                                    }, onClick: () => {
                                        dayRef.current?.focus();
                                        dayRef.current?.select();
                                    } },
                                    day === '' ? 'dd' : day < 10 ? `0${day}` : day,
                                    ","),
                                react_1.default.createElement(components_1.Text, { style: {
                                        fontSize: 14,
                                        padding: '0px 1px',
                                        backgroundColor: focusField === 'yearFocus'
                                            ? (0, varsUtilities_1.color)('action', 'neutral', 'subtleActive')
                                            : '',
                                        borderRadius: 4,
                                        ...hover,
                                    }, onClick: () => {
                                        yearRef.current?.focus();
                                        yearRef.current?.select();
                                    } }, year === '' ? 'yyyy' : year))),
                            react_1.default.createElement(inlines_1.styled.div, { style: {
                                    display: 'flex',
                                    flexShrink: 0,
                                    paddingLeft: 8,
                                    flexDirection: 'row',
                                    marginLeft: 'auto',
                                } },
                                react_1.default.createElement(icons_1.IconChevronDown, { color: "default", style: {
                                        '&:hover': {
                                            backgroundColor: (0, varsUtilities_1.color)('action', 'system', 'hover'),
                                        },
                                        [utils_1.BpTablet]: {
                                            '&:hover': null,
                                        },
                                        '&:active': {
                                            backgroundColor: (0, varsUtilities_1.color)('action', 'system', 'active'),
                                        },
                                    } })))),
                    time && (react_1.default.createElement(NewTimeInput_1.NewTimeInput, { timeString: timeString, setTimeString: setTimeString, style: { marginLeft: 8 } })))),
            react_1.default.createElement(Popover.Portal, null,
                react_1.default.createElement(Popover.Content
                // asChild
                , { 
                    // asChild
                    onInteractOutside: (e) => {
                        setOpen(false);
                    }, onOpenAutoFocus: (e) => {
                        e.preventDefault();
                    }, onCloseAutoFocus: (e) => {
                        e.preventDefault();
                    }, sideOffset: 8, style: {
                        border: `1px solid ${(0, varsUtilities_1.color)('border', 'default', 'strong')}`,
                        boxShadow: `0px 3px 16px 1px rgba(0,0,0,0.05)`,
                        borderRadius: 4,
                    } },
                    react_1.default.createElement(Picker_1.Picker, { setOpen: setOpen, setValue: setValue, timeString: timeString, stringToMilliseconds: stringToMilliseconds }))))));
};
exports.NewDateInput = NewDateInput;
//# sourceMappingURL=NewDateInput.js.map