import React, { useState, useEffect } from 'react';
import { useRoute } from '@react-navigation/native';
import { View, Image, Alert, Platform, Linking } from 'react-native';
import { DrawerContentScrollView, DrawerItem } from '@react-navigation/drawer';
import { Title, Caption, Drawer, Text, TouchableRipple, Switch, Modal } from 'react-native-paper';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { globalStyles, customStyles, GetPageTheme } from "../../styles/Global";
import { logout } from '../../components/logout';
import { version, db } from '../../constants/constants';
import { get_item, clear_item, set_item } from '../../components/localStorage';
import { AntDesign, Entypo, EvilIcons, FontAwesome, Ionicons, MaterialIcons } from '../../components/icons';
import LinearGradient from 'react-native-linear-gradient';
import { SvgUri, SvgXml } from 'react-native-svg';
import CustomLoader from '../../components/CustomLoader';
// import RNExitApp from 'react-native-exit-app';
import SQLite from 'react-native-sqlite-2';
import * as RNFS from 'react-native-fs';


// import images
import download_data_image from '../../assets/performics/sidemenu_icons/download_data_icon.svg';
import dailyrouteplan_image from '../../assets/performics/sidemenu_icons/adhoc_route_plan_icon.svg';
import leave_management_icon from '../../assets/performics/sidemenu_icons/leave_management_icon.svg';
import training_icon from '../../assets/performics/sidemenu_icons/training_section_icon.svg';
import resume_icon from '../../assets/performics/sidemenu_icons/leave_management_icon.svg';
import visitor_login_icon from '../../assets/performics/sidemenu_icons/visitor_login_icon.svg';
import upload_data_icon from '../../assets/performics/sidemenu_icons/upload_data_icon.svg';
import reports_icon from '../../assets/performics/sidemenu_icons/reports_icon.svg';
import exit_icon from '../../assets/performics/sidemenu_icons/exit_icon.svg';
import settings_icon from '../../assets/performics/sidemenu_icons/exit_icon.svg';
import { notify } from '../../components/notify';
import { getIf_UserIsManager } from '../../controller/functions';

