import React,{useState,useEffect, useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
// import CustomInput from '../components/customInput';
import CustomButton from '../components/customButton';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,KeyboardAvoidingView, Keyboard, Animated, Linking} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {requestMultiplePerms,_checkLocationPermission} from '../components/geolocation';
import OtpInputs from 'react-native-otp-inputs';
import SplashScreen from 'react-native-splash-screen';
import { SvgUri, SvgXml} from 'react-native-svg';
import {version,copyrightText,baseurl,logoImage,db, AppVersion,DevType} from '../constants/constants';
import {METHODS,getMethodName} from '../constants/methodNames';
import GradientButton from '../components/gradientButton';
import { Ionicons } from '../components/icons';
import * as RNFS from "react-native-fs";
import RNApkInstaller from "@dominicvonk/react-native-apk-installer";
import VersionCheck from "react-native-version-check";
import CustomModal from '../components/CustomModal';
import Graphic1 from '../assets/performics/mpin.svg';
import {getProjectData, getProjectInfo, login, RestoreProjectInProps } from '../controller/functions';
import CustomLoader from '../components/CustomLoader';
// import Geolocation from '@react-native-community/geolocation';
// import Geolocation from '@react-native-community/geolocation'
import Geolocation from 'react-native-geolocation-service';


import moment from 'moment';
import DeviceInfo from 'react-native-device-info';
import Text_eng from '../constants/Text_eng.json';
import Text_thai from '../constants/Text_thai.json';
import DownloadAPKModal from '../components/downloadApkModal';
import ReactNativeBlobUtil from 'react-native-blob-util';
import { SafeAreaView } from 'react-native-safe-area-context';

