import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import { debounce } from '../../../../lib/debounce.js';
import { CheckBlackIcon } from '../../../../lib/icons/CheckBlack.js';
import { ChevronWideIcon } from '../../../../lib/icons/ChevronWide.js';
import { NestedClimateSettingScheduleTable } from '../../../../lib/seam/components/ClimateSettingScheduleTable/ClimateSettingScheduleTable.js';
import { DeviceInfo } from '../../../../lib/seam/components/DeviceDetails/DeviceInfo.js';
import { useClimateSettingSchedules } from '../../../../lib/seam/thermostats/climate-setting-schedules/use-climate-setting-schedules.js';
import { useCoolThermostat } from '../../../../lib/seam/thermostats/use-cool-thermostat.js';
import { useHeatCoolThermostat } from '../../../../lib/seam/thermostats/use-heat-cool-thermostat.js';
import { useHeatThermostat } from '../../../../lib/seam/thermostats/use-heat-thermostat.js';
import { useSetThermostatOff } from '../../../../lib/seam/thermostats/use-set-thermostat-off.js';
import { useUpdateFanMode } from '../../../../lib/seam/thermostats/use-update-fan-mode.js';
import { useUpdateThermostat } from '../../../../lib/seam/thermostats/use-update-thermostat.js';
import { getSupportedThermostatModes } from '../../../../lib/temperature-bounds.js';
import { AccordionRow } from '../../../../lib/ui/layout/AccordionRow.js';
import { ContentHeader } from '../../../../lib/ui/layout/ContentHeader.js';
import { DetailRow } from '../../../../lib/ui/layout/DetailRow.js';
import { DetailSection } from '../../../../lib/ui/layout/DetailSection.js';
import { DetailSectionGroup } from '../../../../lib/ui/layout/DetailSectionGroup.js';
import { Snackbar } from '../../../../lib/ui/Snackbar/Snackbar.js';
import { Switch } from '../../../../lib/ui/Switch/Switch.js';
import { ClimateModeMenu } from '../../../../lib/ui/thermostat/ClimateModeMenu.js';
import { ClimateSettingStatus } from '../../../../lib/ui/thermostat/ClimateSettingStatus.js';
import { FanModeMenu } from '../../../../lib/ui/thermostat/FanModeMenu.js';
import { TemperatureControlGroup } from '../../../../lib/ui/thermostat/TemperatureControlGroup.js';
import { ThermostatCard } from '../../../../lib/ui/thermostat/ThermostatCard.js';
export function ThermostatDeviceDetails({ device, errorFilter, warningFilter, disableLockUnlock, disableCreateAccessCode, disableEditAccessCode, disableDeleteAccessCode, disableResourceIds, disableConnectedAccountInformation, disableClimateSettingSchedules, onBack, className, }) {
    const [climateSettingsOpen, setClimateSettingsOpen] = useState(false);
    const { climateSettingSchedules } = useClimateSettingSchedules({
        device_id: device.device_id,
    });
    if (climateSettingsOpen) {
        return (_jsx(NestedClimateSettingScheduleTable, { deviceId: device.device_id, errorFilter: errorFilter, warningFilter: warningFilter, disableLockUnlock: disableLockUnlock, disableCreateAccessCode: disableCreateAccessCode, disableEditAccessCode: disableEditAccessCode, disableDeleteAccessCode: disableDeleteAccessCode, disableResourceIds: disableResourceIds, disableConnectedAccountInformation: disableConnectedAccountInformation, disableClimateSettingSchedules: disableClimateSettingSchedules, onBack: () => {
                setClimateSettingsOpen(false);
            }, className: className }));
    }
    if (device == null) {
        return null;
    }
    const climateSettingSchedulesLabel = climateSettingSchedules?.length !== 1
        ? t.climateSchedules
        : t.climateSchedule;
    return (_jsxs("div", { className: classNames('seam-device-details', className), children: [_jsx(ContentHeader, { title: t.thermostat, onBack: onBack }), _jsxs("div", { className: 'seam-body', children: [_jsx(ThermostatCard, { device: device }), _jsx("div", { className: 'seam-thermostat-device-details', children: _jsxs(DetailSectionGroup, { children: [!disableClimateSettingSchedules && (_jsx(DetailSection, { label: t.scheduledClimates, tooltipContent: t.scheduledClimatesTooltip, children: _jsx(DetailRow, { label: climateSettingSchedules == null
                                            ? t.viewingClimateSchedules
                                            : `${climateSettingSchedules.length} ${climateSettingSchedulesLabel}`, onClick: () => {
                                            setClimateSettingsOpen(true);
                                        }, children: _jsx("div", { className: 'seam-detail-row-rotated-icon', children: _jsx(ChevronWideIcon, {}) }) }) })), _jsxs(DetailSection, { label: t.currentSettings, tooltipContent: t.currentSettingsTooltip, children: [_jsx(ClimateSettingRow, { device: device }), _jsx(FanModeRow, { device: device })] }), !disableClimateSettingSchedules && (_jsxs(DetailSection, { label: t.defaultSettings, tooltipContent: t.defaultSettingsTooltip, children: [_jsx(DetailRow, { label: t.defaultClimate, children: device.properties.default_climate_setting != null ? (_jsx(ClimateSettingStatus, { climateSetting: device.properties.default_climate_setting, temperatureUnit: 'fahrenheit', iconPlacement: 'right' })) : (_jsx("p", { children: t.none })) }), _jsx(ManualOverrideRow, { device: device })] })), _jsx(DeviceInfo, { device: device, disableConnectedAccountInformation: disableConnectedAccountInformation, disableResourceIds: disableResourceIds })] }) })] })] }));
}
function ManualOverrideRow({ device, }) {
    const { mutate, isSuccess, isError } = useUpdateThermostat();
    return (_jsxs(_Fragment, { children: [_jsx("div", { className: 'seam-detail-row-wrap', children: _jsx(DetailRow, { label: t.allowManualOverride, children: _jsx(Switch, { checked: device.properties.default_climate_setting
                            ?.manual_override_allowed ?? true, onChange: (checked) => {
                            mutate({
                                device_id: device.device_id,
                                default_climate_setting: {
                                    manual_override_allowed: checked,
                                },
                            });
                        } }) }) }), _jsx(Snackbar, { message: t.manualOverrideSuccess, variant: 'success', visible: isSuccess, automaticVisibility: true }), _jsx(Snackbar, { message: t.manualOverrideError, variant: 'error', visible: isError, automaticVisibility: true })] }));
}
function FanModeRow({ device }) {
    const { mutate, isSuccess, isError } = useUpdateFanMode();
    return (_jsxs(_Fragment, { children: [_jsx("div", { className: 'seam-detail-row-wrap', children: _jsx(DetailRow, { label: t.fanMode, children: _jsx(FanModeMenu, { mode: device.properties.fan_mode_setting, onChange: (fanMode) => {
                            mutate({
                                device_id: device.device_id,
                                fan_mode_setting: fanMode,
                            });
                        } }) }) }), _jsx(Snackbar, { message: t.fanModeSuccess, variant: 'success', visible: isSuccess, automaticVisibility: true, autoDismiss: true }), _jsx(Snackbar, { message: t.fanModeError, variant: 'error', visible: isError, automaticVisibility: true })] }));
}
function ClimateSettingRow({ device, }) {
    const deviceHeatValue = device.properties.current_climate_setting.heating_set_point_fahrenheit;
    const deviceCoolValue = device.properties.current_climate_setting.cooling_set_point_fahrenheit;
    const supportedModes = getSupportedThermostatModes(device);
    const [showSuccess, setShowSuccess] = useState(false);
    const [mode, setMode] = useState((supportedModes.includes('heat_cool') ? 'heat_cool' : supportedModes[0]) ??
        'off');
    const [heatValue, setHeatValue] = useState(device.properties.current_climate_setting.heating_set_point_fahrenheit ?? 0);
    const [coolValue, setCoolValue] = useState(device.properties.current_climate_setting.cooling_set_point_fahrenheit ?? 0);
    const { mutate: heatCoolThermostat, isSuccess: isHeatCoolSuccess, isError: isHeatCoolError, } = useHeatCoolThermostat();
    const { mutate: heatThermostat, isSuccess: isHeatSuccess, isError: isHeatError, } = useHeatThermostat();
    const { mutate: coolThermostat, isSuccess: isCoolSuccess, isError: isCoolError, } = useCoolThermostat();
    const { mutate: setThermostatOff, isSuccess: isSetOffSuccess, isError: isSetOffError, } = useSetThermostatOff();
    useEffect(() => {
        const handler = debounce(() => {
            switch (mode) {
                case 'heat_cool':
                    heatCoolThermostat({
                        device_id: device.device_id,
                        heating_set_point_fahrenheit: heatValue,
                        cooling_set_point_fahrenheit: coolValue,
                    });
                    break;
                case 'heat':
                    heatThermostat({
                        device_id: device.device_id,
                        heating_set_point_fahrenheit: heatValue,
                    });
                    break;
                case 'cool':
                    coolThermostat({
                        device_id: device.device_id,
                        cooling_set_point_fahrenheit: coolValue,
                    });
                    break;
                case 'off':
                    setThermostatOff({
                        device_id: device.device_id,
                    });
                    break;
            }
        }, 2000);
        if (heatValue !== deviceHeatValue ||
            coolValue !== deviceCoolValue ||
            mode === 'off') {
            handler();
        }
        return () => {
            handler.cancel();
        };
    }, [
        heatValue,
        coolValue,
        mode,
        deviceHeatValue,
        deviceCoolValue,
        device,
        heatThermostat,
        coolThermostat,
        heatCoolThermostat,
        setThermostatOff,
    ]);
    useEffect(() => {
        if (isHeatCoolSuccess ||
            isHeatSuccess ||
            isCoolSuccess ||
            isSetOffSuccess) {
            setShowSuccess(true);
            const timeout = globalThis.setTimeout(() => {
                setShowSuccess(false);
            }, 3000);
            return () => {
                globalThis.clearTimeout(timeout);
            };
        }
        return () => { };
    }, [isHeatCoolSuccess, isHeatSuccess, isCoolSuccess, isSetOffSuccess]);
    return (_jsxs(_Fragment, { children: [_jsx(AccordionRow, { label: t.climate, leftContent: _jsxs("div", { className: classNames('seam-thermostat-mutation-status', {
                        'is-visible': showSuccess,
                    }), children: [_jsx("div", { className: 'seam-thermostat-mutation-status-icon', children: _jsx(CheckBlackIcon, {}) }), _jsx("div", { className: 'seam-thermostat-mutation-status-label', children: t.saved })] }), rightCollapsedContent: _jsx(ClimateSettingStatus, { climateSetting: device.properties.current_climate_setting, temperatureUnit: 'fahrenheit', iconPlacement: 'right' }), children: _jsxs("div", { className: 'seam-detail-row-end-alignment', children: [mode !== 'off' && (_jsx(TemperatureControlGroup, { mode: mode, heatValue: heatValue, coolValue: coolValue, onHeatValueChange: setHeatValue, onCoolValueChange: setCoolValue, delta: Number('min_heating_cooling_delta_fahrenheit' in device.properties &&
                                device.properties.min_heating_cooling_delta_fahrenheit) ?? 0 })), _jsx(ClimateModeMenu, { mode: mode, onChange: setMode, supportedModes: supportedModes })] }) }), _jsx(Snackbar, { message: t.climateSettingError, variant: 'error', visible: isHeatCoolError || isHeatError || isCoolError || isSetOffError, automaticVisibility: true })] }));
}
const t = {
    thermostat: 'Thermostat',
    climateSchedule: 'scheduled climate',
    climateSchedules: 'scheduled climates',
    viewingClimateSchedules: 'View scheduled climates',
    scheduledClimates: 'Scheduled climates',
    scheduledClimatesTooltip: "Scheduled climates let you automatically change the thermostat's climate at a set time.",
    currentSettings: 'Current settings',
    currentSettingsTooltip: 'These are the settings currently on the device. If you change them here, they change on the device.',
    climate: 'Climate',
    fanMode: 'Fan mode',
    defaultSettings: 'Default settings',
    defaultSettingsTooltip: 'When a scheduled climate reaches its end time, the default settings will kick in.',
    defaultClimate: 'Default climate',
    allowManualOverride: 'Allow manual override',
    none: 'None',
    fanModeSuccess: 'Successfully updated fan mode!',
    fanModeError: 'Error updating fan mode. Please try again.',
    manualOverrideSuccess: 'Successfully updated manual override!',
    manualOverrideError: 'Error updating manual override. Please try again.',
    climateSettingError: 'Error updating climate setting. Please try again.',
    saved: 'Saved',
};
//# sourceMappingURL=ThermostatDeviceDetails.js.map