import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import classNames from 'classnames';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { compareByCreatedAtDesc } from '../../../../lib/dates.js';
import { AddIcon } from '../../../../lib/icons/Add.js';
import { useDevice } from '../../../../lib/index.js';
import { useAccessCodes } from '../../../../lib/seam/access-codes/use-access-codes.js';
import { NestedAccessCodeDetails } from '../../../../lib/seam/components/AccessCodeDetails/AccessCodeDetails.js';
import { AccessCodeHealthBar, } from '../../../../lib/seam/components/AccessCodeTable/AccessCodeHealthBar.js';
import { AccessCodeRow } from '../../../../lib/seam/components/AccessCodeTable/AccessCodeRow.js';
import { withRequiredCommonProps, } from '../../../../lib/seam/components/common-props.js';
import { NestedCreateAccessCodeForm } from '../../../../lib/seam/components/CreateAccessCodeForm/CreateAccessCodeForm.js';
import { NestedEditAccessCodeForm } from '../../../../lib/seam/components/EditAccessCodeForm/EditAccessCodeForm.js';
import { useComponentTelemetry } from '../../../../lib/telemetry/index.js';
import { IconButton } from '../../../../lib/ui/IconButton.js';
import { ContentHeader } from '../../../../lib/ui/layout/ContentHeader.js';
import { LoadingToast } from '../../../../lib/ui/LoadingToast/LoadingToast.js';
import { Snackbar } from '../../../../lib/ui/Snackbar/Snackbar.js';
import { EmptyPlaceholder } from '../../../../lib/ui/Table/EmptyPlaceholder.js';
import { TableBody } from '../../../../lib/ui/Table/TableBody.js';
import { TableHeader } from '../../../../lib/ui/Table/TableHeader.js';
import { TableTitle } from '../../../../lib/ui/Table/TableTitle.js';
import { SearchTextField } from '../../../../lib/ui/TextField/SearchTextField.js';
import { Caption } from '../../../../lib/ui/typography/Caption.js';
import { useToggle } from '../../../../lib/ui/use-toggle.js';
export const NestedAccessCodeTable = withRequiredCommonProps(AccessCodeTable);
export function AccessCodeTable({ deviceId, disableSearch = false, onAccessCodeClick = () => { }, preventDefaultOnAccessCodeClick = false, onBack, accessCodeFilter = defaultAccessCodeFilter, accessCodeComparator = compareByCreatedAtDesc, errorFilter = () => true, warningFilter = () => true, heading = t.accessCodes, className, disableCreateAccessCode = false, disableEditAccessCode = false, disableLockUnlock = false, disableDeleteAccessCode = false, disableResourceIds = false, disableConnectedAccountInformation = false, }) {
    useComponentTelemetry('AccessCodeTable');
    const { accessCodes, isInitialLoading, isError, refetch } = useAccessCodes({
        device_id: deviceId,
    });
    const { device } = useDevice({
        device_id: deviceId,
    });
    const [selectedViewAccessCodeId, setSelectedViewAccessCodeId] = useState(null);
    const [searchInputValue, setSearchInputValue] = useState('');
    const [addAccessCodeFormVisible, toggleAddAccessCodeForm] = useToggle();
    const [selectedEditAccessCodeId, setSelectedEditAccessCodeId] = useState(null);
    const filteredAccessCodes = useMemo(() => accessCodes
        ?.filter((accessCode) => accessCodeFilter(accessCode, searchInputValue))
        ?.sort(accessCodeComparator) ?? [], [accessCodes, searchInputValue, accessCodeFilter, accessCodeComparator]);
    const handleAccessCodeClick = useCallback((accessCodeId) => {
        onAccessCodeClick(accessCodeId);
        if (preventDefaultOnAccessCodeClick)
            return;
        setSelectedViewAccessCodeId(accessCodeId);
    }, [
        onAccessCodeClick,
        preventDefaultOnAccessCodeClick,
        setSelectedViewAccessCodeId,
    ]);
    const handleAccessCodeEdit = useCallback((accessCodeId) => {
        setSelectedEditAccessCodeId(accessCodeId);
    }, [setSelectedEditAccessCodeId]);
    const [accessCodeResult, setAccessCodeResult] = useState(null);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const handleAccessCodeDeleteSuccess = useCallback(() => {
        setAccessCodeResult('deleted');
    }, [setAccessCodeResult]);
    // Circumvent Snackbar bug that causes it to switch to default message
    // while the dismiss animation is playing
    useEffect(() => {
        if (accessCodeResult !== null) {
            setSnackbarMessage(accessCodeResultToMessage(accessCodeResult));
        }
    }, [accessCodeResult]);
    if (device == null) {
        return _jsx(_Fragment, {});
    }
    if (selectedEditAccessCodeId != null) {
        return (_jsx(NestedEditAccessCodeForm, { accessCodeId: selectedEditAccessCodeId, errorFilter: errorFilter, warningFilter: warningFilter, disableLockUnlock: disableLockUnlock, disableCreateAccessCode: disableCreateAccessCode, disableEditAccessCode: disableEditAccessCode, disableDeleteAccessCode: disableDeleteAccessCode, disableResourceIds: disableResourceIds, disableConnectedAccountInformation: disableConnectedAccountInformation, onBack: () => {
                setSelectedEditAccessCodeId(null);
            }, onSuccess: () => {
                setAccessCodeResult('updated');
            }, className: className }));
    }
    if (selectedViewAccessCodeId != null) {
        return (_jsx(NestedAccessCodeDetails, { accessCodeId: selectedViewAccessCodeId, errorFilter: errorFilter, warningFilter: warningFilter, disableLockUnlock: disableLockUnlock, disableCreateAccessCode: disableCreateAccessCode, disableEditAccessCode: disableEditAccessCode, disableDeleteAccessCode: disableDeleteAccessCode, disableResourceIds: disableResourceIds, disableConnectedAccountInformation: disableConnectedAccountInformation, onBack: () => {
                setSelectedViewAccessCodeId(null);
            }, className: className }));
    }
    if (addAccessCodeFormVisible) {
        return (_jsx(NestedCreateAccessCodeForm, { deviceId: deviceId, errorFilter: errorFilter, warningFilter: warningFilter, disableLockUnlock: disableLockUnlock, disableCreateAccessCode: disableCreateAccessCode, disableEditAccessCode: disableEditAccessCode, disableDeleteAccessCode: disableDeleteAccessCode, disableResourceIds: disableResourceIds, disableConnectedAccountInformation: disableConnectedAccountInformation, onBack: toggleAddAccessCodeForm, className: className, onSuccess: () => {
                setAccessCodeResult('created');
            } }));
    }
    return (_jsxs(_Fragment, { children: [_jsx(Snackbar, { variant: 'success', message: snackbarMessage, visible: accessCodeResult != null, autoDismiss: true, onClose: () => {
                    setAccessCodeResult(null);
                } }), _jsxs("div", { className: classNames('seam-table', className), children: [_jsx(ContentHeader, { onBack: onBack }), _jsxs(TableHeader, { children: [_jsxs("div", { className: 'seam-left', children: [heading != null ? (_jsxs(TableTitle, { children: [heading, " ", _jsxs(Caption, { children: ["(", filteredAccessCodes.length, ")"] })] })) : (_jsx("div", { className: 'seam-fragment' })), !disableCreateAccessCode &&
                                        (device.properties.online_access_codes_enabled === true ||
                                            device.can_program_online_access_codes === true) && (_jsx(IconButton, { onClick: toggleAddAccessCodeForm, className: 'seam-add-button', children: _jsx(AddIcon, {}) }))] }), _jsx("div", { className: 'seam-table-header-loading-wrap', children: _jsx(LoadingToast, { isLoading: isInitialLoading, label: t.loading, top: -20 }) }), !disableSearch && (_jsx(SearchTextField, { value: searchInputValue, onChange: setSearchInputValue, disabled: (accessCodes?.length ?? 0) === 0 }))] }), _jsx(TableBody, { children: _jsx(Content, { accessCodes: filteredAccessCodes, onAccessCodeClick: handleAccessCodeClick, onAccessCodeEdit: handleAccessCodeEdit, onAccessCodeDeleteSuccess: handleAccessCodeDeleteSuccess, errorFilter: errorFilter, warningFilter: warningFilter, disableEditAccessCode: disableEditAccessCode, disableDeleteAccessCode: disableDeleteAccessCode }) }), _jsx(Snackbar, { variant: 'error', visible: isError, message: t.fallbackErrorMessage, action: {
                            label: t.tryAgain,
                            onClick: () => {
                                void refetch();
                            },
                        }, disableCloseButton: true })] })] }));
}
function Content(props) {
    const { accessCodes, onAccessCodeClick, onAccessCodeEdit, onAccessCodeDeleteSuccess, errorFilter, warningFilter, disableEditAccessCode, disableDeleteAccessCode, } = props;
    const [filter, setFilter] = useState(null);
    const filteredAccessCodes = useMemo(() => {
        if (filter === null) {
            return accessCodes;
        }
        if (filter === 'access_code_issues') {
            return accessCodes.filter((accessCode) => {
                return accessCode.errors.length > 0 || accessCode.warnings.length > 0;
            });
        }
        return accessCodes;
    }, [accessCodes, filter]);
    if (accessCodes.length === 0) {
        return _jsx(EmptyPlaceholder, { children: t.noAccessCodesMessage });
    }
    return (_jsxs(_Fragment, { children: [_jsx(AccessCodeHealthBar, { accessCodes: accessCodes, filter: filter, onFilterSelect: setFilter, errorFilter: errorFilter, warningFilter: warningFilter }), filteredAccessCodes.map((accessCode) => (_jsx(AccessCodeRow, { accessCode: accessCode, onClick: () => {
                    onAccessCodeClick(accessCode.access_code_id);
                }, disableEditAccessCode: disableEditAccessCode, disableDeleteAccessCode: disableDeleteAccessCode, onEdit: () => {
                    onAccessCodeEdit(accessCode.access_code_id);
                }, onDeleteSuccess: () => {
                    onAccessCodeDeleteSuccess(accessCode.access_code_id);
                } }, accessCode.access_code_id)))] }));
}
const defaultAccessCodeFilter = (accessCode, searchInputValue) => {
    const value = searchInputValue.trim().toLowerCase();
    if (value === '')
        return true;
    const name = accessCode.name ?? '';
    const code = accessCode.code ?? '';
    return (name.trim().toLowerCase().includes(value) ||
        code.trim().toLowerCase().includes(value));
};
const accessCodeResultToMessage = (result) => {
    if (result === 'created')
        return t.accessCodeCreated;
    if (result === 'deleted')
        return t.accessCodeDeleted;
    return t.accessCodeUpdated;
};
const t = {
    accessCodes: 'Access Codes',
    noAccessCodesMessage: 'Sorry, no access codes were found',
    loading: 'Loading access codes',
    accessCodeUpdated: 'Access code updated',
    accessCodeCreated: 'Access code created',
    accessCodeDeleted: 'Access code is being removed',
    tryAgain: 'Try again',
    fallbackErrorMessage: 'Access codes could not be loaded',
};
//# sourceMappingURL=AccessCodeTable.js.map