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} 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} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign} from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import {checkFilledSurveys, getAvailblQuery, getIfAvlbl, getIfKPIDone, getQuery, Q_GetAvailabityDefaultData, Q_getCategoryforAdditional, Q_getdefaltShareofSelf, Q_getMyDBMenuList, Q_getMyStoresMenuList, Q_getpaidvisibility, Q_getpromotionmappingList, Q_getSamplingData, Q_getSurveys, Q_MenuList} from '../constants/ConstantQueries';

import grey_bg_image from '../assets/performics/circle_grey.svg';
import { SvgXml } from 'react-native-svg';

function DB_StoreDailyMenu(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 [StoreIntro, setStoreIntro] = useState(false);
    const [StorePhotosDone, setStorePhotosDone] = useState(false);
    const [StoreSKUPhotosDone, setStoreSKUPhotosDone] = useState(false);
    const [StoreSKUActPhotosDone, setStoreSKUActPhotosDone] = useState(false);
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [dailyMenu, setDailyMenu] = useState([]);
    const [refreshMenuStatus, setRefreshMenuStatus] = useState(false);
    const [checkAvailable, setcheckAvailable] = useState(false);
    const [refreshMenuRender, setRefreshMenuRender] = useState(0);
    const [isLoaded, setIsLoaded] = useState(false);
    
  
    useEffect(() => { 
      setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        setStoreData(storeData1);
       
        getDailyMenu(storeData1,false);
        const willFocusSubscription = props.navigation.addListener('focus', () => {
          console.log('DB_StoreDailyMenu onfocus');
          getDailyMenu(storeData1,false);
        });

        return willFocusSubscription;
    }, []);

    // useEffect(() => { 
    //   if(refreshMenuStatus==true){
    //     updateStatus();
    //   }       
    // }, [refreshMenuStatus]);

    // useEffect(() => { 
    //   if(checkAvailable==true){
    //     checkAvailability();
    //   }       
    // }, [checkAvailable]);

    useEffect(() => {
      console.log('AutoGoToPrev dailmenu onchange',props.AutoGoToPrev);
      if(props.AutoGoToPrev==true){
        getDailyMenu(storeData,true);
      }
    }, [props.AutoGoToPrev]);


    async function getDailyMenu(storeData1,isAutoBack=false){
      setProcessing(true);
      console.log('getDailyMenu');
        try {   
          let d1=new Date();
          let d2=moment(d1).format('MM/DD/YYYY');
          let {StoreId,ChannelId,RegionId,StoreTypeId}=storeData1;
          let q=await Q_getMyDBMenuList(storeData1,props);
          console.log('My menu q:',q);
          await db.transaction(async function (txn) {     
            await txn.executeSql(q,[],async function (txn2, txnres) { 
              if(txnres.rows.length>0){     
                let arr=[];      
                let allDone=true;          
                for(var i=0;i<txnres.rows.length;i++){
                  let data =txnres.rows.item(i);
                  let {KPIAVBL,DataRowCount}=data;
                  let isAvlbl=parseInt(KPIAVBL)>0;
                  let isDone=parseInt(KPIAVBL)>0 && parseInt(DataRowCount)>0;
                  data['isAvlbl']=isAvlbl;
                  data['isKPI_Done']=isDone;
                  arr.push(data);

                  if(isAvlbl && !isDone){
                    allDone=false;
                  }

                  if(i==(txnres.rows.length-1)){
                    setDailyMenu(arr);
                    setIsLoaded(true);
                    setProcessing(false);
                    console.log('isAllKPIDone dailymenu :',allDone,props.AutoGoToPrev,isAutoBack)
                    if(allDone==true && props.AutoGoToPrev==true && isAutoBack==true){
                      // props.set_autoback({'AutoGoToPrev':true});
                      setTimeout(() => {
                        props.navigation.goBack();
                      },3000);
                    }
                  }
                }
              }
              else{
                setProcessing(false);
              }
            },function (txnE,txnerr) { console.log(txnerr); setProcessing(false);},);

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

    async function checkAvailability(storeData1,data){
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {  
          let q2=getAvailblQuery(data.ScreenName,storeData1);
          if(data.ScreenName=='ADDITIONALVISI'){
            console.log('POSM query:',q2);
          }
          if(q2!='' && q2!=null){
            await txn.executeSql(q2,[],async function (txn2, txnres2) {  
              if(data.ScreenName=='ADDITIONALVISI'){
                console.log('POSM count:',txnres2.rows.length);
                for(var n=0;n<txnres2.rows.length;n++){
                  let dkeh=txnres2.rows.item(n);
                  console.log(dkeh);
                }
              }                   
              let isAvlbl=getIfAvlbl(data.ScreenName,txnres2,storeData1);
              
              resolve(isAvlbl);
            },function (txnE,txnerr) { console.log(txnerr); resolve(false);},);
          }
          else{
            let isAvlbl=getIfAvlbl(data.ScreenName,{},storeData1);
            resolve(isAvlbl);
          }
        });   
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      });     
    }

    async function updateStatus(storeData1,data,isAvlbl){
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {  
          let q2=getQuery(data.ScreenName,storeData1);
          if(q2!='' && q2!=null && isAvlbl==true){
              await txn.executeSql(q2,[],async function (txn2, txnres2) {                     
                let isDone=await getIfKPIDone(data.ScreenName,txnres2,storeData1);
                resolve(isDone);
              },function (txnE,txnerr) { console.log(txnerr); resolve(false);},);
          }
          else{
              resolve(false);
          }
        });   
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      }); 
             
    }
   

    
    async function checkForData(ScreenName,callback=()=>{},extraData={}){
      try {           
        await db.transaction(async function (txn) {        
          let q2=getQuery2(ScreenName,extraData);
          if(q2!='' && q2!=null){
            await txn.executeSql(q2,[],async function (txn2, txnres2) {                     
              callback(txnres2);
            },function (txnE,txnerr) { console.log(txnerr); },);
          }
        });          
      } catch (err) {
        console.log(err);          
      }        
    }

    async function gotoKPITaskScreen(item){
      switch(item.ScreenName){
        case 'DBWINDOWONEAPP':{
          gotoPage('DB_Window',item);
        }
        return;
        case 'DBPOSMONEAPP':{
          gotoPage('DB_POSM',item);
        }
        return;
        case 'VISICOOLER':{
          gotoPage('DBVisiCooler',item);
        }
        return;

        default:return;
      }
    }

    function gotoPage(screenname='',item){
      props.set_autoback({'AutoGoToPrev':false});
      props.navigation.navigate(screenname,{storeData:storeData,menu:item})
    }
  

    function _renderLeftMenuItem(index,RowContent){
      return(
        <View style={customStyle.dialyMenu_Rows} key={index}> 
          {RowContent[0]}
        </View>
      )
    }


    function _renderRightMenuItem(item,index,RowContent){
      return(
        <View style={customStyle.dialyMenu_Rows} key={index}> 
          {RowContent[0]}
          {_renderMenuItem(item,index)}
        </View>
      )

    }

    function _renderMenuItem(item,index){
      let newi=index>2?((index%3)):index;
      let firstitem=(index%2==0)?true:false;            
      let arr=colors_Arr[newi]?colors_Arr[newi].bg:colors_Arr["0"].bg;
      let unavlbl_bg=['#bfbfbf','#bfbfbf'];
      let arr_new=item.isAvlbl==false?unavlbl_bg:arr;
      let iconColor=colors_Arr[newi]?colors_Arr[newi].color:colors_Arr["0"].color;
      const imgPath=item.MenuPath+(item.isAvlbl==false?item.GreyIcon:item.NormalIcon);
      
      let m_bgimage=colors_Arr[newi]?colors_Arr[newi].bgImage:colors_Arr["0"].bgImage;
      m_bgimage=item.isAvlbl==false?grey_bg_image:m_bgimage;
      
      return(
        <TouchableOpacity activeOpacity={(item.isAvlbl==false?1:0.7)}  style={[customStyle.daily_menu_outer,firstitem?customStyle.daily_menu_first:{}]} key={index} onPress={() => {if(item.isAvlbl!=false){gotoKPITaskScreen(item)}}}> 
          <View style={customStyle.daily_menu_tilebgShadow}>
          <LinearGradient colors={arr_new} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.daily_menu}>
          </LinearGradient>  
          <View style={[customStyle.daily_menu_innerImgCon]}> 
              <SvgXml xml={m_bgimage} width={90} height={90} style={customStyle.daily_menu_bgImg}/>
          </View>
          <View style={[customStyle.daily_menu_inner2]}> 
            {(imgPath!=null && imgPath!='') && <Image source={{uri:imgPath}} style={customStyle.daily_menu_Icon}/>}
          </View>
          
          <Text style={customStyle.daily_menu_title}>{item.MenuName}</Text>
          {item.isKPI_Done==true &&
            <View style={customStyle.daily_menu_done}><AntDesign color={'green'} size={30} name='checkcircle'/></View>
          }  
          </View>     
        </TouchableOpacity>
      )
    }


    function _renderDailyMenu(){
      var RowContent=[];
      return(
        <View style={customStyle.dailymenu_listcon}>
        <View style={customStyle.dailymenu_list}>
          {refreshMenuRender==refreshMenuRender && dailyMenu.length>0 &&
            dailyMenu.map((item,index)=>{ 
              let firstitem=(index%2==0)?true:false;
              
              if(firstitem){
                var content=_renderMenuItem(item,index);
                RowContent=[content];
                if(index==dailyMenu.length-1){
                  return _renderLeftMenuItem(index,RowContent);
                }
              }
              else{
                return _renderRightMenuItem(item,index,RowContent);
              }
              
            })
          }
          
        </View>
        </View>
      );
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}> 
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={'Distributor Menu'}/>        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper]}>
          { Object.keys(storeData).length>0 &&
            <ScrollView contentContainerStyle={[customStyle.geotag_scroll]} style={{}}>            
            
              <View style={[customStyle.storel,customStyle.storeInfo_wrap]}>

              <View style={customStyle.storel_card_outer}> 
                <View style={customStyle.storel_card}>
                  <View style={customStyle.storel_card_content}>
                    <Text style={customStyle.storel_card_title}>{storeData.StoreName}</Text>
                    <View style={customStyle.storel_card_subtitle}>
                      <Text style={customStyle.storel_card_subtitleTxt}>{storeData.StoreType}</Text>
                    </View>
                  </View>                  
                </View>
                <View style={customStyle.storel_details}>
                  <View style={customStyle.storel_code}>
                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
                      <Text style={customStyle.storel_codeLbl}>{'Distributor Id:'}</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                    </View>                    
                    <View style={[customStyle.storel_codeCon]}>
                      <Text style={customStyle.storel_codeLbl}>{'Distributor Code:'}</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreCode}</Text>
                    </View>
                  </View>
                </View>                
              </View> 

              </View>
              {isLoaded==true && _renderDailyMenu()}  
            </ScrollView>
          }
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

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