import { __rest } from "tslib";
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import React, { useEffect, useMemo } from 'react';
import { styled } from '@mui/material/styles';
import { Box, IconButton, Stack, Typography } from '@mui/material';
import { defineMessages, useIntl } from 'react-intl';
import { SCPreferences, useSCFetchUser, useSCFetchUserProviders, useSCPreferences } from '@selfcommunity/react-core';
import classNames from 'classnames';
import { useThemeProps } from '@mui/system';
import Icon from '@mui/material/Icon';
import { SCUserSocialAssociations } from '../../types';
const messages = defineMessages({
    socialAdd: {
        id: 'ui.userSocialAssociation.add',
        defaultMessage: 'ui.userSocialAssociation.add'
    },
    socialRemove: {
        id: 'ui.userSocialAssociation.remove',
        defaultMessage: 'ui.userSocialAssociation.remove'
    }
});
const PREFIX = 'SCUserSocialAssociation';
const classes = {
    root: `${PREFIX}-root`,
    field: `${PREFIX}-field`
};
const Root = styled(Stack, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({}));
const PREFERENCES = [
    SCPreferences.PROVIDERS_FACEBOOK_SIGNIN_ENABLED,
    SCPreferences.PROVIDERS_GOOGLE_SIGNIN_ENABLED,
    SCPreferences.PROVIDERS_TWITTER_SIGNIN_ENABLED,
    SCPreferences.PROVIDERS_LINKEDIN_SIGNIN_ENABLED
];
/**
 * > API documentation for the Community-JS User Social Association component. Learn about the available props and the CSS API.

 #### Import

 ```jsx
 import {UserSocialAssociation} from '@selfcommunity/react-ui';
 ```

 #### Component Name

 The name `SCUserSocialAssociation` can be used when providing style overrides in the theme.


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCUserSocialAssociation-root|Styles applied to the root element.|
 |field|.SCUserSocialAssociation-field|Styles applied to the field element.|

 * @param inProps
 */
export default function UserSocialAssociation(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className = null, userId = null, user = null, providers = null, onCreateAssociation = null, onDeleteAssociation = null, children = null, deletingProvider = null } = props, rest = __rest(props, ["className", "userId", "user", "providers", "onCreateAssociation", "onDeleteAssociation", "children", "deletingProvider"]);
    // HOOKS
    const { scUser } = useSCFetchUser({ id: userId, user });
    const { scUserProviders, setSCUserProviders } = useSCFetchUserProviders({ id: userId || scUser.id, providers });
    // INTL
    const intl = useIntl();
    // Compute preferences
    const scPreferences = useSCPreferences();
    const preferences = useMemo(() => {
        const _preferences = {};
        PREFERENCES.map((p) => (_preferences[p] = p in scPreferences.preferences ? scPreferences.preferences[p].value : null));
        return _preferences;
    }, [scPreferences.preferences]);
    // MEMO PROVIDERS
    const _providers = useMemo(() => {
        return scUserProviders
            .map((provider) => ({ [provider.provider]: provider }))
            .reduce((prev, provider) => Object.assign(prev, provider), {});
    }, [scUserProviders]);
    const providersEnabled = Object.values(SCUserSocialAssociations).filter((p) => preferences[`providers.${p}_signin_enabled`]);
    const providersToLink = providersEnabled === null || providersEnabled === void 0 ? void 0 : providersEnabled.filter((p) => { var _a, _b; return !((_a = _providers[p]) === null || _a === void 0 ? void 0 : _a.provider) && !((_b = _providers[p]) === null || _b === void 0 ? void 0 : _b.ext_id); });
    const providersLinked = Object.values(_providers).filter((p) => providersEnabled.includes(p.provider));
    /**
     * Updates providers list onDelete association
     */
    useEffect(() => {
        if (deletingProvider) {
            const updatedProviders = scUserProviders.filter((p) => p.provider !== deletingProvider.provider);
            setSCUserProviders(updatedProviders);
        }
    }, [deletingProvider]);
    /**
     * Renders social association block
     */
    if (!providersEnabled) {
        return null;
    }
    return (_jsxs(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { direction: "column" }, { children: [providersLinked.length !== 0 || (providersToLink.length !== 0 && onCreateAssociation) ? children : null, providersToLink.length !== 0 && onCreateAssociation && (_jsxs(Box, { children: [_jsxs(Typography, Object.assign({ variant: "body2" }, { children: [" ", intl.formatMessage(messages.socialAdd)] })), providersToLink.map((p, index) => (_jsx(React.Fragment, { children: _jsx(IconButton, Object.assign({ onClick: onCreateAssociation ? () => onCreateAssociation(p) : null }, { children: _jsx(Icon, { children: p }) })) }, index)))] })), providersLinked.length !== 0 && (_jsxs(Box, { children: [_jsxs(Typography, Object.assign({ variant: "body2" }, { children: [" ", intl.formatMessage(messages.socialRemove)] })), providersLinked.map((p, index) => (_jsx(React.Fragment, { children: _jsx(IconButton, Object.assign({ color: "primary", onClick: () => onDeleteAssociation(p) }, { children: _jsx(Icon, { children: p.provider }) })) }, index)))] }))] })));
}
