import React, { useState, useEffect, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import { useNavigate } from 'react-router-dom';
import { intersection } from 'ramda';

// store
import { storeSet, useStoreValue, useTrackedValue } from '../../store';

// components
import { Menu } from 'primereact/menu';
import { Toast } from 'primereact/toast';

const TopBarProfileMenu = ({ menuLeftRef }) => {
    const navigate = useNavigate();
    const userData = useTrackedValue('userData');
    const fulleName = `${userData.firstName} ${userData.lastName}`;
    const permissions = useStoreValue('getPermissions');
    const companies = useStoreValue('companies');
    const chosenCompanyId = useStoreValue('chosenCompanyId')
    const [companyItems, setCompanyItems] = useState([]);
    const toast = useRef(null);
    let items = [
        {
            template: () => {
                return (
                    <div className="topBar__menuProfileItem">
                       <div className="userInfo">
                            <span className="userName" title={fulleName}>{fulleName}</span>
                            <span className="userEmail" title={userData.email}>{userData.email}</span>
                        </div>
                    </div>
                );
            },
            enable: true
        },
        {
            label: __('Il mio profilo', 'gepafin'),
            command: () => {
                navigate('/profilo')
            },
            enable: true
        },
        {
            label: __('Profilo aziendale', 'gepafin'),
            command: () => {
                navigate('/profilo-aziendale')
            },
            enable: intersection(permissions, ['APPLY_CALLS', 'APPLY_CONFIDI_CALLS']).length && companies.length > 0
        },
        {
            label: __('Seleziona azienda', 'gepafin'),
            template: () => {
                return (
                    <div className="p-menuitem-content" data-pc-section="content">
                        <ul className="topBar__menuCompaniesList">
                            {companyItems.map(o => o.component)}
                        </ul>
                    </div>
                );
            },
            enable: companies.length
        },
        {
            label: __('Aggiungi Azienda', 'gepafin'),
            command: () => {
                navigate('/agguingi-azienda')
            },
            enable: intersection(permissions, ['APPLY_CALLS', 'APPLY_CONFIDI_CALLS']).length
        },
        {
            separator: true,
            enable: true
        },
        {
            label: __('Logout', 'gepafin'),
            icon: 'pi pi-sign-out',
            command: () => {
                storeSet('doLogout');
                window.location.reload();
            },
            enable: true
        }
    ].filter(o => o.enable);

    const switchCompany = (id) => {
        if (chosenCompanyId !== id) {
            storeSet('chosenCompanyId', id);

            if (toast.current) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: __('L\'azienda è stata cambiata')
                });
            }

            navigate('/')
        }
    }

    useEffect(() => {
        const items = companies.map(o => ({
            label: o.companyName,
            companyId: o.id,
            component: <li key={o.id}>
                <span className="topBar__menuCompanyItem"
                             onClick={() => switchCompany(o.id)}
                             data-id={o.id}
                             data-active={chosenCompanyId === o.id}>
                    <i className="pi pi-building-columns"></i>
                    {o.companyName}
                </span>
            </li>
        }));
        setCompanyItems(items);
    }, [companies, chosenCompanyId])

    return <>
        <Toast ref={toast}/>
        <Menu model={items} popup ref={menuLeftRef} id="topBar_profileMenu" className="topBar__menuProfile"/>
    </>
}

export default TopBarProfileMenu;