import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useCallback, useEffect, useReducer, useRef, useState } from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import { useThemeProps } from '@mui/system';
import classNames from 'classnames';
import { Preferences } from '@selfcommunity/react-core';
import { PREFIX } from '../../constants';
import { Button, CircularProgress, Drawer, IconButton, Tab, Tabs, TextField, Typography } from '@mui/material';
import { MuiColorInput } from 'mui-color-input';
import { actionTypes } from './reducer';
import { getInitialState, reducer } from './reducer';
import { PreferenceService } from '@selfcommunity/api-services';
import { formatColorLabel, formatLogoLabel } from '../../../../utils/onBoarding';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import Icon from '@mui/material/Icon';
import { SCOPE_SC_UI } from '../../../../constants/Errors';
import { Logger } from '@selfcommunity/utils';
import { LoadingButton } from '@mui/lab';
import ScrollContainer from '../../../../shared/ScrollContainer';
const messages = defineMessages({
    titleField: {
        id: 'ui.onBoardingWidget.step.appearance.titleSlogan.field.title',
        defaultMessage: 'ui.onBoardingWidget.step.appearance.titleSlogan.field.title'
    },
    sloganField: {
        id: 'ui.onBoardingWidget.step.appearance.titleSlogan.field.slogan',
        defaultMessage: 'ui.onBoardingWidget.step.appearance.titleSlogan.field.slogan'
    }
});
const classes = {
    root: `${PREFIX}-appearance-root`,
    title: `${PREFIX}-appearance-title`,
    summary: `${PREFIX}-appearance-summary`,
    colorContainer: `${PREFIX}-appearance-color-container`,
    color: `${PREFIX}-appearance-color`,
    colorProgress: `${PREFIX}-appearance-color-progress`,
    logoContainer: `${PREFIX}-appearance-logo-container`,
    logo: `${PREFIX}-appearance-logo`,
    uploadButton: `${PREFIX}-appearance-upload-button`,
    drawerRoot: `${PREFIX}-appearance-drawer-root`,
    drawerHeader: `${PREFIX}-appearance-drawer-header`,
    drawerHeaderAction: `${PREFIX}-appearance-drawer-header-action`,
    drawerContent: `${PREFIX}-appearance-drawer-content`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'AppearanceRoot'
})(() => ({}));
const DrawerRoot = styled(Drawer, {
    name: PREFIX,
    slot: 'AppearanceDrawerRoot',
    overridesResolver: (props, styles) => styles.appearanceDrawerRoot
})(({ theme }) => ({}));
export default function Appearance(inProps) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, onCompleteAction } = props;
    // STATE
    const [state, dispatch] = useReducer(reducer, getInitialState(null));
    const [loadingLogo, setLoadingLogo] = useState('');
    const [anchorEl, setAnchorEl] = useState(null);
    const [tab, setTab] = useState(0);
    const [updating, setUpdating] = useState(false);
    const [updatingColor, setUpdatingColor] = useState('');
    const colorRef = useRef(null);
    // INTL
    const intl = useIntl();
    // HANDLERS
    const handleTabChange = (event, newValue) => {
        setTab(newValue);
    };
    const handleOpen = useCallback((event) => {
        setAnchorEl(event.currentTarget);
    }, []);
    const handleClose = useCallback(() => {
        setAnchorEl(null);
    }, []);
    const fetchColors = () => {
        dispatch({ type: actionTypes.LOADING, payload: { loading: true } });
        PreferenceService.searchPreferences('', '', `${Preferences.COLORS_COLORBACK},${Preferences.COLORS_COLORPRIMARY},${Preferences.COLORS_COLORSECONDARY},${Preferences.COLORS_NAVBARBACK},${Preferences.COLORS_COLORFONT},${Preferences.COLORS_COLORFONTSECONDARY}`)
            .then((res) => {
            dispatch({
                type: actionTypes.SET_COLORS,
                payload: {
                    loading: false,
                    colors: res.results
                }
            });
        })
            .catch((e) => {
            Logger.error(SCOPE_SC_UI, e);
            dispatch({ type: actionTypes.SET_COLORS, payload: { loading: false, colors: [] } });
        });
    };
    const fetchLogos = () => {
        dispatch({ type: actionTypes.LOADING, payload: { loading: true } });
        PreferenceService.searchPreferences('', '', `${Preferences.LOGO_NAVBAR_LOGO},${Preferences.LOGO_NAVBAR_LOGO_MOBILE}`)
            .then((res) => {
            dispatch({
                type: actionTypes.SET_LOGOS,
                payload: {
                    loading: false,
                    logos: res.results
                }
            });
        })
            .catch((e) => {
            Logger.error(SCOPE_SC_UI, e);
            dispatch({ type: actionTypes.SET_LOGOS, payload: { loading: false, logos: [] } });
        });
    };
    const fetchSlogans = () => {
        dispatch({ type: actionTypes.LOADING, payload: { loading: true } });
        PreferenceService.searchPreferences('', '', `${Preferences.TEXT_APPLICATION_SLOGAN1},${Preferences.TEXT_APPLICATION_SLOGAN2}`)
            .then((res) => {
            dispatch({
                type: actionTypes.SET_SLOGANS,
                payload: {
                    loading: false,
                    slogans: res.results
                }
            });
        })
            .catch((e) => {
            Logger.error(SCOPE_SC_UI, e);
            dispatch({ type: actionTypes.SET_SLOGANS, payload: { loading: false, slogans: [] } });
        });
    };
    const updatePreference = (preference) => __awaiter(this, void 0, void 0, function* () {
        try {
            yield PreferenceService.updatePreferences(preference);
        }
        catch (e) {
            Logger.error(SCOPE_SC_UI, e);
        }
        finally {
            setUpdating(false);
            setUpdatingColor('');
            onCompleteAction();
        }
    });
    const updateSlogans = () => __awaiter(this, void 0, void 0, function* () {
        setUpdating(true);
        try {
            yield Promise.all(state.slogans.map(({ name, value }) => {
                return updatePreference({ [name]: value });
            }));
        }
        catch (e) {
            Logger.error(SCOPE_SC_UI, e);
        }
        finally {
            setUpdating(false);
        }
    });
    const updateLogoPreference = (name, file) => __awaiter(this, void 0, void 0, function* () {
        setLoadingLogo(name);
        const formData = new FormData();
        formData.append(name, file);
        yield PreferenceService.updatePreferences(formData)
            .then((preference) => {
            setLoadingLogo('');
            dispatch({
                type: actionTypes.SET_LOGOS,
                payload: { logos: state.logos.map((l) => (l.name === name ? Object.assign(Object.assign({}, l), { value: preference[name].value }) : l)) }
            });
            onCompleteAction();
        })
            .catch((e) => {
            setLoadingLogo('');
            Logger.error(SCOPE_SC_UI, e);
        });
    });
    /**
     * Handles logo upload
     * @param event
     * @param name
     */
    const handleUpload = (event, name) => {
        const file = event.target.files[0];
        if (file) {
            updateLogoPreference(name, file);
        }
    };
    useEffect(() => {
        fetchColors();
        fetchLogos();
        fetchSlogans();
    }, []);
    // HANDLERS
    const handleColorChange = (color, name) => {
        setUpdatingColor(name);
        const currentColor = state.colors.find((col) => col.name === name);
        if (currentColor && currentColor.value !== color) {
            setUpdating(true);
            dispatch({
                type: actionTypes.SET_COLORS,
                payload: { colors: state.colors.map((col) => (col.name === name ? Object.assign(Object.assign({}, col), { value: color }) : col)) }
            });
            updatePreference({ [`${name}`]: color });
        }
    };
    const handleChange = (event) => {
        const { name, value } = event.target;
        dispatch({
            type: actionTypes.SET_SLOGANS,
            payload: { slogans: state.slogans.map((s) => (s.name === name ? Object.assign(Object.assign({}, s), { value: value }) : s)) }
        });
    };
    const handleClosePopover = () => {
        if (colorRef.current) {
            colorRef.current.blur();
        }
    };
    return (_jsxs(Root, Object.assign({ className: classNames(classes.root, className) }, { children: [_jsx(Typography, Object.assign({ variant: "h4", className: classes.title, alignSelf: "self-start" }, { children: _jsx(FormattedMessage, { id: "ui.onBoardingWidget.appearance", defaultMessage: "ui.onBoardingWidget.appearance" }) })), _jsx(Typography, Object.assign({ className: classes.summary }, { children: _jsx(FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.summary", defaultMessage: "ui.onBoardingWidget.step.appearance.summary" }) })), _jsx(Button, Object.assign({ variant: "outlined", size: "small", color: "primary", onClick: handleOpen }, { children: _jsx(FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.button", defaultMessage: "ui.onBoardingWidget.step.appearance.button" }) })), _jsxs(DrawerRoot, Object.assign({ className: classes.drawerRoot, anchor: "right", open: Boolean(anchorEl), onClose: handleClose }, { children: [_jsxs(Box, Object.assign({ className: classes.drawerHeader }, { children: [_jsx(Typography, Object.assign({ variant: "h4", color: "primary" }, { children: _jsx(FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.header.title", defaultMessage: "ui.onBoardingWidget.step.appearance.header.title" }) })), _jsx(IconButton, Object.assign({ className: classes.drawerHeaderAction, onClick: handleClose }, { children: _jsx(Icon, { children: "close" }) }))] })), _jsxs(Tabs, Object.assign({ value: tab, onChange: handleTabChange, variant: "scrollable", scrollButtons: "auto", "aria-label": "scrollable-tabs" }, { children: [_jsx(Tab, { label: _jsx(FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.colors.title", defaultMessage: "ui.onBoardingWidget.step.appearance.colors.title" }) }), _jsx(Tab, { label: _jsx(FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.logo.title", defaultMessage: "ui.onBoardingWidget.step.appearance.logo.title" }) }), _jsx(Tab, { label: _jsx(FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.titleSlogan.title", defaultMessage: "ui.onBoardingWidget.step.appearance.titleSlogan.title" }) })] })), _jsx(ScrollContainer, { children: _jsxs(Box, Object.assign({ className: classes.drawerContent }, { children: [tab === 0 && (_jsx(_Fragment, { children: state.colors.map((color) => (_jsxs(React.Fragment, { children: [_jsx(Typography, Object.assign({ variant: "h6" }, { children: formatColorLabel(color) })), _jsxs(Box, Object.assign({ className: classes.colorContainer }, { children: [_jsx(MuiColorInput, { inputRef: colorRef, className: classes.color, format: "hex", value: color.value, onChange: (newColor) => handleColorChange(newColor, color.name), isAlphaHidden: true, PopoverProps: { onClose: handleClosePopover } }), updatingColor && updatingColor === color.name && (_jsx(CircularProgress, { className: classes.colorProgress, color: "secondary", size: 24 }))] }))] }, color.id))) })), tab === 1 && (_jsx(_Fragment, { children: state.logos.map((logo) => (_jsxs(React.Fragment, { children: [_jsx(Typography, Object.assign({ variant: "h6" }, { children: formatLogoLabel(logo.name) })), _jsxs(Box, Object.assign({ className: classes.logoContainer }, { children: [_jsx("img", { src: logo.value, className: classes.logo }), _jsx("input", { type: "file", onChange: (event) => handleUpload(event, logo.name), hidden: true, accept: ".gif,.png,.jpg,.jpeg", id: logo.name }), _jsx(LoadingButton, Object.assign({ className: classes.uploadButton, onClick: () => document.getElementById(`${logo.name}`).click(), loading: Boolean(loadingLogo) && Boolean(logo.name === loadingLogo), disabled: Boolean(loadingLogo) && Boolean(logo.name !== loadingLogo) }, { children: _jsx(Icon, { children: "upload" }) }))] }))] }, logo.id))) })), tab === 2 && (_jsxs(Box, { children: [_jsx(TextField, { multiline: true, fullWidth: true, 
                                            //className={classes.field}
                                            label: `${intl.formatMessage(messages.titleField)}`, margin: "normal", value: (_a = state === null || state === void 0 ? void 0 : state.slogans[0]) === null || _a === void 0 ? void 0 : _a.value, name: "application_slogan1", onChange: handleChange, InputProps: {
                                                endAdornment: _jsx(Typography, Object.assign({ variant: "body2" }, { children: ((_b = state.slogans[0].value) === null || _b === void 0 ? void 0 : _b.length) ? 50 - ((_c = state.slogans[0].value) === null || _c === void 0 ? void 0 : _c.length) : 50 }))
                                            }, error: Boolean(((_e = (_d = state === null || state === void 0 ? void 0 : state.slogans[0]) === null || _d === void 0 ? void 0 : _d.value) === null || _e === void 0 ? void 0 : _e.length) > 50) }), _jsx(TextField, { multiline: true, fullWidth: true, 
                                            //className={classes.field}
                                            label: `${intl.formatMessage(messages.sloganField)}`, margin: "normal", value: (_f = state === null || state === void 0 ? void 0 : state.slogans[1]) === null || _f === void 0 ? void 0 : _f.value, name: "application_slogan2", onChange: handleChange, InputProps: {
                                                endAdornment: (_jsx(Typography, Object.assign({ variant: "body2" }, { children: ((_g = state.slogans[1].value) === null || _g === void 0 ? void 0 : _g.length) ? 150 - ((_h = state.slogans[1].value) === null || _h === void 0 ? void 0 : _h.length) : 150 })))
                                            }, error: Boolean(((_k = (_j = state === null || state === void 0 ? void 0 : state.slogans[1]) === null || _j === void 0 ? void 0 : _j.value) === null || _k === void 0 ? void 0 : _k.length) > 150) }), _jsx(LoadingButton, Object.assign({ loading: updating, disabled: updating, variant: "outlined", size: "small", color: "primary", onClick: updateSlogans }, { children: _jsx(FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.titleSlogan.button", defaultMessage: "ui.onBoardingWidget.step.appearance.titleSlogan.button" }) }))] }))] })) })] }))] })));
}
