import React, { useEffect, useState } from "react";
import { Checkbox } from "../../../common/Checkbox";
import { TimeSelect } from "../../../common/TimeSelect";
import DefaultDropdownButton from "../../../shared/DefaultDropdownButton";
import { FinsembleToggleButtonBar } from "../../../common/FinsembleToggleButtonBar";
import { UserPreferencesStore } from "../../stores/UserPreferencesStore";
const DEFAULT_TIME = {
    hour: 4,
    minute: 0,
    meridiem: "AM",
};
export const ScheduledClose = (props) => {
    var _a;
    const [initialized, setInitialized] = useState(false);
    const [enabled, setEnabled] = useState(false);
    const [weekly, setWeekly] = useState(false);
    const [scheduledClose, setScheduledClose] = useState(DEFAULT_TIME);
    const [day, setDay] = useState(false);
    const dayChanged = (dayValue) => {
        setDay(Number.parseInt(dayValue, 10));
    };
    const setDefaultState = () => {
        setInitialized(false);
        setEnabled(false);
        setWeekly(false);
        setScheduledClose(DEFAULT_TIME);
        setDay(false);
    };
    // To keep the consistent UI of the General Tab resets the component state to default when user reset preferences
    useEffect(() => {
        UserPreferencesStore === null || UserPreferencesStore === void 0 ? void 0 : UserPreferencesStore.addListener({ field: "resetToDefault" }, setDefaultState);
        return () => {
            UserPreferencesStore === null || UserPreferencesStore === void 0 ? void 0 : UserPreferencesStore.removeListener({ field: "resetToDefault" }, setDefaultState);
        };
    }, []);
    const dayOptions = [];
    const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    for (let k in DAYS) {
        dayOptions.push({
            optionLabel: DAYS[k],
            optionValue: k,
            clickHandler: () => {
                dayChanged(k);
            },
        });
    }
    /**
     * Toggle the enabled state of the select boxes.
     */
    const toggleEnabled = () => {
        const toggled = !enabled;
        // If the select boxes are no longer enabled, reset the scheduled restart time and call a method on the Actions object.
        // That function will set scheduledRestart to null via the preferences API. But we want our display to look nice, hence the bit where we reset it to the default value.
        setEnabled(toggled);
    };
    const onTimeSelectChange = (time) => {
        setScheduledClose(time);
    };
    /**
     * Add listener on the store. When the preferences field changes, we change our local state.
     * Also, get the initial state from the store.
     */
    useEffect(() => {
        props.getPreferences((err, data) => {
            var _a;
            if (data) {
                let configValue = data[props.configKey];
                const isEnabled = typeof configValue === "object";
                let preferencesDay = false;
                if (isEnabled) {
                    preferencesDay = (_a = configValue.dayOfWeek) !== null && _a !== void 0 ? _a : false;
                    configValue.meridiem = configValue.hour > 11 ? "PM" : "AM";
                }
                else {
                    configValue = DEFAULT_TIME;
                }
                setDay(preferencesDay);
                setWeekly(preferencesDay !== false);
                setEnabled(isEnabled);
                setScheduledClose(configValue);
                // This is a hack to prevent preferences from being saved back from initialization
                setTimeout(() => {
                    setInitialized(true);
                }, 500);
            }
        });
    }, []);
    const getSchedule = () => {
        let returnValue = false;
        if (enabled) {
            returnValue = { ...scheduledClose };
            if (weekly) {
                returnValue.dayOfWeek = day ? day : 0;
            }
            else {
                delete returnValue.dayOfWeek;
            }
        }
        return returnValue;
    };
    useEffect(() => {
        if (initialized) {
            props.setPreferences(props.configKey, getSchedule());
        }
    }, [scheduledClose, weekly, enabled, day]);
    return (React.createElement("div", { className: "complex-menu-content-row", style: { overflow: "visible" } },
        React.createElement("div", { className: "close-toggle-container" },
            React.createElement(Checkbox, { onClick: toggleEnabled, checked: enabled, label: props.label }),
            React.createElement(FinsembleToggleButtonBar, { selected: !weekly, options: [
                    {
                        label: "Daily",
                        value: true,
                    },
                    {
                        label: "Weekly",
                        value: false,
                    },
                ], onChange: (value) => {
                    // Day represents the day of the week, and is false when irrelevant.
                    // Here, we only ever set it to false. The day number comes from the dropdown below.
                    if (!value) {
                        setDay(false);
                    }
                    setWeekly(!value);
                }, enabled: enabled })),
        weekly && (React.createElement("div", { className: `time-selectors daily-select ${enabled ? "" : "disabled"}` },
            React.createElement("div", { className: "daily-select-label", "aria-label": "Day" }, "Day:"),
            React.createElement("div", { className: "daily-select-dropdown" },
                React.createElement(DefaultDropdownButton, { key: `${day}`, buttonOptions: dayOptions, classNames: "push-right", allowEmpty: false, caretLocation: "right", enabled: enabled, buttonLabel: `${(_a = dayOptions[day ? day : 0]) === null || _a === void 0 ? void 0 : _a.optionLabel}`, defaultSelection: dayOptions[day ? day : 0] })))),
        React.createElement("div", { className: "time-selectors" },
            React.createElement(TimeSelect, { key: `${scheduledClose.hour}${scheduledClose.minute}${scheduledClose.meridiem}`, enabled: enabled, initialTime: scheduledClose, onChange: onTimeSelectChange }))));
};
export default ScheduledClose;
//# sourceMappingURL=ScheduledClose.js.map