import React from 'react'
import { connect } from 'react-redux'
import { Switch, useRouteMatch,useLocation, useHistory} from 'react-router-dom'
import { TermsAndConditionContentComponent } from '../../components/utility/terms_and_conditions/terms_and_conditions.component'
import {getTermsAcceptedStatus, getUserIsSubmitting, getErrorMessage, getTermsAndConditionsContent } from '../../redux/user/selectors'
import {submitTermsAndConditionAcceptanceAsync, clearAuthenticationState} from '../../redux/user/user.action'

import PrivateRoute from '../../components/private-route/private.route'
import './dashboard.styles.scss'
import {dashboardComponentRoutes} from  '../../components/inside-dashboard/all-routes'

const TitleBar = ({title, showBack, backClick}) => (
    <div className="row component-title">                    
        <div className="col-md-12 mt-2">                                    
            <div className="page-title">
                <div className="container">
                    <div className="row">
                        <div className="col-md-6 no-p-h">
                            <h3>{title }</h3>
                        </div>
                        <div className="col-md-6 no-p-h">
                            {
                                showBack ?                                 
                                <button className="float-right text-right" onClick={backClick}>
                                    <i className="fa fa-angle-double-left"></i> Go back</button>
                                : 
                                null
                            }
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div> 
)

const Dashboard = ({ 
    termsNotAccepted, submitting, content, errorMessages,
    doAcceptTerms, doDismissError
}) => {
    let {path} = useRouteMatch()
    const history = useHistory()
    const { pathname } = useLocation()
    const spliitedPath = pathname.split('/')
    const lastItem = spliitedPath.length > 2 ? spliitedPath[2].toUpperCase() : null
    const currentComponent = !!lastItem ? dashboardComponentRoutes[lastItem] : null
    //this check helps in determining whether the current component is result of navigation from another page or just menu clicked
    const checkForNavigationNeeded = !!currentComponent ? !(currentComponent.route === spliitedPath[spliitedPath.length - 1]) : false

    const onTermsModalHide = (accepted) => {
        if (accepted)
            doAcceptTerms()        
    }

    return (
        <div id="main">
            <div className="dashboard-inner">
                <div className="container">
                            {
                                !!currentComponent ? <TitleBar title={currentComponent.title} 
                                    showBack={!!currentComponent.enableBack && checkForNavigationNeeded ? currentComponent.enableBack : false}
                                    backClick={() => history.goBack()}
                                    />: null
                            }
                    {/* <TitleBar title={currentComponent.title}/> */}
                    <div className="row d-flex justify-content-center">
                        <Switch>
                            {
                                Object.keys(dashboardComponentRoutes).map( key => {
                                    const sourceObject = dashboardComponentRoutes[key]
                                    //in case of param name this is optional (?).
                                    //courtesy: https://www.digitalprimates.net/blog/taking-full-advantage-of-parameterized-routes-in-react-router/
                                    const targetPath = !!sourceObject.paramName ? `${path}/${sourceObject.route}/:${sourceObject.paramName}?` : `${path}/${sourceObject.route}`
                                    return (
                                            <PrivateRoute key={sourceObject.id} path={targetPath}>        
                                                {
                                                    sourceObject.component
                                                }
                                            </PrivateRoute>
                                        )
                                })
                            }
                            
                        </Switch>                            
                    </div>
                </div>
            </div>   
            {
                termsNotAccepted ?
                    
                    <TermsAndConditionContentComponent showNotAccept={false} isLoading={submitting} show={termsNotAccepted} 
                        onHide={onTermsModalHide} errorMessages={errorMessages} content={content} dismissError={doDismissError} />                        
                    
                : null
            }
        </div>
    )
}

const mapStateToProps = (state) => ({
    termsNotAccepted : getTermsAcceptedStatus(state),
    submitting: getUserIsSubmitting(state),
    errorMessages: getErrorMessage(state),
    content: getTermsAndConditionsContent(state)  
})

const mapDispatchToProps = dispatch => ({
    doDismissError: () => {
        dispatch(clearAuthenticationState())
    },
    doAcceptTerms:() => dispatch(submitTermsAndConditionAcceptanceAsync())

})

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)
