import React, { useState, useEffect, useContext, useRef } from 'react';

import { Route, Switch } from 'react-router-dom';

import { Skeleton } from 'antd';

import { GlobalHeader, ChangePassword } from 'soxo-firebase-core';

// import MenuTemplate from 'soxo-firebase-core';

import './landing-api.scss';

import { GlobalContext, ModuleRoutes, Profile, SpotlightSearch, SettingsUtil } from 'soxo-firebase-core';

import HomePageAPI from './../../pages/homepage-api/homepage-api';

import MenuTemplate from './../menu-template-api/menu-template-api';

import ReportingDashboard from '../../modules/reporting/components/reporting-dashboard/reporting-dashboard';


// import HomePage from 'soxo-firebase-core';

// import ModuleRoutes from 'soxo-firebase-core';

// import TaskList from 'soxo-firebase-core';

// import TaskForm from 'soxo-firebase-core';

// import WaitingRoom from '../../../business/common/components/waiting-room/waiting-room';

// import Twilio from '../../../business/common/components/twilio/twilio';

import {
    ModelsAPI,
    PagesAPI,
    MenusAPI,
    RolesAPI,
    CoreScripts,
    UsersAPI
}
    from '../../../core/models';

// import { Questions, } from '../../../models';

import { message } from 'antd';

/**
 * Landing file for
 *
 * @param {*} props
 * @returns
 */
export default function Landing({ history, CustomComponents, appSettings, ...props }) {

    const [loader, setLoader] = useState(false);

    const [modules, setModules] = useState([]);

    const [connected, setConnected] = useState();

    const { user = {} } = useContext(GlobalContext);

    const [meta, setMeta] = useState({});

    const [reports, setReports] = useState([]);

    var config = {};

    if (user.role && user.role.name) {

        var role = user.role.name.toLowerCase();
    }

    // Variable decides the control of homepage
    // #TODO This is a temporary fix - Homemage 

    let disableHomepage = false;

    if (process.env.REACT_APP_DISABLEHOMEPAGE) {

        disableHomepage = JSON.parse(process.env.REACT_APP_DISABLEHOMEPAGE);
    }

    useEffect(() => {

        loadMenus();

        // need to find what implement, with a login who has the respective value ("wug_custreportids")
        loadScripts(user);

    }, []);


    const keyMap = {
        moveUp: 'Shift+B',
        spotlight: 'Shift+F'
    }

    /**
     * 
     * 
     */
    const loadMenus = async () => {

        setLoader(true);

        const result = await MenusAPI.getMenus(user);

        // console.log(result);

        if (result && Array.isArray(result.result) && result.result.length) {

            setModules(result.result);



        }

        setLoader(false);
    }

    /**
     * 
     */
    const loadScripts = async (user) => {

        let { wug_custreportids = '' } = user.user_group;

        if (wug_custreportids && wug_custreportids !== '') {

            var report_ids = wug_custreportids.split(',');

            const result = await Promise.all(report_ids.map((id) => CoreScripts.getReportMenu({ id })))

            let filtered = result.filter((record) => record.active === 'Y')

            setReports(filtered);
        }
    }

    // let core_modules = [];

    // Reports length
    let reportMenus = []

    // Reports length
    if (reports.length) {

        reportMenus = [{ caption: 'Reports', sub_menus: reports }]
    }

    // let preferences = [{
    //     caption: 'Preferences',
    //     sub_menus: [{
    //         path: '/change-password',
    //         caption: 'Change Password'
    //     }]
    // }]

    // , ...core_modules
    // , ...preferences
    //


    let core_modules = [{
        caption: 'Preferences',
        sub_menus: [{
            path: '/change-password',
            caption: 'Change Password'
        }]
    }]

    if (user.isAdmin) {

        core_modules = MenusAPI.getCoreMenus();
    }
    // 
    let allModules = [...modules, ...reportMenus, ...core_modules]



    return (
        <section className="landing">

            {/* <HotKeys focused={true} attach={window} keyMap={keyMap} handlers={handlers}> */}

            <GlobalHeader appSettings={appSettings} meta={meta} isConnected={connected} reload={loadMenus} modules={allModules} user={user} history={history}>


                {
                    loader
                        ?
                        <div className='card skeleton'><Skeleton /></div>
                        :
                        <>

                            {/* <Switch> */}

                            {/* Homepage */}
                            {!disableHomepage ? <Route exact key={'home'} path={'/'} render={(props) => <HomePageAPI config={config} {...props} />} /> : null}
                            {/* Homepage Ends */}

                            <Route exact key={'profile'} path={'/profile'} render={(props) => <Profile model={UsersAPI} {...props} />} />

                            {/* <Route exact path={'/upcoming-appointments-form/:id'} component={WaitingRoom} /> */}

                            {/* <Route exact path={'/meeting/:id'} render={(props) => {

    return <Twilio {...props} onConnect={onConnect} />

}} /> */}

                            {/* <Switch> */}
                            {/* Modules and Menus */}
                            <DefineRoute menus={modules} CustomComponents={CustomComponents} callback={(props) => {

                                setMeta({
                                    ...props
                                })

                            }} />

                            <Route path={'/users'} render={() => <ModuleRoutes model={UsersAPI} />} />

                            <Route path={'/reports/:id'} render={(props) => <ReportingDashboard {...props} />} />

                            {/* Modules and Menus Ends */}
                            {/* </Switch> */}

                            {/* Back Office Modules */}

                            {/* <Route key={'data-import'} path={'/candidates'} render={(props) => <ModuleRoutes model={Candidates} {...props} />} /> */}

                            {/* <Route key={'appointments'} path={'/appointments'} render={(props) => <ModuleRoutes model={Appointments} {...props} />} /> */}

                            {/* Back Office Modules Ends */}

                            {/* <Switch> */}
                            {/* Core Menus */}
                            {/* <Route key={'modules'} path={'/modules'} render={(props) => <ModuleRoutes model={Modules} {...props} />} /> */}

                            <Route path={'/menus'} component={() => <ModuleRoutes model={MenusAPI} />} />

                            <Route path={'/models'} render={() => <ModuleRoutes model={ModelsAPI} />} />

                            <Route path={'/pages'} render={() => <ModuleRoutes model={PagesAPI} />} />

                            <Route path={'/roles'} render={() => <ModuleRoutes model={RolesAPI} />} />


                            <Route exact key={'change-password'} path={'/change-password'} render={(props) => <ChangePassword {...props} />} />


                            {/*
                            <Route path={'/permissions'} render={() => <ModuleRoutes model={Permissions} />} />

                            <Route path={'/users'} render={() => <ModuleRoutes model={Users} />} />

                            <Route path={'/questions'} render={() => <ModuleRoutes model={Questions} />} />

                            <Route path={'/lookup-types'} render={() => <ModuleRoutes model={LookupTypes} />} />

                            <Route path={'/process'} render={() => <ModuleRoutes model={Process} />} />

                            <Route path={'/forms'} render={() => <ModuleRoutes model={Forms} />} />

                            <Route path={'/list/:id'} render={(routeParams) => <TaskList {...routeParams} />} />

                            <Route path={'/task/:step_id'} render={(routeParams) => <TaskForm {...routeParams} />} />

                            <Route path={'/steps'} render={() => <ModuleRoutes model={Steps} />} /> */}

                            {/* </Switch> */}

                            {/* Core Menus Ends */}

                        </>}



            </GlobalHeader >

            {/* </HotKeys> */}

            <SpotlightSearch config={props.searchConfig} ref={(elem) => SettingsUtil.registerModal(elem)} />

        </section >
    );
}


