import React from 'react';
import Icon from '../../../atoms/icon/Icon';

export const getMemberships = async config => {
    try {
        const { user: currentUser } = config || {};
        if (currentUser?.userUuid) {
            const membership = await fetch(`/api/account/v2/users/${currentUser?.userUuid}/memberships`);
            const res = await membership.json();
            return res.content;
        }
    } catch (e) {
        console.warn('fetch company membership error: ', e);
    }
    return [];
};

const changeCompanyContext = (userId, companyUuid) => {
    fetch(`/api/account/v2/users/${userId}/memberships/${companyUuid}/current`, {
        method: 'PUT',
        mode: 'cors',
        credentials: 'include',
        cache: 'no-store'
    }).then(() => {
        window.location = '/home';
    }).catch(e => {
        console.warn(`Change Company error: ${e}`);
    });
};

export const getCompanyListItems = (memberships, config, namespace, i18nWithDefaults, mainClass) => {
    const {
        companyUuid: currentCompanyId,
        userUuid
    } = config.user || {};

    const sortedMemberships = memberships.slice().sort(
        (a, b) => (b?.company?.uuid === currentCompanyId) - (a?.company?.uuid === currentCompanyId)
    );

    return sortedMemberships.map(membership => {
        const company = (membership && membership.company) || {};
        const isSelected = company.uuid === currentCompanyId;

        return (
            <li {...namespace('userDropdownItem').props} key={company.uuid}>
                <button
                    {...namespace(mainClass, 'userCompanyDropDown').props}
                    type="button"
                    onClick={() => {
                        changeCompanyContext(userUuid, company.uuid);
                    }}
                >
                    <span>
                        <span {...namespace('userCompanyDropdownSpan').props}>
                            <span {...namespace('userCompanyText').props}>{company.name}</span>
                            {isSelected && (
                                <span {...namespace('userCompanyDropdownSelectedCompany').props}>
                                    <Icon
                                        type="checkMark"
                                        width={24}
                                        height={24}
                                        fill="currentColor"
                                    />
                                </span>
                            )}
                        </span>
                        {isSelected && (
                            <span {...namespace('userCompanyDropdownSpanSelected').props}>
                                {i18nWithDefaults.currentCompany}
                            </span>
                        )}
                    </span>
                </button>
            </li>
        );
    });
};
