import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import classNames from 'classnames';
import { useState } from 'react';
import { get24HoursLater, getBrowserTimezone, getNow, getTimezoneFromIsoDate, } from '../../../lib/dates.js';
import { useGenerateAccessCodeCode } from '../../../lib/seam/access-codes/use-generate-access-code-code.js';
import { AccessCodeFormDatePicker } from '../../../lib/ui/AccessCodeForm/AccessCodeFormDatePicker.js';
import { AccessCodeFormTimes } from '../../../lib/ui/AccessCodeForm/AccessCodeFormTimes.js';
import { AccessCodeFormTimezonePicker } from '../../../lib/ui/AccessCodeForm/AccessCodeFormTimezonePicker.js';
import { Button } from '../../../lib/ui/Button.js';
import { FormField } from '../../../lib/ui/FormField.js';
import { InputLabel } from '../../../lib/ui/InputLabel.js';
import { ContentHeader } from '../../../lib/ui/layout/ContentHeader.js';
import { RadioField } from '../../../lib/ui/RadioField/RadioField.js';
import { TextField } from '../../../lib/ui/TextField/TextField.js';
import { useToggle } from '../../../lib/ui/use-toggle.js';
export function AccessCodeForm({ className, ...props }) {
    return (_jsx("div", { className: classNames('seam-access-code-form', className), children: _jsx(Content, { ...props }) }));
}
function Content({ onBack, accessCode, device, onSubmit, isSubmitting, codeError, }) {
    const [name, setName] = useState(accessCode?.name ?? '');
    const [code, setCode] = useState(accessCode?.code ?? '');
    const [type, setType] = useState(accessCode?.type ?? 'ongoing');
    const [datePickerVisible, setDatePickerVisible] = useState(false);
    const [timezone, setTimezone] = useState(getAccessCodeTimezone(accessCode) ?? getBrowserTimezone());
    const [startDate, setStartDate] = useState(getAccessCodeDate('starts_at', accessCode) ?? getNow());
    const [endDate, setEndDate] = useState(getAccessCodeDate('ends_at', accessCode) ?? get24HoursLater());
    const [timezonePickerVisible, toggleTimezonePicker] = useToggle();
    const { isLoading: isGeneratingCode, mutate: generateCode } = useGenerateAccessCodeCode();
    const submit = () => {
        if (isSubmitting) {
            return;
        }
        onSubmit({
            name,
            code,
            type,
            device,
            startDate,
            endDate,
            timezone,
        });
    };
    if (timezonePickerVisible) {
        return (_jsx(AccessCodeFormTimezonePicker, { value: timezone, onChange: setTimezone, onClose: toggleTimezonePicker }));
    }
    if (datePickerVisible) {
        return (_jsx(AccessCodeFormDatePicker, { startDate: startDate, setStartDate: setStartDate, endDate: endDate, setEndDate: setEndDate, timezone: timezone, onChangeTimezone: toggleTimezonePicker, onBack: () => {
                setDatePickerVisible(false);
            } }));
    }
    const nameError = name.length > 60 ? t.overCharacterLimitError : undefined;
    const isFormValid = name.trim().length > 0 &&
        nameError === undefined &&
        code.trim().length > 0 &&
        !isSubmitting;
    const title = accessCode == null ? t.addNewAccessCode : t.editAccessCode;
    const handleGenerateCode = () => {
        generateCode({
            device_id: device.device_id,
        }, {
            onSuccess: ({ code: generatedCode }) => {
                if (generatedCode != null) {
                    setCode(generatedCode);
                }
            },
        });
    };
    return (_jsxs(_Fragment, { children: [_jsx(ContentHeader, { title: title, subheading: device.properties.name, onBack: onBack }), _jsxs("div", { className: 'seam-main', children: [_jsxs(FormField, { children: [_jsx(InputLabel, { children: t.nameInputLabel }), _jsx(TextField, { size: 'large', clearable: true, value: name, onChange: setName, hasError: nameError != null, helperText: nameError })] }), _jsxs(FormField, { className: 'seam-code-field', children: [_jsx(InputLabel, { children: t.codeInputLabel }), _jsx(TextField, { size: 'large', clearable: true, value: code, onChange: setCode, hasError: codeError != null, helperText: codeError ?? undefined }), _jsx("div", { className: 'seam-bottom', children: _jsx(Button, { size: 'small', onMouseDown: (e) => {
                                        e.preventDefault(); // Disable stealing input focus
                                        handleGenerateCode();
                                    }, disabled: isGeneratingCode, children: t.codeGenerateButton }) })] }), _jsxs(FormField, { children: [_jsx(InputLabel, { children: t.timingInputLabel }), _jsx(RadioField, { value: type, onChange: setType, name: 'type', options: [
                                    {
                                        label: t.typeOngoingLabel,
                                        value: 'ongoing',
                                    },
                                    {
                                        label: t.typeTimeBoundLabel,
                                        value: 'time_bound',
                                    },
                                ] }), _jsx(_Fragment, { children: type === 'time_bound' && (_jsx(AccessCodeFormTimes, { startDate: startDate, endDate: endDate, onEdit: () => {
                                        setDatePickerVisible(true);
                                    } })) })] }), _jsxs("div", { className: 'seam-actions', children: [_jsx(Button, { onClick: onBack, children: t.cancel }), _jsx(Button, { variant: 'solid', disabled: !isFormValid, onMouseDown: submit, children: t.save })] })] })] }));
}
function getAccessCodeTimezone(accessCode) {
    if (accessCode == null) {
        return undefined;
    }
    if (accessCode.type === 'ongoing') {
        return undefined;
    }
    const date = accessCode.starts_at;
    const timezone = getTimezoneFromIsoDate(date);
    if (timezone == null) {
        return undefined;
    }
    return timezone;
}
function getAccessCodeDate(date, accessCode) {
    if (accessCode == null) {
        return undefined;
    }
    if (accessCode.type !== 'time_bound') {
        return undefined;
    }
    return accessCode[date];
}
const t = {
    addNewAccessCode: 'Add new access code',
    editAccessCode: 'Edit access code',
    overCharacterLimitError: '60 characters max',
    nameInputLabel: 'Name the new code',
    codeGenerateButton: 'Generate code',
    codeInputLabel: 'Enter the code (PIN)',
    cancel: 'Cancel',
    save: 'Save',
    timingInputLabel: 'Timing',
    typeOngoingLabel: 'Ongoing',
    typeTimeBoundLabel: 'Start/end times',
};
//# sourceMappingURL=AccessCodeForm.js.map