/**
 * Define route
 * 
 * @param {*} param0 
 * @returns 
 */
function DefineRoute({ menus, CustomComponents, CustomModels, callback }) {

    const [routes, setRoutes] = useState([]);

    useEffect(() => {

        buildRoutes(menus);

    }, [])


    async function buildRoutes(menus) {

        // console.log(menus);

        let dynamicRoutes = prepareRoutes(menus)

        // console.log(dynamicRoutes);

        SettingsUtil.registerMenus(dynamicRoutes);

        setRoutes(dynamicRoutes);
    }


    let dynamic = [];

    function prepareRoutes(menus) {

        (menus.forEach(async (menu) => {

            dynamic.push(menu);

            if (menu.sub_menus && menu.sub_menus.length) {

                return prepareRoutes(menu.sub_menus)

            }
        }))

        return dynamic;
    }


    function printRoute(menu, index, CustomComponents, CustomModels, callback) {

        // From the path we remove any query parameters that exist in the url
        //  
        let paths = menu.path.split('?');

        // Find the route path
        let path = paths[0];

        return (
            <Route
                exact
                key={index}
                path={path}
                render={(props) => {

                    return <MenuTemplate
                        menu={menu}

                        {...menu.attributes}

                        {...props}
                        CustomModels={CustomModels}
                        CustomComponents={CustomComponents}
                        callback={(props) => {
                            callback(props);
                        }} />;
                }}
            />
        );
    }


    return (<>

        <Switch>

            {
                routes.map((menu, index) => {

                    return printRoute(menu, index, CustomComponents, CustomModels, callback)

                })
            }

        </Switch>

    </>)

}