import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { LoadingButton } from '@mui/lab';
import { Alert, Box, FormGroup, Paper, TextField, Typography } from '@mui/material';
import { styled } from '@mui/material/styles';
import { useThemeProps } from '@mui/system';
import { SCPreferences, useSCPreferences } from '@selfcommunity/react-core';
import classNames from 'classnames';
import { useCallback, useState } from 'react';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import { LIVE_STREAM_DESCRIPTION_MAX_LENGTH, LIVE_STREAM_TITLE_MAX_LENGTH, LIVE_STREAM_SLUG_MAX_LENGTH } from '../../constants/LiveStream';
import { LIVESTREAM_DEFAULT_SETTINGS, PREFIX } from './constants';
import UploadEventCover from '../EventForm/UploadEventCover';
import LiveStreamSettingsForm from './LiveStreamFormSettings';
import { formatHttpErrorCode, LiveStreamService } from '@selfcommunity/api-services';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { Logger } from '@selfcommunity/utils';
const classes = {
    root: `${PREFIX}-root`,
    form: `${PREFIX}-form`,
    title: `${PREFIX}-title`,
    cover: `${PREFIX}-cover`,
    slug: `${PREFIX}-slug`,
    description: `${PREFIX}-description`,
    content: `${PREFIX}-content`,
    actions: `${PREFIX}-actions`,
    error: `${PREFIX}-error`,
    genericError: `${PREFIX}-generic-error`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'Root'
})(({ theme }) => ({}));
const messages = defineMessages({
    title: {
        id: 'ui.liveStreamForm.title.placeholder',
        defaultMessage: 'ui.liveStreamForm.title.placeholder'
    },
    slug: {
        id: 'ui.liveStreamForm.slug.placeholder',
        defaultMessage: 'ui.liveStreamForm.slug.placeholder'
    },
    description: {
        id: 'ui.liveStreamForm.description.placeholder',
        defaultMessage: 'ui.liveStreamForm.description.placeholder'
    }
});
/**
 *> API documentation for the Community-JS LiveStreamForm component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {LiveStreamForm} from '@selfcommunity/react-ui';
 ```

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

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCLiveStreamForm-root|Styles applied to the root element.|
 |title|.SCLiveStreamForm-title|Styles applied to the title element.|
 |cover|.SCLiveStreamForm-cover|Styles applied to the cover field.|
 |form|.SCLiveStreamForm-form|Styles applied to the form element.|
 |name|.SCLiveStreamForm-name|Styles applied to the name field.|
 |description|.SCLiveStreamForm-description|Styles applied to the description field.|
 |content|.SCLiveStreamForm-content|Styles applied to the  element.|
 |error|.SCLiveStreamForm-error|Styles applied to the error elements.|

 * @param inProps
 */
