import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useMemo } from 'react';
import { styled } from '@mui/material/styles';
import { Button, Paper, Stack, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } 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 { SCUserSocialAssociations } from '../../types';
import { PROVIDER_ICONS_CONTAINED } from '../../constants/SocialShare';
const messages = defineMessages({
    provider: {
        id: 'ui.userSocialAssociation.provider',
        defaultMessage: 'ui.userSocialAssociation.provider'
    },
    actions: {
        id: 'ui.userSocialAssociation.actions',
        defaultMessage: 'ui.userSocialAssociation.actions'
    },
    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`,
    providerTable: `${PREFIX}-provider-table`,
    providerIcon: `${PREFIX}-provider-icon`,
    providerName: `${PREFIX}-provider-name`,
    providerAction: `${PREFIX}-provider-action`
};
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, _jsx(TableContainer, Object.assign({ component: Paper, className: classes.providerTable }, { children: _jsxs(Table, { children: [_jsx(TableHead, { children: _jsxs(TableRow, { children: [_jsx(TableCell, Object.assign({ sx: { width: '60%' } }, { children: intl.formatMessage(messages.provider) })), _jsx(TableCell, Object.assign({ align: "left" }, { children: intl.formatMessage(messages.actions) }))] }) }), _jsxs(TableBody, { children: [providersToLink.length !== 0 && onCreateAssociation && (_jsx(_Fragment, { children: providersToLink.map((p, index) => (_jsxs(TableRow, { children: [_jsxs(TableCell, Object.assign({ scope: "row" }, { children: [_jsx("img", { src: PROVIDER_ICONS_CONTAINED[`${p}`], width: "30", height: "30", className: classes.providerIcon, alt: p }), _jsx("span", Object.assign({ className: classes.providerName }, { children: p }))] })), _jsx(TableCell, Object.assign({ align: "left" }, { children: _jsx(Button, Object.assign({ variant: "contained", className: classes.providerAction, color: "primary", onClick: onCreateAssociation ? () => onCreateAssociation(p) : null, size: "small" }, { children: intl.formatMessage(messages.socialAdd) })) }))] }, index))) })), providersLinked.length !== 0 && (_jsx(_Fragment, { children: providersLinked.map((p, index) => (_jsxs(TableRow, Object.assign({ sx: { '&:last-child td, &:last-child th': { border: 0 } } }, { children: [_jsxs(TableCell, Object.assign({ scope: "row" }, { children: [_jsx("img", { src: PROVIDER_ICONS_CONTAINED[`${p.provider}`], width: "30", height: "30", className: classes.providerIcon, alt: p.provider }), _jsx("span", Object.assign({ className: classes.providerName }, { children: p.provider }))] })), _jsx(TableCell, Object.assign({ align: "left" }, { children: _jsx(Button, Object.assign({ variant: "outlined", className: classes.providerAction, onClick: () => onDeleteAssociation(p), size: "small" }, { children: intl.formatMessage(messages.socialRemove) })) }))] }), index))) }))] })] }) }))] })));
}
