"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.TillRangePicker = void 0;
const react_1 = __importStar(require("react"));
const icons_1 = require("../../icons");
const ContextState_1 = require("../../hooks/ContextState");
const RangeCalendar_1 = require("./RangeCalendar");
const varsUtilities_1 = require("../../varsUtilities");
const inlines_1 = require("inlines");
const components_1 = require("../../components");
const StyledDatePickerBox = (0, inlines_1.styled)('div', {
    background: (0, varsUtilities_1.color)('background', 'default', 'strong'),
    borderRadius: 4,
    width: 280,
    // height: 396,
});
const StyledChevronHolders = (0, inlines_1.styled)('div', {
    borderRadius: 4,
    height: 24,
    width: 24,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    '@media (hover: hover)': {
        '&:hover': {
            background: (0, varsUtilities_1.color)('action', 'neutral', 'subtleHover'),
            cursor: 'pointer',
        },
    },
});
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const months = [
    '',
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
];
const MscToString = (value) => {
    const newDate = new Date(value);
    const year = newDate.getFullYear();
    const month = newDate.getMonth() < 9
        ? '0' + (newDate.getMonth() + 1)
        : newDate.getMonth() + 1;
    const day = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate();
    return `${day}/${month}/${year}`;
};
// const stringToMilliseconds = (str: string, time?: string): number => {
//   const dateString = `${str?.split('/').reverse().join('-')}T${time || '00:00'}`
//   const outputMs = new Date(dateString).getTime()
//   return outputMs
// }
const TillRangePicker = ({ setOpen, setValue, timeString, stringToMilliseconds, }) => {
    const [millisecondsValue] = (0, ContextState_1.useContextState)('tillValue');
    (0, react_1.useEffect)(() => {
        const newMillSecVal = MscToString(millisecondsValue);
        setSelectedDay(newMillSecVal.split('/')[0]);
        setSelectedMonth(newMillSecVal.split('/')[1]);
        setSelectedYear(newMillSecVal.split('/')[2]);
    }, [millisecondsValue]);
    const [valueAsString, setValueAsString] = (0, react_1.useState)(millisecondsValue ? MscToString(millisecondsValue) : '');
    const [selectedDay, setSelectedDay] = (0, react_1.useState)(valueAsString?.split('/')[0]);
    const [selectedMonth, setSelectedMonth] = (0, react_1.useState)(valueAsString?.split('/')[1]);
    const [selectedYear, setSelectedYear] = (0, react_1.useState)(valueAsString?.split('/')[2]);
    const daysInMonth = (month, year) => {
        return new Date(year, month, 0).getDate();
    };
    // So if year, day or month changes set the new Value 🔥
    (0, react_1.useEffect)(() => {
        setValueAsString(`${selectedDay}/${selectedMonth}/${selectedYear}`);
        setValue(
        //TODO type this?
        //@ts-ignore
        stringToMilliseconds(`${selectedDay}/${selectedMonth}/${selectedYear}`, timeString));
    }, [selectedDay, selectedMonth, selectedYear, valueAsString]);
    // Days forward or backward
    const dayChanger = (str) => {
        if (str === 'forward') {
            if (+selectedDay === daysInMonth(+selectedMonth, +selectedYear)) {
                if (+selectedMonth === 12) {
                    setSelectedDay('01');
                    setSelectedMonth('01');
                    setSelectedYear((+selectedYear + 1).toString());
                }
                else {
                    monthChanger('forward');
                    setSelectedDay('01');
                }
            }
            else
                setSelectedDay(+selectedDay + 1 < 10
                    ? '0' + (+selectedDay + 1).toString()
                    : (+selectedDay + 1).toString());
        }
        if (str === 'backward') {
            if (selectedDay === '01' || +selectedDay === 1) {
                if (selectedMonth === '01' || +selectedMonth === 1) {
                    setSelectedDay(daysInMonth(12, +selectedYear - 1).toString());
                    setSelectedMonth('12');
                    setSelectedYear((+selectedYear - 1).toString());
                }
                else {
                    monthChanger('backward');
                    setSelectedDay(daysInMonth(+selectedMonth - 1, selectedYear).toString());
                }
            }
            else {
                setSelectedDay(+selectedDay - 1 < 10
                    ? '0' + (+selectedDay - 1).toString()
                    : (+selectedDay - 1).toString());
            }
        }
    };
    // Months forward or backward
    const monthChanger = (str) => {
        if (str === 'forward') {
            if (selectedMonth === `12` || +selectedMonth === 12) {
                setSelectedMonth('01');
                setSelectedYear((+selectedYear + 1).toString());
            }
            else {
                setSelectedMonth(+selectedMonth === 9
                    ? '10'
                    : +selectedMonth < 9
                        ? '0' + (+selectedMonth + 1).toString()
                        : (+selectedMonth + 1).toString());
            }
        }
        if (str === 'backward') {
            if (selectedMonth === `01` || +selectedMonth === 1) {
                setSelectedMonth('12');
                setSelectedYear((+selectedYear - 1).toString());
            }
            else {
                setSelectedMonth(+selectedMonth < 11
                    ? '0' + (+selectedMonth - 1).toString()
                    : (+selectedMonth - 1).toString());
            }
        }
    };
    return (react_1.default.createElement(StyledDatePickerBox, null,
        react_1.default.createElement(inlines_1.styled.div, { style: {
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                padding: '16px',
            } },
            react_1.default.createElement(components_1.Text, { weight: "strong" }, (months[+valueAsString?.split('/')[1]] || '') +
                ' ' +
                (valueAsString?.split('/')[2] || '')),
            react_1.default.createElement(inlines_1.styled.div, { style: { display: 'flex' } },
                react_1.default.createElement(StyledChevronHolders, { onClick: () => monthChanger('backward'), style: { marginRight: 16 } },
                    react_1.default.createElement(icons_1.IconChevronTop, null)),
                react_1.default.createElement(StyledChevronHolders, { onClick: () => monthChanger('forward') },
                    react_1.default.createElement(icons_1.IconChevronDown, null)))),
        react_1.default.createElement(RangeCalendar_1.RangeCalendar, { days: days, selectedDay: selectedDay, setSelectedDay: setSelectedDay, selectedMonth: selectedMonth, selectedYear: selectedYear, tillRangeCal: true }),
        react_1.default.createElement(inlines_1.styled.div, { style: {
                padding: '8px 16px',
                display: 'flex',
                flexDirection: 'column',
                gap: '2px',
                '@media (hover: hover)': {
                    '& div': {
                        cursor: 'pointer',
                        // height: '16px',
                        padding: '8px 12px',
                        alignItems: 'center',
                        borderRadius: '8px',
                        '&:hover': {
                            backgroundColor: (0, varsUtilities_1.color)('action', 'system', 'hover'),
                        },
                        '&:active': {
                            backgroundColor: (0, varsUtilities_1.color)('action', 'system', 'active'),
                        },
                    },
                },
            } },
            react_1.default.createElement(components_1.Text, { onClick: () => {
                    setValue(new Date().getTime());
                }, style: { display: 'flex' } }, "Today"),
            react_1.default.createElement(components_1.Text, { style: { display: 'flex' }, onClick: () => dayChanger('forward') }, "Select next date"),
            react_1.default.createElement(components_1.Text, { style: { display: 'flex', marginBottom: '6px' }, onClick: () => dayChanger('backward') }, "Select previous date"),
            react_1.default.createElement(inlines_1.styled.span, { style: {
                    borderTop: `1px solid ${(0, varsUtilities_1.color)('border', 'default', 'strong')}`,
                    height: 0,
                    margin: '0 -8px',
                    borderRadius: 0,
                    padding: 0,
                } }),
            react_1.default.createElement(components_1.Text, { style: { display: 'flex', marginTop: '6px' }, onClick: () => {
                    setValue(0);
                    setOpen(false);
                } }, "Clear"))));
};
exports.TillRangePicker = TillRangePicker;
//# sourceMappingURL=TillRangePicker.js.map