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_getpaidvisibility, Q_getpromotionmappingList, Q_getSamplingData, Q_getSurveys} from '../constants/ConstantQueries';

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

function StoreDailyMenuCat(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 [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCategories, setStoreCategories] = useState([]);
 
    const [refreshMenuRender, setRefreshMenuRender] = useState(0);
   
    
  
    useEffect(() => { 
       let params=props.route.params? props.route.params:{};
       let storeData1=params.storeData || {};
       let isAdhoc=params.isAdhoc || false;
       setIsAdhocScreen(isAdhoc);
       setStoreData(storeData1);
       
        getStoreCategories(storeData1);
        const willFocusSubscription = props.navigation.addListener('focus', () => {
          getStoreCategories(storeData1);
        });

        return willFocusSubscription;
    }, []);

   

    // useEffect(() => {
    //   console.log('AutoGoToPrev dailmenu onchange',props.AutoGoToPrev);
    //   if(props.AutoGoToPrev==true){
    //     let params=props.route.params? props.route.params:{};
    //     let storeData1=params.storeData || {};
    //     getDailyMenu(storeData1,true);
    //   }
    // }, [props.AutoGoToPrev]);


    async function getStoreCategories(storeData1){
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
           
            await db.transaction(async function (txn) {  
              
              let join=' INNER join Product_Master p on c.CategoryId=p.CategoryId ';
              let join2=' INNER join Mapping_ProductAssortment mp on p.ProductId=mp.ProductId ';
              let q=`SELECT DISTINCT c.CategoryId,c.CategoryName from Master_Category c ${join} ${join2}  where mp.StateId='${StateId}' and mp.ChainId='${ChainId}' and mp.StoreTypeId='${StoreTypeId}' order by p.CategorySequence`;
              
              await txn.executeSql(q,[],async function (txn2, txnres2) { 
                  console.log('cats len:',txnres2.rows.length)
                  if(txnres2.rows.length>0){
                      let arr=[];
                      for(var i=0;i<txnres2.rows.length;i++){
                          let data =txnres2.rows.item(i);
                        //   let isDone=await isCatDone(storeData1,data);
                        //   data['isDone']=isDone;
                          data['isCatPresent']=false;
                          arr.push(data);
                          if(i==txnres2.rows.length-1){
                            setStoreCategories(arr);
                            setProcessing(false);
                          }                                
                      }
                      
                  }else{
                      setProcessing(false);
                  }
              },function (txn2, txnerr) { console.log(txnerr);setProcessing(false); },);
              
              
            });          
        } catch (err) {
            console.log(err);          
        }   
    }

    async function isCatDone(storeData1,cat){
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
        return await new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {  
                let seletlist=`STOCK_UID,PRODUCT as ProductName,PRODUCT_ID as ProductId,BRAND as BrandName,BRAND_ID as BrandId,SUB_CATEGORY as SubCategoryName,SUB_CATEGORY_ID as SubCategoryId,MSL,STOCK,BACKROOM_STOCK,DAMAGED_STOCK,LOST_STOCK,EXPIRY_STOCK,IS_SKU_STOCK_PRESENT,NREXPIRY1_STOCK,NREXPIRY2_STOCK,NREXPIRY3_STOCK`;
                let sku_q=`SELECT ${seletlist} FROM ${AppTables.STOCKWITHCAT_DATA} WHERE STORE_ID='${StoreId}' and CATEGORY_ID='${cat.CategoryId}'    `;
                await txn.executeSql(sku_q,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        resolve(true);
                    }else{
                        resolve(false);
                    }
                },function (txn2, txnerr) { console.log(txnerr);resolve(false); },);
                
              });   
        }).catch((err)=>{
            console.log(err);
            return false;
        })
    }


    function gotoPage(item){
      props.set_autoback({'AutoGoToPrev':false});
      props.navigation.navigate('StoreDailyMenu',{'storeData':storeData,'isAdhoc':isAdhocScreen,'category':item,'CategoryWiseMenu':true});
    }

    async function setCatSelected(item,index,val){
        let allData=StoreCategories;
        let data=allData[index]!=null?allData[index]:{};
        data['isCatPresent']=val;
        setStoreCategories(allData);
        setRefreshMenuRender(!refreshMenuRender);
    }
  



    function _renderCats(){
   
      return(
        <View style={customStyle.catDMenu_listcon}>
        <View style={customStyle.catDMenu_list}>
          {refreshMenuRender==refreshMenuRender && StoreCategories.length>0 &&
            StoreCategories.map((item,index)=>{ 
                let isCatPresent=item.isCatPresent!=null?item.isCatPresent:false;
                return (
                    <TouchableOpacity style={[customStyle.catDMenuI_Wrap]} key={index} onPress={()=>{gotoPage(item);}}>
                       <View style={customStyle.catDMenuI_CheckBoxCon} >
                            <CheckBox
                            boxType='square'
                            value={(isCatPresent==1)}
                            onValueChange={(val)=>{console.log('valchange:',val); let val1=(val==true)?1:0; setCatSelected(item,index,val1); }}
                            style={[customStyle.catDMenuI_CheckBox,(Platform.OS=='ios'?{height:20,width:20,marginTop:8,marginLeft:8,}:{})]}
                            tintColors={{ true:PageTheme.$primary_color, false:PageTheme.$text_color_light }}
                            />
                        </View>
                        <Text style={[customStyle.openStk_prd_name,customStyle.catDMenuI_CheckBox_pName]}>{item.CategoryName}</Text>
                    </TouchableOpacity>
                )
            })
          }
          
        </View>
        </View>
      );
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}> 
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={'Store Categories'}/>        
        <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>                  
                </View>
                <View style={customStyle.storel_details}>
                  <View style={customStyle.storel_code}>
                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
                      <Text style={customStyle.storel_codeLbl}>Store Id:</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                    </View>                    
                    <View style={[customStyle.storel_codeCon]}>
                      <Text style={customStyle.storel_codeLbl}>Store Code:</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreCode}</Text>
                    </View>
                  </View>
                </View>                
              </View> 

              </View>
              {_renderCats()}  
            </ScrollView>
          }
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
  }
  
  

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