export function DrawerContent(props) {
    const route = useRoute();
    const propsData = props?.propsData



    // get all theme styles acc to current theme set 
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);
    const globalStyle = globalStyles(props.DarkMode, route.name);


    const [isDarkTheme, setIsDarkTheme] = useState(false)
    const toggleTheme = () => {
        setIsDarkTheme(!isDarkTheme);
    }


    let pageprops = props.pageprops || {};
    let userData = pageprops.sessionData || {};
    const ST = pageprops.StaticText || {};
    let un = userData.UserId || '';
    const activeOpacityC = 0.6;

    function startDownload() {
        props.navigation.closeDrawer();

        if (props.pageprops) {
            if (props.pageprops.set_startDownload) {
                props.pageprops.set_startDownload({ startDownload: true });
            }
            else {
                notify(ST.Couldnotstartdownload)
            }
        }
        else {
            notify(ST.Couldnotstartdownload)
        }
    }

    function AskForDownload() {
        Alert.alert(
            "Performics",
            ST.Doyouwanttodownloaddata,
            [
                {
                    text: ST.Cancel,
                    onPress: () => { },
                    style: "cancel"
                },
                { text: ST.OK, onPress: () => { startDownload(); } }
            ],
        );
    }

    function startUpload() {
        props.navigation.closeDrawer();
        if (props.pageprops) {
            if (props.pageprops.set_startUpload) {
                props.pageprops.set_startUpload({ startUpload: true });
            }
            else {
                notify(ST.Couldnotstartupload)
            }
        }
        else {
            notify(ST.Couldnotstartupload)
        }
    }

    function AskForUpload() {
        Alert.alert(
            "Performics",
            ST.Doyouwanttouploaddata,
            [
                {
                    text: ST.Cancel,
                    onPress: () => { },
                    style: "cancel"
                },
                { text: ST.OK, onPress: () => { startUpload(); } }
            ],
        );
    }

    async function exitApp() {
        console.log('exit app');
        clear_item('islogin');
        clear_item('mpin');
        clear_item('loginToken');
        clear_item('loginInfo');
        clear_item('login_credentials');
        clear_item('firsttime');
        clear_item('projectCode');
        clear_item('projectInfo');
        clear_item('loginOfDays');
        const pdata = { islogin: false, SecurityToken: '' };
        props.pageprops ? props.pageprops.set_session(pdata) : '';
        setTimeout(() => { 
            console.log("exit now");
            props.navigation.reset({index: 0,routes: [{name: "Mpin"}],});
            // RNExitApp.exitApp(); 
        }, 1000);
    }

    async function clearStorage() {
        await set_item('DataStorageCleared', '1');
        try {
            db.transaction(async function (txn) {
                await txn.executeSql(`SELECT name FROM sqlite_schema WHERE type='table' ORDER BY name`, [], async function (txnd, txnres1) {
                    console.log('q exec:', txnres1.rows.length);
                    if (txnres1.rows.length > 0) {
                        for (var i = 0; i < txnres1.rows.length; i++) {
                            let data = txnres1.rows.item(i);
                            let index = i;
                            if (data.name !== 'sqlite_sequence' && data.name != 'android_metadata') {
                                const q = `drop table ${data.name} `;
                                console.log(q);
                                txn.executeSql(q, [], async function (txnd, txnres3) {
                                    console.log(data.name + ' dropped');
                                    if (index == txnres1.rows.length - 1) {
                                        await exitApp();
                                    }
                                }, async function (txn1, txnerr) {
                                    console.log(txnerr);
                                    if (index == txnres1.rows.length - 1) {
                                        await exitApp();
                                    }
                                });
                            } else {
                                if (index == txnres1.rows.length - 1) {
                                    await exitApp();
                                }
                            }
                        }
                    }
                    else {
                        await exitApp();
                    }
                }, async function (txn1, txnerr) { console.log(txnerr); await exitApp(); });
            });

        } catch (err) {
            console.log(err);
            await exitApp();
        }

    }

    function AskForClearStorage() {
        Alert.alert(
            "Performics",
            ST.DoyoureallywanttoclearalldataThiswillremoveallcacheandstorage,
            [
                {
                    text: ST.Cancel,
                    onPress: () => { },
                    style: "cancel"
                },
                { text: ST.OK, onPress: () => { clearStorage() } }
            ],
        );
    }

    async function gotoStore() {
        // let loginInfo = await get_item('loginInfo');
        // let loginDetails = JSON.parse(loginInfo); 
        // let designation=loginDetails.Designation!=null?loginDetails.Designation:'';

        // let ManagersList=pageprops.SUP_ManagerDesigList!=null && pageprops.SUP_ManagerDesigList!="" && typeof pageprops.SUP_ManagerDesigList=="string"?pageprops.SUP_ManagerDesigList.split(","):[];
        // console.log("user designation & ManagersList:",designation,ManagersList);
        let userIsManager = await getIf_UserIsManager(pageprops);

        if (userIsManager) {
            // if current user is in manager list - then show search wise storelist
            console.log("user is manager");
            props.navigation.navigate('StoreList', { showSearchWiseStore: true });
        }
        else {
            pageprops.SUP_StorewisePJP == true ? props.navigation.navigate('StoreList') : props.navigation.navigate('TeamList');
        }
    }


    // console.log(pageprops.ShowImageAudit, "props.ShowImageAudit")

    return (
        <View style={{ flex: 1 }}>
                <LinearGradient colors={[PageTheme.$secondary_color_light, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.drawerInfoCon}>
                    <Image style={globalStyle.drawerLogo} source={{ uri: pageprops.drawerlogo }} />
                    <Title style={globalStyle.title}>{un}</Title>
                    {/* <Text style={customStyle.drawerSubTitle}>{uemail}</Text> */}
                </LinearGradient>
            <DrawerContentScrollView {...props} style={globalStyle.drawerContentScroll} contentContainerStyle={globalStyle.drawerContentScrollInner}>
                <View style={globalStyle.drawerContent}>
                    <Drawer.Section style={globalStyle.drawerSection}>
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={() => { AskForDownload() }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={download_data_image} /></View>
                            <Text style={globalStyle.drawerLabel}>{ST.DownloadData}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={() => { props.navigation.navigate('Attendance') }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={visitor_login_icon} /></View>
                            <Text style={globalStyle.drawerLabel}>{'Attendance'}</Text>
                        </TouchableOpacity>

                        {/*                         
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('AttendanceSup')}}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18}  xml={visitor_login_icon}/></View>  
                            <Text style={globalStyle.drawerLabel}>{'Employee Attendance'}</Text>
                        </TouchableOpacity> */}

                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle}
                            onPress={() => { gotoStore(); }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={dailyrouteplan_image} /></View>
                            <Text style={globalStyle.drawerLabel}>{ST.DailyRoutePlan}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle}
                            onPress={() => { props.navigation.navigate('DistributorList') }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={dailyrouteplan_image} /></View>
                            <Text style={globalStyle.drawerLabel}>{'CD Point'}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={() => { props.navigation.navigate('GateMeeting') }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={upload_data_icon} /></View>
                            <Text style={globalStyle.drawerLabel}>{'Gate Meeting'}</Text>
                        </TouchableOpacity>

                        {pageprops.ShowImageAudit == true &&
                            <TouchableOpacity activeOpacity={activeOpacityC} style={[globalStyle.drawerItemStyle]} onPress={() => { props.navigation.navigate('ImageAuditStoreList') }}>
                                <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={dailyrouteplan_image} /></View>
                                <Text style={globalStyle.drawerLabel}>{'Image Audit'}</Text>
                            </TouchableOpacity>
                        }

                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={() => { AskForUpload() }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={upload_data_icon} /></View>
                            <Text style={globalStyle.drawerLabel}>{ST.UplaodData}</Text>
                        </TouchableOpacity>
                        
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={() => { props.navigation.navigate('GroomingPictures') }}>
                            <View style={globalStyle.drawerItemIcon}>
                                <Image source={require('../../assets/icons/audit/grooming.png')} style={{height:20,width:20,resizeMode:'contain'}} />
                            </View>
                            <Text style={globalStyle.drawerLabel}>{'Grooming Images'}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={() => { props.navigation.navigate('ReportsMenu') }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={reports_icon} /></View>
                            <Text style={globalStyle.drawerLabel}>{ST.Report}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={() => { props.navigation.navigate('HR') }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={resume_icon} /></View>
                            <Text style={globalStyle.drawerLabel}>{'Add Resume/CV'}</Text>
                        </TouchableOpacity>
                        {/* 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('Training')}}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18}  xml={training_icon}/></View>  
                            <Text style={globalStyle.drawerLabel}>{ST.Training}</Text>
                        </TouchableOpacity> */}

                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={() => { props.navigation.navigate('TrainingMenu', { 'Contentid': 1 }) }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={training_icon} /></View>
                            <Text style={globalStyle.drawerLabel}>{"Misc. Documents"}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={activeOpacityC} style={[globalStyle.drawerItemStyle]} onPress={() => { logout(props) }}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={17} height={17} xml={exit_icon} /></View>
                            <Text style={globalStyle.drawerLabel}>{ST.Exit}</Text>
                        </TouchableOpacity>
                        {/* <TouchableOpacity activeOpacity={activeOpacityC} style={[globalStyle.drawerItemStyle]} onPress={()=>{props.navigation.navigate('DynamicStoreList')}}>
                            <View style={globalStyle.drawerItemIcon}><EvilIcons name='gear' size={24} color={PageTheme.$sidemenuColor} /></View> 
                            <Text style={globalStyle.drawerLabel}>{'Dynamic Store List'}</Text>
                        </TouchableOpacity>   */}
                        {/* <TouchableOpacity activeOpacity={activeOpacityC} style={[globalStyle.drawerItemStyle]} onPress={()=>{props.navigation.navigate('DynamicSurveys')}}>
                            <View style={globalStyle.drawerItemIcon}><EvilIcons name='gear' size={24} color={PageTheme.$sidemenuColor} /></View> 
                            <Text style={globalStyle.drawerLabel}>{'Dynamic Surveys'}</Text>
                        </TouchableOpacity>      */}
                        {/* 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('GetDb')}}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={upload_data_icon}/></View> 
                            <Text style={globalStyle.drawerLabel}>{'GetDb'}</Text>
                        </TouchableOpacity> */}

                        <TouchableOpacity activeOpacity={activeOpacityC} style={[globalStyle.drawerItemStyle]} onPress={() => { props.navigation.navigate('Settings') }}>
                            <View style={globalStyle.drawerItemIcon}><EvilIcons name='gear' size={24} color={PageTheme.$sidemenuColor} /></View>
                            <Text style={globalStyle.drawerLabel}>{ST.Settings}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={activeOpacityC} style={[globalStyle.drawerItemStyle]} onPress={() => { Linking.openURL('https://www.cpm-int.com/legal-stuff/privacy-notice') }}>
                            <View style={globalStyle.drawerItemIcon}><MaterialIcons name='policy' size={24} color={PageTheme.$sidemenuColor} /></View>
                            <Text style={globalStyle.drawerLabel}>{ST.PrivacyPolicy}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={activeOpacityC} style={[globalStyle.drawerItemStyle, customStyle.mb7]} onPress={() => { props.navigation.navigate('ContactUs') }}>
                            <View style={globalStyle.drawerItemIcon}><MaterialIcons name='contact-support' size={24} color={PageTheme.$sidemenuColor} /></View>
                            <Text style={globalStyle.drawerLabel}>{ST.ContactUs}</Text>
                        </TouchableOpacity>



                    </Drawer.Section>

                    {/* <Drawer.Section style={globalStyle.preferenceCon}> 
                        <Text style={globalStyle.preferenceTitle}>Preference</Text>
                        <TouchableOpacity onPress={toggleTheme}>
                            <View style={globalStyle.preference}>
                            <Text style={globalStyle.drawerLabel}>
                                Dark Theme
                            </Text><Switch value={isDarkTheme}/>
                            </View>
                        </TouchableOpacity>
                    </Drawer.Section> */}
                </View>
            </DrawerContentScrollView>
            <Drawer.Section style={globalStyle.bottomDrawerSecion}>
                <View style={globalStyle.bottomDrawerCon}>
                    <Image style={globalStyle.bottomDrawerIcon} source={require('../../assets/image/PerformicsLogo.png')} />
                    <Text style={globalStyle.bottomDrawerLabel}>{version}</Text>
                </View>
            </Drawer.Section>

        </View>
    )
}

