"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = tslib_1.__importStar(require("react"));
const styles_1 = require("@mui/material/styles");
const Box_1 = tslib_1.__importDefault(require("@mui/material/Box"));
const system_1 = require("@mui/system");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const react_core_1 = require("@selfcommunity/react-core");
const constants_1 = require("../../constants");
const material_1 = require("@mui/material");
const mui_color_input_1 = require("mui-color-input");
const reducer_1 = require("./reducer");
const reducer_2 = require("./reducer");
const api_services_1 = require("@selfcommunity/api-services");
const onBoarding_1 = require("../../../../utils/onBoarding");
const react_intl_1 = require("react-intl");
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const Errors_1 = require("../../../../constants/Errors");
const utils_1 = require("@selfcommunity/utils");
const lab_1 = require("@mui/lab");
const ScrollContainer_1 = tslib_1.__importDefault(require("../../../../shared/ScrollContainer"));
const messages = (0, react_intl_1.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: `${constants_1.PREFIX}-appearance-root`,
    title: `${constants_1.PREFIX}-appearance-title`,
    summary: `${constants_1.PREFIX}-appearance-summary`,
    colorContainer: `${constants_1.PREFIX}-appearance-color-container`,
    color: `${constants_1.PREFIX}-appearance-color`,
    colorProgress: `${constants_1.PREFIX}-appearance-color-progress`,
    logoContainer: `${constants_1.PREFIX}-appearance-logo-container`,
    logo: `${constants_1.PREFIX}-appearance-logo`,
    uploadButton: `${constants_1.PREFIX}-appearance-upload-button`,
    drawerRoot: `${constants_1.PREFIX}-appearance-drawer-root`,
    drawerHeader: `${constants_1.PREFIX}-appearance-drawer-header`,
    drawerHeaderAction: `${constants_1.PREFIX}-appearance-drawer-header-action`,
    drawerContent: `${constants_1.PREFIX}-appearance-drawer-content`
};
const Root = (0, styles_1.styled)(Box_1.default, {
    name: constants_1.PREFIX,
    slot: 'AppearanceRoot'
})(() => ({}));
const DrawerRoot = (0, styles_1.styled)(material_1.Drawer, {
    name: constants_1.PREFIX,
    slot: 'AppearanceDrawerRoot',
    overridesResolver: (props, styles) => styles.appearanceDrawerRoot
})(({ theme }) => ({}));
function Appearance(inProps) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { className, onCompleteAction } = props;
    // STATE
    const [state, dispatch] = (0, react_1.useReducer)(reducer_2.reducer, (0, reducer_2.getInitialState)(null));
    const [loadingLogo, setLoadingLogo] = (0, react_1.useState)('');
    const [anchorEl, setAnchorEl] = (0, react_1.useState)(null);
    const [tab, setTab] = (0, react_1.useState)(0);
    const [updating, setUpdating] = (0, react_1.useState)(false);
    const [updatingColor, setUpdatingColor] = (0, react_1.useState)('');
    const colorRef = (0, react_1.useRef)(null);
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    // HANDLERS
    const handleTabChange = (event, newValue) => {
        setTab(newValue);
    };
    const handleOpen = (0, react_1.useCallback)((event) => {
        setAnchorEl(event.currentTarget);
    }, []);
    const handleClose = (0, react_1.useCallback)(() => {
        setAnchorEl(null);
    }, []);
    const fetchColors = () => {
        dispatch({ type: reducer_1.actionTypes.LOADING, payload: { loading: true } });
        api_services_1.PreferenceService.searchPreferences('', '', `${react_core_1.Preferences.COLORS_COLORBACK},${react_core_1.Preferences.COLORS_COLORPRIMARY},${react_core_1.Preferences.COLORS_COLORSECONDARY},${react_core_1.Preferences.COLORS_NAVBARBACK},${react_core_1.Preferences.COLORS_COLORFONT},${react_core_1.Preferences.COLORS_COLORFONTSECONDARY}`)
            .then((res) => {
            dispatch({
                type: reducer_1.actionTypes.SET_COLORS,
                payload: {
                    loading: false,
                    colors: res.results
                }
            });
        })
            .catch((e) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, e);
            dispatch({ type: reducer_1.actionTypes.SET_COLORS, payload: { loading: false, colors: [] } });
        });
    };
    const fetchLogos = () => {
        dispatch({ type: reducer_1.actionTypes.LOADING, payload: { loading: true } });
        api_services_1.PreferenceService.searchPreferences('', '', `${react_core_1.Preferences.LOGO_NAVBAR_LOGO},${react_core_1.Preferences.LOGO_NAVBAR_LOGO_MOBILE}`)
            .then((res) => {
            dispatch({
                type: reducer_1.actionTypes.SET_LOGOS,
                payload: {
                    loading: false,
                    logos: res.results
                }
            });
        })
            .catch((e) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, e);
            dispatch({ type: reducer_1.actionTypes.SET_LOGOS, payload: { loading: false, logos: [] } });
        });
    };
    const fetchSlogans = () => {
        dispatch({ type: reducer_1.actionTypes.LOADING, payload: { loading: true } });
        api_services_1.PreferenceService.searchPreferences('', '', `${react_core_1.Preferences.TEXT_APPLICATION_SLOGAN1},${react_core_1.Preferences.TEXT_APPLICATION_SLOGAN2}`)
            .then((res) => {
            dispatch({
                type: reducer_1.actionTypes.SET_SLOGANS,
                payload: {
                    loading: false,
                    slogans: res.results
                }
            });
        })
            .catch((e) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, e);
            dispatch({ type: reducer_1.actionTypes.SET_SLOGANS, payload: { loading: false, slogans: [] } });
        });
    };
    const updatePreference = (preference) => tslib_1.__awaiter(this, void 0, void 0, function* () {
        try {
            yield api_services_1.PreferenceService.updatePreferences(preference);
        }
        catch (e) {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, e);
        }
        finally {
            setUpdating(false);
            setUpdatingColor('');
            onCompleteAction();
        }
    });
    const updateSlogans = () => tslib_1.__awaiter(this, void 0, void 0, function* () {
        setUpdating(true);
        try {
            yield Promise.all(state.slogans.map(({ name, value }) => {
                return updatePreference({ [name]: value });
            }));
        }
        catch (e) {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, e);
        }
        finally {
            setUpdating(false);
        }
    });
    const updateLogoPreference = (name, file) => tslib_1.__awaiter(this, void 0, void 0, function* () {
        setLoadingLogo(name);
        const formData = new FormData();
        formData.append(name, file);
        yield api_services_1.PreferenceService.updatePreferences(formData)
            .then((preference) => {
            setLoadingLogo('');
            dispatch({
                type: reducer_1.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('');
            utils_1.Logger.error(Errors_1.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);
        }
    };
    (0, react_1.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: reducer_1.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: reducer_1.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 ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h4", className: classes.title, alignSelf: "self-start" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.onBoardingWidget.appearance", defaultMessage: "ui.onBoardingWidget.appearance" }) })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.summary }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.summary", defaultMessage: "ui.onBoardingWidget.step.appearance.summary" }) })), (0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ variant: "outlined", size: "small", color: "primary", onClick: handleOpen }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.button", defaultMessage: "ui.onBoardingWidget.step.appearance.button" }) })), (0, jsx_runtime_1.jsxs)(DrawerRoot, Object.assign({ className: classes.drawerRoot, anchor: "right", open: Boolean(anchorEl), onClose: handleClose }, { children: [(0, jsx_runtime_1.jsxs)(Box_1.default, Object.assign({ className: classes.drawerHeader }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h4", color: "primary" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.header.title", defaultMessage: "ui.onBoardingWidget.step.appearance.header.title" }) })), (0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ className: classes.drawerHeaderAction, onClick: handleClose }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "close" }) }))] })), (0, jsx_runtime_1.jsxs)(material_1.Tabs, Object.assign({ value: tab, onChange: handleTabChange, variant: "scrollable", scrollButtons: "auto", "aria-label": "scrollable-tabs" }, { children: [(0, jsx_runtime_1.jsx)(material_1.Tab, { label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.colors.title", defaultMessage: "ui.onBoardingWidget.step.appearance.colors.title" }) }), (0, jsx_runtime_1.jsx)(material_1.Tab, { label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.logo.title", defaultMessage: "ui.onBoardingWidget.step.appearance.logo.title" }) }), (0, jsx_runtime_1.jsx)(material_1.Tab, { label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.titleSlogan.title", defaultMessage: "ui.onBoardingWidget.step.appearance.titleSlogan.title" }) })] })), (0, jsx_runtime_1.jsx)(ScrollContainer_1.default, { children: (0, jsx_runtime_1.jsxs)(Box_1.default, Object.assign({ className: classes.drawerContent }, { children: [tab === 0 && ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: state.colors.map((color) => ((0, jsx_runtime_1.jsxs)(react_1.default.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h6" }, { children: (0, onBoarding_1.formatColorLabel)(color) })), (0, jsx_runtime_1.jsxs)(Box_1.default, Object.assign({ className: classes.colorContainer }, { children: [(0, jsx_runtime_1.jsx)(mui_color_input_1.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 && ((0, jsx_runtime_1.jsx)(material_1.CircularProgress, { className: classes.colorProgress, color: "secondary", size: 24 }))] }))] }, color.id))) })), tab === 1 && ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: state.logos.map((logo) => ((0, jsx_runtime_1.jsxs)(react_1.default.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h6" }, { children: (0, onBoarding_1.formatLogoLabel)(logo.name) })), (0, jsx_runtime_1.jsxs)(Box_1.default, Object.assign({ className: classes.logoContainer }, { children: [(0, jsx_runtime_1.jsx)("img", { src: logo.value, className: classes.logo }), (0, jsx_runtime_1.jsx)("input", { type: "file", onChange: (event) => handleUpload(event, logo.name), hidden: true, accept: ".gif,.png,.jpg,.jpeg", id: logo.name }), (0, jsx_runtime_1.jsx)(lab_1.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: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "upload" }) }))] }))] }, logo.id))) })), tab === 2 && ((0, jsx_runtime_1.jsxs)(Box_1.default, { children: [(0, jsx_runtime_1.jsx)(material_1.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: (0, jsx_runtime_1.jsx)(material_1.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) }), (0, jsx_runtime_1.jsx)(material_1.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: ((0, jsx_runtime_1.jsx)(material_1.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) }), (0, jsx_runtime_1.jsx)(lab_1.LoadingButton, Object.assign({ loading: updating, disabled: updating, variant: "outlined", size: "small", color: "primary", onClick: updateSlogans }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.onBoardingWidget.step.appearance.titleSlogan.button", defaultMessage: "ui.onBoardingWidget.step.appearance.titleSlogan.button" }) }))] }))] })) })] }))] })));
}
exports.default = Appearance;