export default function LiveStreamForm(inProps) {
    var _a, _b, _c;
    //PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, onSuccess, onError, liveStream = null } = props, rest = __rest(props, ["className", "onSuccess", "onError", "liveStream"]);
    // INTL
    const intl = useIntl();
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const initialFieldState = {
        title: (liveStream === null || liveStream === void 0 ? void 0 : liveStream.title) || '',
        description: (liveStream === null || liveStream === void 0 ? void 0 : liveStream.description) || '',
        slug: (liveStream === null || liveStream === void 0 ? void 0 : liveStream.slug) || '',
        settings: (liveStream === null || liveStream === void 0 ? void 0 : liveStream.settings) || LIVESTREAM_DEFAULT_SETTINGS,
        cover: (liveStream === null || liveStream === void 0 ? void 0 : liveStream.cover) || '',
        coverFile: (liveStream === null || liveStream === void 0 ? void 0 : liveStream.cover) || '',
        isSubmitting: false
    };
    // STATE
    const [field, setField] = useState(initialFieldState);
    const [error, setError] = useState({});
    const [genericError, setGenericError] = useState(null);
    // PREFERENCES
    const scPreferences = useSCPreferences();
    const _backgroundCover = Object.assign({}, (field.cover
        ? { background: `url('${field.cover}') center / cover` }
        : { background: `url('${scPreferences.preferences[SCPreferences.IMAGES_USER_DEFAULT_COVER].value}') center / cover` }));
    const handleChangeCover = useCallback((cover) => {
        setField((prev) => (Object.assign(Object.assign({}, prev), { ['coverFile']: cover })));
        const reader = new FileReader();
        reader.onloadend = () => {
            setField((prev) => (Object.assign(Object.assign({}, prev), { ['cover']: reader.result })));
        };
        reader.readAsDataURL(cover);
        if (error.coverError) {
            delete error.coverError;
            setError(error);
        }
    }, [error]);
    const handleSubmit = useCallback(() => {
        setField((prev) => (Object.assign(Object.assign({}, prev), { ['isSubmitting']: true })));
        setGenericError(null);
        const formData = new FormData();
        if (field.coverFile) {
            formData.append('cover', field.coverFile);
        }
        formData.append('title', field.title);
        formData.append('description', field.description);
        formData.append('slug', field.slug);
        formData.append('settings', JSON.stringify(field.settings));
        let liveStreamService;
        if (liveStream) {
            liveStreamService = LiveStreamService.update(liveStream.id, formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
        }
        else {
            liveStreamService = LiveStreamService.create(formData, { headers: { 'Content-Type': 'multipart/form-data' } });
        }
        liveStreamService
            .then((data) => {
            setField((prev) => (Object.assign(Object.assign({}, prev), { ['isSubmitting']: false })));
            onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(data);
        })
            .catch((e) => {
            const _error = formatHttpErrorCode(e);
            // eslint-disable-next-line @typescript-eslint/ban-ts-ignore,@typescript-eslint/ban-ts-comment
            // @ts-ignore
            console.log(_error);
            if ('errorsError' in _error) {
                setGenericError(intl.formatMessage({
                    id: 'ui.liveStreamForm.error.monthlyMinuteLimitReached',
                    defaultMessage: 'ui.liveStreamForm.error.monthlyMinuteLimitReached'
                }));
            }
            else {
                setGenericError(null);
            }
            let __errors = {};
            if ('coverError' in _error) {
                __errors = Object.assign(Object.assign({}, __errors), { ['coverError']: _jsx(FormattedMessage, { id: "ui.liveStreamForm.cover.error.invalid", defaultMessage: "ui.liveStreamForm.cover.error.invalid" }) });
            }
            if ('titleError' in _error) {
                __errors = Object.assign(Object.assign({}, __errors), { ['titleError']: _jsx(FormattedMessage, { id: "ui.liveStreamForm.title.error.invalid", defaultMessage: "ui.liveStreamForm.title.error.invalid" }) });
            }
            if ('slugError' in _error) {
                __errors = Object.assign(Object.assign({}, __errors), { ['slugError']: _jsx(FormattedMessage, { id: "ui.liveStreamForm.slug.error.invalid", defaultMessage: "ui.liveStreamForm.slug.error.invalid" }) });
            }
            setError(__errors);
            setField((prev) => (Object.assign(Object.assign({}, prev), { ['isSubmitting']: false })));
            Logger.error(SCOPE_SC_UI, e);
            onError === null || onError === void 0 ? void 0 : onError(e);
        });
    }, [field, onSuccess, onError]);
    const handleChange = useCallback((event) => {
        const { name, value } = event.target;
        setField((prev) => (Object.assign(Object.assign({}, prev), { [name]: value })));
        if (error[`${name}Error`]) {
            delete error[`${name}Error`];
            setError(error);
        }
        setGenericError(null);
    }, [error, setGenericError]);
    const handleChangeSettings = useCallback((data) => {
        setField((prev) => (Object.assign(Object.assign({}, prev), { settings: data })));
    }, [setField]);
    /**
     * Renders root object
     */
    return (_jsxs(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: [_jsx(Paper, Object.assign({ style: _backgroundCover, classes: { root: classes.cover } }, { children: _jsx(UploadEventCover, { isCreationMode: true, onChange: handleChangeCover }) })), Boolean(error['coverError']) && _jsx(Typography, Object.assign({ color: "error" }, { children: error['coverError'] })), _jsxs(FormGroup, Object.assign({ className: classes.form }, { children: [_jsx(TextField, { required: true, className: classes.title, placeholder: `${intl.formatMessage(messages.title)}`, margin: "normal", value: field.title, name: "title", onChange: handleChange, InputProps: {
                            endAdornment: _jsx(Typography, Object.assign({ variant: "body2" }, { children: LIVE_STREAM_TITLE_MAX_LENGTH - field.title.length }))
                        }, error: Boolean(field.title.length > LIVE_STREAM_TITLE_MAX_LENGTH) || Boolean(error['titleError']), helperText: field.title.length > LIVE_STREAM_TITLE_MAX_LENGTH ? (_jsx(FormattedMessage, { id: "ui.liveStreamForm.title.error.maxLength", defaultMessage: "ui.liveStreamForm.title.error.maxLength" })) : error['titleError'] ? (error['titleError']) : null }), _jsx(TextField, { required: true, className: classes.slug, placeholder: `${intl.formatMessage(messages.slug)}`, margin: "normal", value: field.slug, name: "slug", onChange: handleChange, InputProps: {
                            endAdornment: _jsx(Typography, Object.assign({ variant: "body2" }, { children: LIVE_STREAM_SLUG_MAX_LENGTH - field.title.length }))
                        }, error: Boolean(field.slug.length > LIVE_STREAM_SLUG_MAX_LENGTH) || Boolean(error['slugError']), helperText: field.title.length > LIVE_STREAM_SLUG_MAX_LENGTH ? (_jsx(FormattedMessage, { id: "ui.liveStreamForm.slug.error.maxLength", defaultMessage: "ui.liveStreamForm.slug.error.maxLength" })) : error['slugError'] ? (error['slugError']) : null }), _jsx(TextField, { multiline: true, rows: 4, className: classes.description, placeholder: `${intl.formatMessage(messages.description)}`, margin: "normal", value: field.description, name: "description", onChange: handleChange, InputProps: {
                            endAdornment: (_jsx(Typography, Object.assign({ variant: "body2" }, { children: ((_a = field.description) === null || _a === void 0 ? void 0 : _a.length) ? LIVE_STREAM_DESCRIPTION_MAX_LENGTH - field.description.length : LIVE_STREAM_DESCRIPTION_MAX_LENGTH })))
                        }, error: Boolean(((_b = field.description) === null || _b === void 0 ? void 0 : _b.length) > LIVE_STREAM_DESCRIPTION_MAX_LENGTH), helperText: ((_c = field.description) === null || _c === void 0 ? void 0 : _c.length) > LIVE_STREAM_DESCRIPTION_MAX_LENGTH ? (_jsx(FormattedMessage, { id: "ui.liveStreamForm.description.error.maxLength", defaultMessage: "ui.liveStreamForm.description.error.maxLength" })) : null }), _jsx(LiveStreamSettingsForm, { settings: field.settings, onChange: handleChangeSettings }), genericError && (_jsx(Box, Object.assign({ className: classes.genericError }, { children: _jsx(Alert, Object.assign({ variant: "filled", severity: "error" }, { children: genericError })) }))), _jsx(Box, Object.assign({ className: classes.actions }, { children: _jsx(LoadingButton, Object.assign({ loading: field.isSubmitting, disabled: !field.title ||
                                Object.keys(error).length !== 0 ||
                                Boolean(genericError) ||
                                field.title.length > LIVE_STREAM_TITLE_MAX_LENGTH ||
                                field.description.length > LIVE_STREAM_DESCRIPTION_MAX_LENGTH, variant: "contained", onClick: handleSubmit, color: "secondary" }, { children: liveStream ? (_jsx(FormattedMessage, { id: "ui.liveStreamForm.button.edit", defaultMessage: "ui.liveStreamForm.button.edit" })) : (_jsx(FormattedMessage, { id: "ui.liveStreamForm.button.create", defaultMessage: "ui.liveStreamForm.button.create" })) })) }))] }))] })));
}
