import React, { useState, useEffect } from 'react'
import { connect } from 'react-redux'
import styled from 'styled-components'
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { Navbar,Container, NavDropdown, Nav} from 'react-bootstrap'
// import  from 'react-bootstrap/OverlayTrigger'
import {Link, useRouteMatch } from 'react-router-dom'
import SimpleLineIcon from 'react-simple-line-icons'
import HorizontalSidebarComponent from './horizontal-sidebar/horizontal-sidebar.component'
import {setSidebarState, fetchUserRoleBasedMenuAsync, userLogOut, fetchUserTermsAndConditionsAsync} from '../../redux/user/user.action'
import {makeConnectionToHubAsync, startReceivingNotificationsAsync} from '../../redux/dashboard/notification-header/remote-notification.action'
import NotificationPopoverContent from './notification-popover/notification-popover.component'
import PulsatingComponent from '../utility/pulsator/pulsator.component'
import VerticalSidebarComponent from './vertical-sidebar/vertical-sidebar.component'

import logo from './assets/logo.svg'
import './header.styles.scss'
import { getCurrentUser, getConnectedStatus, getRemoteNotificationErrorMessages,
    getRemoteNotifications, getRemoteNotificationItemCount,
    getCountOfWorkingNotificationStatus,
    getCountOfHealthNotificationStatus,
    getCountOfSystemNotificationStatus,
    getCurrentUserMenu, getIsSideBarOpen,
    getCurrentUseProfilePhotoUrl    
} from './selectors'

import {getIsSuperAdmin, getDoctorId, getTermsAndConditionsContent } from '../../redux/user/selectors'

import { dashboardComponentRoutes } from '../inside-dashboard/all-routes'

const Sidebar = styled.div`
    width: ${(props) => props.isOpen ? '180px' : '0px'};
    overflow-x: ${(props) => props.isOpen ? 'visible': 'hidden'}; /* Disable horizontal scroll */

`

const AppHeader = ({currentUser, makeConnection, termsAndConditionContent, isSuperAdmin, doctorId,
    errorMessage, itemCount, items, workingCount, healthStatusCount, systemCount, menu,isSidebarOpen,profilePhotoUrl,
    //dispatchers
    getUserMenu,toggleSidebar,fetchNotifications, startReceivingNotifications,doLogout,doFetchTermsConditions,
    ...props}) => {

    const profileImageStyle = {
        height: 30,        
        width: 30,
        borderRadius: "50%"
        };
        
    useEffect(() => {
            makeConnection(isSuperAdmin ? doctorId : currentUser.userId)
            getUserMenu()
            doFetchTermsConditions()
    }, [])

    useEffect(() => {
        if(props.connected){
            startReceivingNotifications()
        }
    }, [props.connected])


    const [userDropDown, setUserDropDown] = useState(false)
    const {path} = useRouteMatch()
    // console.log(path,'=',url)
    // console.log('location =',pathname)    
    // console.log( '🧢 header component... ')
    return (
        <>
            <Sidebar id="mySidenav" className="sidenav some-shadow" isOpen={isSidebarOpen}>
                <VerticalSidebarComponent />
            </Sidebar>
        
            <div>
                <Navbar bg="metta" sticky="top" >
                    <Container className="fixed-height">
                        <div className="d-flex justify-content-start" >
                            <div className="hamburger p-2 mt-2">
                                <a href="#" className="push-sidebar" onClick={toggleSidebar}>
                                    <FontAwesomeIcon icon="bars"/>
                                </a>
                            </div>
                            <div className="p-2">      
                                <img src={logo} className="logo-dimens"/>                  
                                {/* <span className="brand-text">Metta</span>                         */}
                            </div>
                        </div>

                        <Nav className="justify-content-end" >       
                            {/* <span>{currentUser.email}</span> */}
                            <NavDropdown title={
                                            <span className={`${itemCount > 0 ? 'bell-dot': ''}`}>
                                                <FontAwesomeIcon
                                                        icon={"bell"} size="2x">
                                                </FontAwesomeIcon>
                                            </span>
                                } id="collasible-nav-dropdown" className="no-dropdown-toggle-icon">
                                    <NotificationPopoverContent systemCount={systemCount} healthCount={healthStatusCount} workingCount={workingCount}/>                        
                            </NavDropdown>
                            <Nav.Link>{
                                    !! profilePhotoUrl ? 
                                        <img src={profilePhotoUrl }
                                            style={profileImageStyle}
                                        />
                                        :
                                        <FontAwesomeIcon
                                                icon={"user-circle"} size="2x"/>
                                }
                            </Nav.Link>    
                        
                            <NavDropdown title={<span className="resp-username">{currentUser.name}</span>} id="collasible-nav-dropdown" className={`${userDropDown ? 'show': ''}`}>
                                {
                                    
                                    !!menu && !!menu[dashboardComponentRoutes.USER_PROFILE.id] ?
                                        <Link to={`${path}/user_profile`} className="dropdown-item"><SimpleLineIcon name="user" size="Medium" /><span>
                                            {menu[dashboardComponentRoutes.USER_PROFILE.id].menu_name}</span>
                                            </Link>
                                    : null
                                }
                                <Link to={`${path}/change_password`} className="dropdown-item"><SimpleLineIcon name="lock" size="Medium"/><span>Change Password</span></Link>
                                <Link to={`${path}/user_feedback`} className="dropdown-item"><SimpleLineIcon name="like" size="Medium" /><span>Feedback Form</span></Link>
                                {/* <Link to={`${path}/user_terms_conditions`} className="dropdown-item"><SimpleLineIcon name="envelope-letter" size="Medium" /><span>Terms and Conditions</span></Link> */}
                                <NavDropdown.Divider />
                                <Link to={`/`} className="dropdown-item" onClick={doLogout}><SimpleLineIcon name="logout" size="Medium" /><span>Log out</span></Link>
                            </NavDropdown>

                            <Nav.Link>
                                <PulsatingComponent isConnected={props.connected} />
                            </Nav.Link>  
                        </Nav>
                                    
                    </Container>                    
                </Navbar>

                <div className="bg-metta-sidebar py-1" >
                    <HorizontalSidebarComponent />                        
                </div>

                    
            </div>
        </>
    )
}

const mapStateToProps= state => ({
    currentUser: getCurrentUser(state),
    connected: getConnectedStatus(state),
    errorMessage: getRemoteNotificationErrorMessages(state),
    itemCount: getRemoteNotificationItemCount(state),
    items: getRemoteNotifications(state),
    workingCount: getCountOfWorkingNotificationStatus(state),
    healthStatusCount: getCountOfHealthNotificationStatus(state),
    systemCount: getCountOfSystemNotificationStatus(state),
    menu: getCurrentUserMenu(state),
    isSidebarOpen: getIsSideBarOpen(state),
    profilePhotoUrl: getCurrentUseProfilePhotoUrl(state),
    termsAndConditionContent: getTermsAndConditionsContent(state),
    isSuperAdmin: getIsSuperAdmin(state),
    doctorId: getDoctorId(state)
})

const mapDispatchToProps = (dispatch) => ({
    toggleSidebar: () => dispatch(setSidebarState()),
    makeConnection: (userId) => dispatch(makeConnectionToHubAsync(userId)),
    startReceivingNotifications: () => dispatch(startReceivingNotificationsAsync()),
    getUserMenu: () => dispatch(fetchUserRoleBasedMenuAsync()),
    doLogout: () => dispatch(userLogOut()),  
    doFetchTermsConditions: () => dispatch(fetchUserTermsAndConditionsAsync())
  })

export default connect(mapStateToProps, mapDispatchToProps)(AppHeader)