import React,{useState} from 'react';
import { useRoute } from '@react-navigation/native';
import { View, Image,Alert, Platform, Linking,TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { DrawerContentScrollView } from '@react-navigation/drawer';
import { Title, Drawer, Text } from 'react-native-paper';
import { globalStyles,customStyles,GetPageTheme } from "../../styles/Global";
import {logout} from '../../components/logout';
import { version,db, DevType } from '../../constants/constants';
import { 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 RNExitApp from 'react-native-exit-app';


// import images
import DownloadDataIcon from '../../assets/performics/sidemenu_icons/download_data_icon.svg';
import DailyRoutePlanImage from '../../assets/performics/sidemenu_icons/daily_route_plan_icon.svg';
import TrainingIcon from '../../assets/performics/sidemenu_icons/training_section_icon.svg';
import VisitorLoginIcon from '../../assets/performics/sidemenu_icons/visitor_login_icon.svg';
import UploadDataIcon from '../../assets/performics/sidemenu_icons/upload_data_icon.svg';
import ReportsIcon from '../../assets/performics/sidemenu_icons/reports_icon.svg';
import ExitsIcon from '../../assets/performics/sidemenu_icons/exit_icon.svg';
import { notify } from '../../components/notify';
import ChangePasswordIcon from '../../assets/performics/sidemenu_icons/change_password.svg';

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

    // 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(()=>{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 (txnE,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 (txnE,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()} }
            ],
        );
    }

    return (
        <SafeAreaView style={{ flex: 1 }}>
            <View style={globalStyle.userInfoSection}>
                <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>
    
                </LinearGradient>
            </View>
            <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()}}>
                            <DownloadDataIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            <Text style={globalStyle.drawerLabel}>{ST.DownloadData}</Text>
                        </TouchableOpacity>

                        {pageprops.ShowBeatPlanList==true && 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('BeatPlan')}}>
                            <View style={globalStyle.drawerItemIcon}>
                           <DailyRoutePlanImage style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View>
                
                            <Text style={globalStyle.drawerLabel}>{'Beat Plan'}</Text>
                        </TouchableOpacity>   
                        }
                       
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('StoreList')}}>
                            <View style={globalStyle.drawerItemIcon}>
                            <DailyRoutePlanImage style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View>
                            <Text style={globalStyle.drawerLabel}>{ST.DailyRoutePlan}</Text>
                        </TouchableOpacity>
                        {pageprops.ShowAddNewStore==true && 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('AddStoreInfo')}}>
                            <View style={globalStyle.drawerItemIcon}>
                            <DailyRoutePlanImage style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View>
                            <Text style={globalStyle.drawerLabel}>{ST.AddStoreInfo}</Text>
                        </TouchableOpacity>
                        }   
                      
                       {/* { <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('ReportDetailNew')}}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={reports_icon}/></View> 
                            <Text style={globalStyle.drawerLabel}>{"IR Report"}</Text>
                        </TouchableOpacity> } */}
        
                        {pageprops.ShowSideMenuKYC==true && 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('KycStoreList')}}>
                            <View style={globalStyle.drawerItemIcon}>
                          <DailyRoutePlanImage style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View>
                            <Text style={globalStyle.drawerLabel}>{"Kyc Store List"}</Text>
                        </TouchableOpacity>
                        }
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{AskForUpload()}}>
                            <View style={globalStyle.drawerItemIcon}>
                           <UploadDataIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View> 
                            <Text style={globalStyle.drawerLabel}>{"Upload Data"}</Text>
                        </TouchableOpacity>

                        {pageprops.ShowContractForm==true && 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('ContractFormStores')}}>
                            <View style={globalStyle.drawerItemIcon}>
                            <VisitorLoginIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View>  
                            <VisitorLoginIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            <Text style={globalStyle.drawerLabel}>{'Contract Forms'}</Text>
                        </TouchableOpacity>
                        }

                        {pageprops.WarehouseShow==true && 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('WareHouseInward')}}>
                            <View style={globalStyle.drawerItemIcon}>
                            <VisitorLoginIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View>  
                            <Text style={globalStyle.drawerLabel}>{'Warehouse Inward'}</Text>
                        </TouchableOpacity>
                        }

                        {pageprops.Allow_Change_Password==true && 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('ChangePassword')}}>
                            <View style={globalStyle.drawerItemIcon}>
                           <ChangePasswordIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View>  
                            <Text style={globalStyle.drawerLabel}>{'Change Password'}</Text>
                        </TouchableOpacity>
                        }

                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('VisitorLogin',[,])}}>
                            <View style={globalStyle.drawerItemIcon}>
                            <VisitorLoginIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            
                            </View>  
                            <Text style={globalStyle.drawerLabel}>{"VisitorLogin"}</Text>
                        </TouchableOpacity>
                       
                        {pageprops.Show_VisitorFeedBack==true && 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('VisitorFeedback')}}>
                            <View style={globalStyle.drawerItemIcon}>
                         <VisitorLoginIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View>  
                            <Text style={globalStyle.drawerLabel}>{'Visitor Feedback'}</Text>
                        </TouchableOpacity>
                        }
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('ReportsMenu')}}>
                             <ReportsIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            <Text style={globalStyle.drawerLabel}>{ST.Report}</Text>
        
                        </TouchableOpacity>
                        
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('MiscMenuList')}}>
                            <TrainingIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            <Text style={globalStyle.drawerLabel}>{"Miscellaneous"}</Text>
                        </TouchableOpacity>

                        {pageprops.Show_ConsumerSection==true && 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('Training',{'Contentid':2})}}>
                            <View style={globalStyle.drawerItemIcon}>
                            <TrainingIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </View>  
                            <Text style={globalStyle.drawerLabel}>{'Consumer Section'}</Text>
                        </TouchableOpacity>
                        }
                        

                        <TouchableOpacity activeOpacity={activeOpacityC} style={[globalStyle.drawerItemStyle]} onPress={()=>{logout(props)}}>
                            <View style={globalStyle.drawerItemIcon}>
                           <ExitsIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </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('Warehouse')}}>
                            <View style={globalStyle.drawerItemIcon}><SvgXml width={18} height={18} xml={upload_data_icon}/></View> 
                            <Text style={globalStyle.drawerLabel}>{'Warehouse POSM'}</Text>
                        </TouchableOpacity> */}

                        { Platform.OS!='ios' && 
                        <TouchableOpacity activeOpacity={activeOpacityC} style={globalStyle.drawerItemStyle} onPress={()=>{props.navigation.navigate('GetDb')}}>
                            <View style={globalStyle.drawerItemIcon}>
                           <UploadDataIcon style={globalStyle.drawerItemIcon} width={24} height={24} />
                            </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>
                    
                </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}>{DevType=="Prod"?version:version+"_Dev"+"0.81.0"}</Text>
                </View>
            </Drawer.Section>
            
        </SafeAreaView>
    )
}

