import { jsx as _jsx } from "react/jsx-runtime";
import { useState } from 'react';
import { useComponentTelemetry } from '../../../../lib/telemetry/index.js';
import { createIsoDate } from '../../../../lib/dates.js';
import { useCreateAccessCode } from '../../../../lib/seam/access-codes/use-create-access-code.js';
import { withRequiredCommonProps, } from '../../../../lib/seam/components/common-props.js';
import { useDevice } from '../../../../lib/seam/devices/use-device.js';
import { getValidationError } from '../../../../lib/seam/error-handlers.js';
import { AccessCodeForm, } from '../../../../lib/ui/AccessCodeForm/AccessCodeForm.js';
export const NestedCreateAccessCodeForm = withRequiredCommonProps(CreateAccessCodeForm);
export function CreateAccessCodeForm({ className, onBack, deviceId, }) {
    useComponentTelemetry('CreateAccessCodeForm');
    const { device } = useDevice({
        device_id: deviceId,
    });
    if (device == null) {
        return null;
    }
    return _jsx(Content, { device: device, className: className, onBack: onBack });
}
function Content({ device, className, onBack, }) {
    const { submit, isSubmitting, codeError } = useSubmitCreateAccessCode({
        onSuccess: () => {
            if (onBack != null) {
                onBack();
            }
        },
    });
    return (_jsx(AccessCodeForm, { device: device, className: className, onBack: onBack, onSubmit: submit, isSubmitting: isSubmitting, codeError: codeError }));
}
function useSubmitCreateAccessCode(params) {
    const { onSuccess } = params;
    const { mutate, isLoading: isSubmitting } = useCreateAccessCode();
    const [codeError, setCodeError] = useState(null);
    const handleError = (error) => {
        const codeError = getValidationError({ error, property: 'code' });
        if (codeError != null) {
            setCodeError(codeError);
        }
    };
    const submit = (data) => {
        setCodeError(null);
        const { name, code, type, device, startDate, endDate, timezone } = data;
        if (name === '') {
            return;
        }
        if (isSubmitting) {
            return;
        }
        if (type === 'time_bound') {
            mutate({
                name,
                code,
                device_id: device.device_id,
                starts_at: createIsoDate(startDate, timezone),
                ends_at: createIsoDate(endDate, timezone),
            }, {
                onSuccess,
                onError: handleError,
            });
            return;
        }
        mutate({
            name,
            code,
            device_id: device.device_id,
        }, {
            onSuccess,
            onError: handleError,
        });
    };
    return { submit, isSubmitting, codeError };
}
//# sourceMappingURL=CreateAccessCodeForm.js.map