function Mpin (props) { 
  const route = useRoute();

  // get all theme styles acc to current theme set 
  const todayDate=moment(new Date()).format('DD/MM/YYYY');
  const [ST,setST] = useState((props.StaticText || {})); 
  const PageTheme=GetPageTheme(props.DarkMode,route.name);
  const customStyle=customStyles(props.DarkMode,route.name);

  const [state, setState] = useState({mpin:'',cmpin:''});
  const [fieldsChange, setFieldsChange] = useState(false);
  const animatedEffects=useRef(new Animated.Value(0)).current;
  const [downloading, setDownloading] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [loading, setLoading] = useState(true);
  const [dowloadedCount, setDowloadedCount] = useState(0);
  const [totalCount, setTotalCount] = useState(0);
  const [isMPINUpdate, setIsMPINUpdate] = useState(false);
  const [loaderTitle, setLoaderTitle] = useState('');
  const [downloadingText,setDownloadingText] = useState('');

  const [verToUpdate, setVerToUpdate] = useState('');
  const [loginRes, setLoginRes] = useState({});
  const [showVerUpdateModal, setShowVerUpdateModal] = useState(false);

  

  useEffect(() => {     
    
    SplashScreen.hide();
    checkVersion()
    getsetLanguage();
    requestMultiplePerms();
    RestoreProjectInProps(props)
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {
        
        Animated.timing(animatedEffects, {
          toValue: 1,
          duration:400,
          useNativeDriver:(Platform.OS=='ios'?false:true),
        }).start();
      }
    );
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {
        Animated.timing(animatedEffects, {
          toValue: 0,
          duration:400,
          useNativeDriver:(Platform.OS=='ios'?false:true),
        }).start();
      }
    );
    return () => {
      keyboardDidHideListener.remove();
      keyboardDidShowListener.remove();
    };
  }, []);


  // useEffect(() => {   
  //   autologin();
  // }, [fieldsChange]);

  useEffect(() => {
    let timeOutId = setTimeout(() => {
      autosubmit();
  }, 500);

  return () => {
      clearTimeout(timeOutId);
  };
   
  }, [isMPINUpdate]);

  
  useEffect(() => {  
    console.log('props.StaticText changed');
    setLoading(false);
    setLoaderTitle(props.StaticText.Loading+'...')
    setST(props.StaticText);
  }, [props.StaticText]);
  
  async function getsetLanguage(){
    let country = await get_item('UserCountry'); 
    let lngJson=country=='2'?Text_thai:Text_eng;
    props.setStaticText(lngJson);
    setTimeout(()=>{setLoading(false);console.log('props.StaticText timeout');},3000);
  }

  async function checkIfData_Downloaded(){
    try{
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      const isDataStorageCleared=await get_item('DataStorageCleared');
      console.log('iisDataStorageCleared on login:',isDataStorageCleared);
      let dateWiseDataDownload=await get_item('dateWiseDataDownload');
      let dateWiseDataDownload1=dateWiseDataDownload!=null?JSON.parse(dateWiseDataDownload):{};
      if(isDataStorageCleared!='1'){
        // let isDataExists=await checkIfData_Downloaded2();
        // console.log('isDataExists on login:',isDataExists);
        
        if(dateWiseDataDownload1[todayDate]!=null){
          let d=dateWiseDataDownload1[todayDate];
          props.setTodayDataExists(d);
          props.setGlobalData({isDataDownloaded:d});
        }
        else{
          
          let lods={};
          lods[todayDate]=false;
          set_item('dateWiseDataDownload',JSON.stringify(lods)); 
          props.setTodayDataExists(false);
        }
      }
    }
    catch(err){
      console.log(err);
    }
  }


  const mpinlogin=async()=>{
    
    const {mpin,cmpin}=state;
    if(validate()){
       //set m-pin info in global reducer
       props.set_mpin({mpin:mpin});  

       //set m-pin info in encryted local storage
       set_item('mpin',mpin); 
       
       //clear stack and mpin open login screen 
       refreshToken();
      //  props.navigation.reset({index: 0,routes: [{name: 'MpinLogin'}],});
    }
   
  }

  function autologin(){
    const {mpin,cmpin}=state;
    if(mpin.trim().length == 4 && cmpin.trim().length==4){
      mpinlogin();
    }
  }

  // const validate=()=>{
  //   const {mpin}=state;
  //   if(mpin.trim().length == 0){
  //     notify(ST.PleaseenterMPin,'SHORT');
  //     return false;
  //   }
  //   return true;
  // }

  const validate=()=>{
    const {mpin,cmpin}=state;
    console.log('state',state)
    
    if(mpin.trim().length == 0){
      notify(ST.PleaseenterMPin,'SHORT');
      return false;
    }
    else if(mpin.trim().length>0 && mpin.trim().length<4){
      notify(ST.Pleaseenter4digitMPin,'SHORT');
      return false;
    }
    
    if(cmpin.trim().length == 0){
      notify(ST.PleaseconfirmyourMPin,'SHORT');
      return false;
    }

    if(cmpin!=mpin){
      console.warn("checkmpin",cmpin,mpin)
      notify(ST.ConfirmMPindoesnotmatch,'SHORT');
      return false;
    }

    return true;
  }

  async function refreshToken(){
    let login_credentials=await get_item('login_credentials');
    let credentials=login_credentials!=null?JSON.parse(login_credentials):{};
    if(credentials.un!=null && credentials.pass!=null){
      
      _getCurrentLocation(credentials.un,credentials.pass);
    }
    else{
      notify(ST.Sessionnotfoundpleaseloginagain,'SHORT');
      // clear stack and open login
      props.navigation.reset({index: 0,routes: [{name: 'Login'}],});
    }
    
  }

  // async function mpinlogin(){
  //   const {mpin}=state;
  //   if(validate()){
  //     let token=await get_item('loginToken');
  //     let master_pin=await get_item('mpin'); 
  //     console.log('master_pin',master_pin)     
  //     if(master_pin==mpin && master_pin!='' && master_pin!=null && token!='' && token!=null && token!=undefined)
  //     {
  //       refreshToken();// refresh token
  //     }
  //     else{
  //       notify(ST.YouenteredwrongMPin,'SHORT');
  //     }
  //   }
  // }

  async function autosubmit(){
    const {mpin,cmpin}=state;
    if(mpin.trim().length == 4 && cmpin.trim().length == 4){ 
      mpinlogin();
    }
  }

  // async function _getCurrentLocation(un,pass) {  
  //   const hasPermission=await _checkLocationPermission();
  //   if(hasPermission==true)
  //   {    
  //     setProcessing(true);
  //     Geolocation.getCurrentPosition(
  //       async (position) => {
  //           let loc={lat:position.coords.latitude,lng:position.coords.longitude};
  //           setState({...state,location:loc});
  //           await userlogin(loc,un,pass);
  //       },
  //       (error) => {
  //           notify(ST.Cannotgetuserposition);
  //           setProcessing(false);
  //       },
  //       { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
  //     );
  //   }
  //   else{        
  //     notify(ST.Pleaseallowlocationpermissiontologin);
  //   }
  // }

  async function _getCurrentLocation(un, pass) {
  const hasPermission = await _checkLocationPermission();

  if (!hasPermission) {
    notify(ST.Pleaseallowlocationpermissiontologin);
    return;
  }

  setProcessing(true);

  Geolocation.getCurrentPosition(
    async (position) => {
      const loc = {
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      };

      setState({ ...state, location: loc });

      await userlogin(loc, un, pass);
    },
    (error) => {
      console.log("LOCATION ERROR =>", error);
      notify(ST.Cannotgetuserposition);
      setProcessing(false);
    },
    {
      enableHighAccuracy: true,
      timeout: 15000,
      maximumAge: 0,
      forceRequestLocation: true,
      showLocationDialog: true,
    }
  );
}
  async function update_project(){
    // refresh project settings
    let defData={isUpdated:false,ProjectDetails:{},projectid:""}
    let projectid=await get_item('projectCode');
    console.log('projectid',projectid);

    return await new Promise((resolve,reject)=>{
      if(projectid!='' && projectid!=null){
        
        getProjectData(projectid)
        .then((res)=>{
          console.log(res);
          if(res.success && res.projectName!=null){
            //set project info in global reducer
              const pdata=getProjectInfo(res,projectid);
              props.set_project(pdata);  
            //set project info in encryted local storage
            set_item('projectCode',projectid); 
            set_item('projectInfo',JSON.stringify(res)); 

            defData['projectid']=projectid;
            defData['isUpdated']=true;
            defData['ProjectDetails']=res;
            resolve(defData);
          }
          else if(res.projectName==null){
            resolve(defData);
          }        
        })
        .catch((err)=>{
          console.log('err',err);
          resolve(defData);
        });
      }
      else{
        resolve(defData);
      }  
    })
    .catch((err)=>{
      return defData;
    });
   
  }

  async function checkIfData_Downloaded(){
    try{
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      const isDataStorageCleared=await get_item('DataStorageCleared');
      console.log('iisDataStorageCleared on login:',isDataStorageCleared);
      let dateWiseDataDownload=await get_item('dateWiseDataDownload');
      let dateWiseDataDownload1=dateWiseDataDownload!=null?JSON.parse(dateWiseDataDownload):{};
      if(isDataStorageCleared!='1'){
        // let isDataExists=await checkIfData_Downloaded2();
        // console.log('isDataExists on login:',isDataExists);
        
        if(dateWiseDataDownload1[todayDate]!=null){
          let d=dateWiseDataDownload1[todayDate];
          props.setTodayDataExists(d);
          props.setGlobalData({isDataDownloaded:d});
        }
        else{
          
          let lods={};
          lods[todayDate]=false;
          set_item('dateWiseDataDownload',JSON.stringify(lods)); 
          props.setTodayDataExists(false);
        }
      }
    }
    catch(err){
      console.log(err);
    }
  }

  const userlogin=async(loc,username,password)=>{  
      let proj_data=await update_project();
      let {isUpdated,ProjectDetails,projectid}=proj_data

      console.log('is Project Detail refreshed:',isUpdated);

      let projectInfo=await get_item('projectInfo');
      let projectDetails=projectInfo!=null?JSON.parse(projectInfo):{};
      let loginDetails=await get_item('loginOfDays');
      let loginOfDays=loginDetails!=null?JSON.parse(loginDetails):{};
      
      let loginInfo=await get_item('loginInfo');
      loginInfo=loginInfo!=null && loginInfo!=''?JSON.parse(loginInfo):{};
      let apv=loginInfo.AppVersion?loginInfo.AppVersion:'';
      // apv='0';

      const todate=new Date();
      const today=moment(todate).format("HH:mm:ss");
      let manufacturer =await DeviceInfo.getManufacturer();
      let model =await DeviceInfo.getDeviceName();
      let os=await DeviceInfo.getSystemVersion();
      let imeiNo1=await DeviceInfo.getAndroidId();
      
      const data={un:username,pass:password,Intime:today,lat:loc.lat,lng:loc.lng,manufacturer:manufacturer,model:model,os:os,imeiNo1:imeiNo1,imeiNo2:imeiNo1};
      
      const method_name=getMethodName(METHODS.LOGIN_METHOD);
      const url=(props.baseurl || baseurl)+method_name;
      console.log('url:',url);
      
      await login(url,data)
      .then(async(res)=>{
        
        setProcessing(false);
        if(res.networkErr && res.error){  
          notify(ST.Pleaseconnecttointernet+'-'+res.error,'SHORT');
        }
        else if(!res.false && res.error){  
          notify(res.error,'SHORT');
        }
        else{
          let currentAppVersion=res.AppVersion!=null ?res.AppVersion.toString() :'';
          if(currentAppVersion!=null && currentAppVersion!='' && AppVersion!=null && AppVersion!='' && currentAppVersion.replace(" ",'')!=AppVersion.replace(" ",'') && Platform.OS=='android'&& DevType=="Prod" ){
            console.log('update version');
            setVerToUpdate(currentAppVersion);
            setLoginRes(res);
            setShowVerUpdateModal(true);
            return;
          }
          notify(ST.LoginSuccess,'SHORT');
          //set login info in global reducer
          const pdata={islogin:true,UserId:res.UserId,SecurityToken:'',sessionData:res};          
          props.set_session(pdata);  
          
          const proj_udata=getProjectInfo(ProjectDetails,projectid,res.AppClearData);
          let ManagerAppConfigObj= props?.ManagerAppConfig && JSON.parse(props.ManagerAppConfig)
          let ManagerObj=ManagerAppConfigObj?.ManagerAppConfig?.filter(obj1=>obj1.Designation==res?.Designation) ||[]

          if(ManagerObj.length>0){
            proj_udata["SUP_StorewisePJP"]=ManagerObj?.[0]?.StorewisePJP
            proj_udata["ShowStoreSearch"]=ManagerObj?.[0]?.StoreSearch
          }
          props.set_project(proj_udata);  
          
          let country=res.CountryId!=null?res.CountryId+'':'';

          //set login info in encryted local storage
          set_item('islogin','done'); 
          set_item('UserCountry',country); 
          set_item('loginToken',res.UserId);
          set_item('loginInfo',JSON.stringify(res)); 
          props.set_user_details({session_name:res.UserId});

          let lngJson=country=='2'?Text_thai:Text_eng;
          props.setStaticText(lngJson)
          
          await checkIfData_Downloaded();
          
          // open login screen 
          
          if(loginOfDays[todayDate]!=null){
            props.setLoginExists(true);
            props.navigation.reset({index: 0,routes: [{name: 'NoticeBoard',params:{UserData:res,'TodayLogin':true}}],});
          }
          else{
            let currenttime=moment(new Date()).format('DD/MM/YYYY HH:mm:ss');
            let lods={};
            lods[todayDate]=currenttime;
            set_item('loginOfDays',JSON.stringify(lods)); 
            props.setLoginExists(false);
            props.navigation.reset({index: 0,routes: [{name: 'One_QAD',params:{UserData:res,'TodayLogin':false}}],});
          }
          
        }        
      })
      .catch((err)=>{
        setProcessing(false);
        console.log('onPage Login error1',err);
      });
    
   
  }

   const checkVersion = async () => {
      try {
        const updateNeeded = await VersionCheck.needUpdate({
          packageName: "com.cpmindiait.PerformicsManager",
        });
  
        console.log("Version check result:", updateNeeded);
  
        if (updateNeeded?.isNeeded) {
          setShowVerUpdateModal(true);
          setVerToUpdate(" "+updateNeeded?.latestVersion)
          checkVersion()
        }
      } catch (error) {
        console.error("Error checking version:", error);
      }
    };

  

  async function UpdateAppVersion(){
    setShowVerUpdateModal(false);
    let res=loginRes;
    let AppPath=res.AppPath?res.AppPath:'';

    if(Platform.OS=='ios'){
      Linking.openURL("https://apps.apple.com/us/app/performicsmanager/id6446242809");
      // props.navigation.reset({index: 0,routes: [{name: 'NoticeBoard',params:{UserData:res}}],});
    }
    else{
      if(AppPath!='' && AppPath!=null){
        // Do you have permission to install from unknown sources?
        let hasAPKInstallPerm=RNApkInstaller.haveUnknownAppSourcesPermission();
       
        if(!hasAPKInstallPerm){
          // Turn on Unknown Sources permission settings
          RNApkInstaller.showUnknownAppSourcesPermission();
        }

        // android update app
        setDownloading(true);
        let file_parts=AppPath.split('/');
        let filename=file_parts[file_parts.length-1];
        const filePath = RNFS.DownloadDirectoryPath + "/"+filename;
        console.log('filePath for downloading:',filename,filePath);
        let size=0;
       
        let isExists=await RNFS.exists(filePath).then((res)=>{return res;});
        if(isExists){
          let tempPath= RNFS.DocumentDirectoryPath + "/"+filename;
          await RNFS.moveFile(filePath,tempPath).then((res)=>{console.log('file moved');});
          console.log('tempPath:',tempPath);
          await RNFS.unlink(tempPath);
        }

        setTotalCount(size);
        // setDownloadingText('0%')
        setDownloadingText('0 %')
        // RNFS.writeFile(filePath, '').then((create_res)=>{
           
            ReactNativeBlobUtil.config({
              // response data will be saved to this path if it has access right.
              
              addAndroidDownloads: {
                path : filePath,
                useDownloadManager: true,
                title: filename,
                description: 'An APK that will be installed',
                mime: 'application/vnd.android.package-archive',
                notification: true,
                mediaScannable: true,
              }
            })
            .fetch('GET', AppPath, {
              //some headers ..
            })
            .progress((received, total) => {
              let status_inpercent=((received / total)*100);
              try{
                status_inpercent=status_inpercent!=NaN && status_inpercent!=null?parseInt(status_inpercent):status_inpercent;
              }
              catch(err){
                console.log('status_inpercent error:',err);
              }
              setDownloadingText(status_inpercent+' %');
              setDowloadedCount(received);
              setTotalCount(total);
            })
            .then(async(res) => {
              // the path should be dirs.DocumentDir + 'path-to-file.anything'
              // let status = res.info().status;
              let cache_filePath=res.path();
              console.log('The file saved to ',cache_filePath,filePath);
              setDownloading(false);
              if (cache_filePath!=null && cache_filePath!="" && cache_filePath!='undefined') {
                // let result = await ReactNativeBlobUtil.MediaCollection.copyToMediaStore({
                //               name: filename, parentFolder: '', mimeType: 'application/vnd.android.package-archive' 
                //               },'Download', // Media Collection to store the file in ("Audio" | "Image" | "Video" | "Download")
                //               cache_filePath );
                // console.log("copy file result:",result);
               
                RNApkInstaller.install(filePath);
                //set login info in global reducer
                const pdata={islogin:true,UserId:res.UserId,SecurityToken:'',sessionData:res};          
                props.set_session(pdata);  

                //set login info in encryted local storage
                set_item('islogin','done'); 
                set_item('loginToken',res.UserId);
                set_item('loginInfo',JSON.stringify(res)); 
                set_item('clearOnInstall','true'); 
                props.set_user_details({session_name:res.UserId});

                // }).catch((err)=>{
                //   console.log('error',err);
                //   notify('Sorry! Cannot download apk. Storage Permission Issue');
                // });
                // res.flush();
                // console.log('removed the apk');
                
              }
            });
            
        // }).catch((err)=>{
        //   console.log('Error while creating:',err);
        //   setDownloading(false);
        //   notify('Sorry! Cannot download apk');
        // });
      }
      else{
        setDownloading(false);
        notify('Something went wrong! Cannot update version')
      }
    }
  }
  function _render_Alert(){
    return (
      <CustomModal 
        style={customStyle.appUpdateMStyle}
        titleStyle={customStyle.appUpdateMT_Style}
        title={ST.Appupdateavailableversion+verToUpdate+' '}
        message={ST.UpdateapptothenewversionYourdataissafeandwillnotbelostduringthisupdate}
        messageStyle={customStyle.appUpdateMT_SubStyle}
        showModal={showVerUpdateModal}
      >
        <View style={customStyle.storelVisitM_options}>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{UpdateAppVersion()}}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.OK}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }
  function _renderAnimPart(){
    let cl_scale=1,cl_ty=0,pl_scale=1,illus_scale=1,illus_ty=0,formty=0;
    if(animatedEffects!=null ){
      pl_scale=animatedEffects.interpolate({
        inputRange:[0,1],
        outputRange:[1,0.7],
      });
      cl_scale=animatedEffects.interpolate({
          inputRange:[0,1],
          outputRange:[1,0.6],
      });
      cl_ty=animatedEffects.interpolate({
        inputRange:[0,1],
        outputRange:[0,-40],
      });
      illus_scale=animatedEffects.interpolate({
        inputRange:[0,1],
        outputRange:[1,0.5],
      });
      illus_ty=animatedEffects.interpolate({
        inputRange:[0,1],
        outputRange:[0,-160],
      });
      formty=animatedEffects.interpolate({
        inputRange:[0,1],
        outputRange:[0,-130],
      });
    }
    return(
      
      <View style={customStyle.keyba_inner_view}>
        <Animated.Image  style={[customStyle.performics_logo,
        {
          transform: [
            {scale:pl_scale}
          ],
         }
        ]} source={require('../assets/image/PerformicsLogo.png')} />


        {props.splashlogo!=null && props.splashlogo!= '' && 
        <Animated.Image style={[customStyle.company_logo,
         {
          transform: [
            {scale:cl_scale},
            {translateY:cl_ty},
          ],
         }
        ]} source={{uri:props.splashlogo}} />
        }

        <Animated.View style={[
          {
            transform: [
              {scale:illus_scale},
              {translateY:illus_ty},
            ],
          }
        ]}>
        <SvgXml style={[customStyle.loginIllutration]} width={190} height={190} xml={Graphic1}/>    
        </Animated.View>
        <Animated.View style={[customStyle.formCon,
        {
          transform: [
            {translateY:formty},
          ],
        }
        ]}>   
          <Text style={[customStyle.pagedescText]}>{ST.HeyThere}</Text>
          <Text style={customStyle.pageText}>{ST.SetMPintologinyouraccount}</Text>
          <View style={customStyle.form_group}>
            <Text style={[customStyle.form_label]}>{ST.EnterMPin}</Text>           
            <OtpInputs
                // handleChange={(code) => {setState({...state,mpin:code}); setFieldsChange(!fieldsChange);}}
                handleChange={(code) => {  setState({...state,mpin:code}); setIsMPINUpdate(!isMPINUpdate);}}
                numberOfInputs={4}
                secureTextEntry={true}
                keyboardType={"numeric"}
                defaultValue={''}
                autofillFromClipboard={false}
                inputStyles={customStyle.otp_inputStyle}
                style={customStyle.otp_field}
            />
          </View>          
          <View style={customStyle.form_group}>
            <Text style={[customStyle.form_label]}>{ST.ConfirmMPin}</Text>           
            <OtpInputs
                // handleChange={(code) => {setState({...state,cmpin:code}); setFieldsChange(!fieldsChange);}}
                handleChange={(code) => {  setState({...state,cmpin:code}); setIsMPINUpdate(!isMPINUpdate);}}
                numberOfInputs={4}
                secureTextEntry={true}
                keyboardType={"numeric"}
                defaultValue={''}
                autofillFromClipboard={false}
                inputStyles={customStyle.otp_inputStyle}
                style={customStyle.otp_field}
                // onSubmitEditing={(val)=>{ mpinlogin();}}
            />
          </View>

          
        </Animated.View>
        
        
      </View>
    )
  }

  return ( 
    <Container {...props}> 
     {processing && <CustomLoader title={loaderTitle}/>}   
      {loading && <CustomLoader/>} 
      {(downloading) && <DownloadAPKModal title={ST.Downloadingapk} downloadCount={dowloadedCount} totalCount={totalCount} hideCounter={true} subtitle={downloadingText}/>}
      {_render_Alert()}
      <View style={[customStyle.projectPageWrapper]}> 
        <ScrollView
          style={[customStyle.projectScrollCon]}
          contentContainerStyle={customStyle.projectCon}
        >
        {_renderAnimPart()}

        </ScrollView>  
        <View style={[customStyle.footerView]}>
          <GradientButton {...props} title={ST.CreateMPin} onPress={()=>{mpinlogin();}}/>
          <View style={[customStyle.signatureBox,customStyle.mt10]}>
            <Text style={customStyle.signatureText}>{version}</Text>
            <Text style={customStyle.signatureText}>{copyrightText}</Text>
          </View>
        </View>
      </View>   
    </Container>   
  ); 
}

export default connect(mapStateToProps, mapDispatchToProps)(Mpin)