import { __awaiter, __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Box, CircularProgress, Typography } from '@mui/material';
import { styled } from '@mui/material/styles';
import { useThemeProps } from '@mui/system';
import { useSCPreferences, useSCUser } from '@selfcommunity/react-core';
import classNames from 'classnames';
import { FormattedMessage, useIntl } from 'react-intl';
import { PREFIX } from './constants';
import { PreJoin } from '@livekit/components-react';
import { useCallback, useMemo, useState } from 'react';
import LiveStreamVideoConference from './LiveStreamVideoConference';
import '@livekit/components-styles';
import { generateRoomId } from '../../utils/liveStream';
const classes = {
    root: `${PREFIX}-root`,
    content: `${PREFIX}-content`,
    title: `${PREFIX}-title`,
    description: `${PREFIX}-description`,
    startPrejoinContent: `${PREFIX}-start-prejoin-content`,
    preJoin: `${PREFIX}-prejoin`,
    preJoinLoading: `${PREFIX}-prejoin-loading`,
    prejoinLoader: `${PREFIX}-prejoin-loader`,
    endPrejoinContent: `${PREFIX}-end-prejoin-content`,
    conference: `${PREFIX}-conference`,
    error: `${PREFIX}-error`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'Root'
})(({ theme }) => ({}));
/**
 *> API documentation for the Community-JS LiveStreamRoom component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {LiveStreamRoom} from '@selfcommunity/react-ui';
 ```

 #### Component Name
 The name `LiveStreamRoom` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCLiveStreamRoom-root|Styles applied to the root element.|
 |title|.SCLiveStreamRoom-title|Styles applied to the title element.|
 |description|.SCLiveStreamRoom-description|Styles applied to the description element.|
 |content|.SCLiveStreamRoom-content|Styles applied to the content.|
 |prejoin|.SCLiveStreamRoom-prejoin|Styles applied to the prejoin.|
 |conference|.SCLiveStreamRoom-conference|Styles applied to the conference.|
 |error|.SCLiveStreamRoom-error|Styles applied to the error elements.|

 * @param inProps
 */
