import React,{useState,useEffect} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,DownloadData} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl, db} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card} from 'react-native-paper';
import {AntDesign, Feather, FontAwesome, MaterialCommunityIcons} from '../components/icons';
import { WebView } from 'react-native-webview';
import CustomLoader from '../components/CustomLoader';
import NoDataComponent from '../components/NoDataComponent';
import LinearGradient from 'react-native-linear-gradient';
import RNExitApp from 'react-native-exit-app';
import { ConfirmSaveAlert } from '../components/alert';
import CustomModal from '../components/CustomModal';
import OtpInputs from 'react-native-otp-inputs';
import { PrimaryTheme } from '../styles/Themes';

function Settings(props) { 
    const route = useRoute();
  
    const ST=props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
  
    const [mpin, setMpin] = useState('');
    const [processing, setProcessing] = useState(false);
    const [isDataFound, setisDataFound] = useState(false);
    const [showAlert, setShowAlert] = useState(false);
    const [showMPinModal, setShowMPinModal] = useState(false);
    
    
    const [reportData, setReportData] = useState([]);
    const [designation, setDesignation] = useState('');
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
      
    }, []);

    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');
        clear_item('GyanCast');
        props.setGlobalData({isDataDownloaded:false});
        const pdata={islogin:false,SecurityToken:''};    
        props.pageprops?props.pageprops.set_session(pdata):'';  
        setTimeout(()=>{
          props.navigation.reset({index: 0,routes: [{name: 'Project'}],});
        },1000);
    }

    async function clearStorage(){
      
        let isvalid=await validate();
        if(isvalid){
          setShowMPinModal(false);
          setProcessing(true);
        await set_item('DataStorageCleared','1');
          try {
            db.transaction(async function (txn) {
              await txn.executeSql(`SELECT name FROM sqlite_master 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();
        }
        }
          
    }

    async function validate(){
        let isValid=true;
        let master_pin=await get_item('mpin');      
        if(master_pin=='' || master_pin==null || master_pin!=mpin || mpin=='' || mpin==null)
        {
            isValid=false;
            notify(ST.YouenteredwrongMPin,'SHORT');
        }
        return isValid;
    }

    function askForMPin(){
        setShowAlert(false);
        setShowMPinModal(true);
    }

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

    function _Mpin_Modal(){
        return (
          <CustomModal
            style={customStyle.MPinM_Style}
            titleStyle={customStyle.MPinM_title_Style}
            title={ST.EnterMPin}
            showModal={showMPinModal}
          >
            <View style={customStyle.MPinM_subtitleCon}>
              <Feather name='alert-triangle' size={18} color={PageTheme.$red}/>
              <Text style={customStyle.MPinM_subtitle_Style}>{ST.Warning}</Text>
            </View>
            <Text style={customStyle.MPinM_subtitle_Style2}>{ST.Allcacheandstoragewillbedeletedfortheapp}</Text>

            <View style={customStyle.MPinM_con}>
            <OtpInputs
                handleChange={(code) => {setMpin(code);}}
                numberOfInputs={4}
                secureTextEntry={true}
                keyboardType={"numeric"}
                defaultValue={''}
                autofillFromClipboard={false}
                inputStyles={customStyle.MPinM_otp_inputStyle}
                style={customStyle.MPinM_otp_field}
            />
            </View>
            <View style={customStyle.storelVisitM_options}>
               
              <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setShowMPinModal(false);}}>
                <Text style={customStyle.storelVisitM_op_btnText}>{ST.Cancel}</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{clearStorage()}}>
                <Text style={customStyle.storelVisitM_op_btnText}>{ST.Yes}</Text>
              </TouchableOpacity>
            </View>
          </CustomModal>
        )
      }


  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        
        <CustomHeader {...props} showaddstore={true} title={ST.Settings} hideBellIcon={true} hideTimer={true}/>
        {_Mpin_Modal()}
        {ConfirmSaveAlert(props,showAlert,()=>{setShowAlert(false)},askForMPin,ST.DoyoureallywanttoclearalldataThiswillremoveallcacheandstorage)}
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        
        <View style={[customStyle.pageContentWrapper]}>
            {/* {borderTopLeftRadius:0,borderTopRightRadius:0,} */}
         
         
                <View style={customStyle.settingsWrap}>
                    <TouchableOpacity style={customStyle.settingsBtn} activeOpacity={0.6} onPress={()=>{AskForClearStorage() }}>
                        <Text style={customStyle.settingsBtnText}>{ST.ClearDataLogout}</Text>
                        <MaterialCommunityIcons name='power' size={26} color={PrimaryTheme.$text_color} style={customStyle.settingsBtnIcon}/>
                    </TouchableOpacity>
                </View>
           
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

export default connect(mapStateToProps, mapDispatchToProps)(Settings);