export default function LiveStreamRoom(inProps) {
    var _a;
    //PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, liveStream = null, showPrejoinTitle = true, showPrejoinDescription = false, startPrejoinContent, endPrejoinContent, connectionDetailsEndpoint, presetConnectionDetails, presetPreJoinChoices, LiveStreamVideoConferenceComponentProps = {} } = props, rest = __rest(props, ["className", "liveStream", "showPrejoinTitle", "showPrejoinDescription", "startPrejoinContent", "endPrejoinContent", "connectionDetailsEndpoint", "presetConnectionDetails", "presetPreJoinChoices", "LiveStreamVideoConferenceComponentProps"]);
    // CONTEXT
    const scUserContext = useSCUser();
    const { preferences, features } = useSCPreferences();
    // INTL
    const intl = useIntl();
    // STATE
    const [preJoinChoices, setPreJoinChoices] = useState(presetPreJoinChoices);
    const [loading, setLoading] = useState(false);
    const preJoinDefaults = useMemo(() => {
        var _a;
        return {
            username: ((_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.username) || '',
            videoEnabled: true,
            audioEnabled: true
        };
    }, [scUserContext.user]);
    const [connectionDetails, setConnectionDetails] = useState(presetConnectionDetails);
    const liveStreamEnabled = true;
    /* const liveStreamEnabled = useMemo(
          () =>
              preferences &&
              features &&
              features.includes(SCFeatureName.LIVE_STREAM) &&
              SCPreferences.CONFIGURATIONS_LIVE_STREAM_ENABLED in preferences &&
              preferences[SCPreferences.CONFIGURATIONS_LIVE_STREAM_ENABLED].value,
          [preferences, features]
      ); */
    const canCreateLiveStream = useMemo(() => true /* scUserContext?.user?.permission?.create_livestream */, [(_a = scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) === null || _a === void 0 ? void 0 : _a.permission]);
    const toggleAttrDisabledPrejoinActions = useCallback((disabled) => {
        const container = document.querySelector('.lk-prejoin');
        if (container) {
            const buttons = container.querySelectorAll('button.lk-button');
            buttons.forEach((button) => {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                button.disabled = disabled;
            });
        }
    }, []);
    // HANDLERS
    /**
     * Handle PreJoin Submit
     */
    const handlePreJoinSubmit = useCallback((values) => __awaiter(this, void 0, void 0, function* () {
        var _b;
        // eslint-disable-next-line no-constant-condition
        if ((liveStream || true) && connectionDetailsEndpoint) {
            setLoading(true);
            toggleAttrDisabledPrejoinActions(true);
            setPreJoinChoices(values);
            const url = new URL(connectionDetailsEndpoint, window.location.origin);
            url.searchParams.append('roomName', liveStream.roomName || generateRoomId());
            url.searchParams.append('participantName', (_b = scUserContext.user) === null || _b === void 0 ? void 0 : _b.username);
            /* if (liveStream && liveStream.region) {
              url.searchParams.append('region', liveStream.region);
            } */
            const connectionDetailsResp = yield fetch(url.toString());
            const connectionDetailsData = yield connectionDetailsResp.json();
            setConnectionDetails(connectionDetailsData);
            toggleAttrDisabledPrejoinActions(false);
            setLoading(false);
        }
    }), [scUserContext.user, connectionDetailsEndpoint, setPreJoinChoices, setConnectionDetails]);
    /**
     * Handle PreJoin Error
     */
    const handlePreJoinError = useCallback((e) => console.error(e), []);
    /**
     * User must be authenticated
     */
    if (!scUserContext.user || !liveStreamEnabled || !canCreateLiveStream) {
        return _jsx(CircularProgress, {});
    }
    /**
     * Renders root object
     */
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: _jsx(Box, Object.assign({ className: classes.content, "data-lk-theme": "default" }, { children: connectionDetails === undefined || preJoinChoices === undefined ? (_jsxs(_Fragment, { children: [startPrejoinContent && _jsx(Box, Object.assign({ className: classes.startPrejoinContent }, { children: startPrejoinContent })), (liveStream === null || liveStream === void 0 ? void 0 : liveStream.title) && (_jsx(Typography, Object.assign({ component: 'div', variant: "h5", className: classes.title }, { children: liveStream === null || liveStream === void 0 ? void 0 : liveStream.title }))), (liveStream === null || liveStream === void 0 ? void 0 : liveStream.description) && (_jsx(Typography, Object.assign({ component: 'div', variant: "body1", className: classes.description }, { children: liveStream === null || liveStream === void 0 ? void 0 : liveStream.description }))), _jsxs(Box, Object.assign({ className: classNames(classes.preJoin, { [classes.preJoinLoading]: loading }) }, { children: [_jsx(PreJoin, { persistUserChoices: true, defaults: preJoinDefaults, onSubmit: handlePreJoinSubmit, onError: handlePreJoinError }), loading && (_jsxs(Box, Object.assign({ className: classes.prejoinLoader }, { children: [_jsx(CircularProgress, {}), _jsx(Typography, Object.assign({ component: 'div', variant: "body2" }, { children: _jsx(FormattedMessage, { id: "ui.liveStreamRoom.connecting", defaultMessage: "ui.liveStreamRoom.connecting" }) }))] })))] })), _jsx(Box, Object.assign({ className: classes.endPrejoinContent }, { children: endPrejoinContent }))] })) : (_jsx(Box, Object.assign({ className: classes.conference }, { children: _jsx(LiveStreamVideoConference, Object.assign({ connectionDetails: connectionDetails, userChoices: preJoinChoices, options: { codec: props.codec, hq: props.hq } }, LiveStreamVideoConferenceComponentProps)) }))) })) })));
}
