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, KeyboardAvoidingView, BackHandler, Keyboard} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath, HierarchyTbls} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, Fontisto, Ionicons, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { getKPIFields, goToMenuPage } from '../controller/functions';


function ProgramList(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 [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isNonMerchan, setIsNonMerchan] = useState(false);
    const [isNonProg, setIsNonProg] = useState(false);
    const [isStoreSearch, SetIsStoreSearch] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [ScreenName, setScreenName] = useState("");
    const [BgNav, setBgNav] = useState(false);
    const [BgNavData, setBgNavData] = useState({});
    const [KPIFields, setKPIFields] = useState([]);
    const [productCats, setProductCats] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);

    const [showAlert, setShowAlert] = useState(false);
    
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [Hdrname, setHdrname] = useState("");
    const [ColId, setColId] = useState("");
    const [ColName, setColName] = useState("");

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let isAdhoc=params.isAdhoc || false;
        let isBeat=params.isBeat!=null? params.isBeat : false;
        let isNonMerchan1=params.isNonMerchans!=null? params.isNonMerchans : false;
        let isNonProgam=params.isNonProgs!=null? params.isNonProgs : false;
        let isStoreSearch=params.isStoreSearch!=null? params.isStoreSearch : false; 
        let screenname1=params.screenname!=null? params.screenname : "";
        let BgNav1=params.redirect!=null? params.redirect : false;
        let BgNavData1=params.BgNavData!=null? params.BgNavData : {};
      
        setIsAdhocScreen(isAdhoc);
        setIsBeatPlan(isBeat);
        setIsNonMerchan(isNonMerchan1)
        setIsNonProg(isNonProgam)
        SetIsStoreSearch(isStoreSearch)
        setStoreData(storeData1);
        setCurrentMenu(menu1);
        console.log("w.ProgramName------",screenname1)
        setScreenName(screenname1);
        setBgNav(BgNav1);
        setBgNavData(BgNavData1);

            
        getData(storeData1,menu1,screenname1,BgNav1,BgNavData1,isAdhoc,isBeat,isNonMerchan1,isNonProgam,isStoreSearch);

        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
      
        const willFocusSubscription = props.navigation.addListener('focus', () => {
            console.log('onfocus');
            getData(storeData1,menu1,screenname1,BgNav1,BgNavData1,isAdhoc,isBeat,isNonMerchan1,isNonProgam,isStoreSearch);
        });

        return function cleanup() {
            return unsubscribe;
            return willFocusSubscription
        };
       
    }, []);

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]);   
    
    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }
    
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
              {
                text: "Cancel",
                onPress: () => {},
                style: "cancel"
              },
              { text: "OK", onPress: () => {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);} }
            ]
          );
    }

    

    async function getData(storeData1,menu1,screenname1,BgNav1,BgNavData1,isAdhoc,isBeat,isNonMerchan1,isNonProgam,isStoreSearch){   
          
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId,StoreClassId,StoreCategoryId}=storeData1;
            let {PSAllow,PSTableName}=menu1;
            PSTableName=PSTableName!=null?PSTableName:'';
            PSAllow=PSAllow!=null?PSAllow:false;

            let AllKPIFields=await getKPIFields(menu1);
            setKPIFields(AllKPIFields);

            let HdrName1=(PSTableName.toLowerCase()==HierarchyTbls.Master_SubCategory.toLowerCase()?'Sub Categories':(PSTableName.toLowerCase()==HierarchyTbls.Master_Brand.toLowerCase()?'Brands':'Categories'));
            setHdrname(HdrName1);

            // Forward to menu screen  if Partial Save is not allowed
            if(!PSAllow || PSTableName==''){
                let obj={props,'storeData':storeData1,'screenname':screenname1,'ShowCatWise':true,'MenuItem':menu1,'BgNav':BgNav1,'BgNavData':BgNavData1,'isAdhocScreen':isAdhoc,'isBeatPlan':isBeat,'isNonMerchan':isNonMerchan1,'isNonProg':isNonProgam,'isStoreSearch':isStoreSearch}
                goToMenuPage(obj);
            }

            let orderBy='',idCol='',nameCol='';
            // if(PSTableName.toLowerCase()==HierarchyTbls.Master_SubCategory.toLowerCase()){
            //     idCol='SubCategoryId',nameCol='SubCategoryName';
            //     orderBy=' p.SubCategorySequence ';
            // }
            // else if(PSTableName.toLowerCase()==HierarchyTbls.Master_Brand.toLowerCase()){
            //     idCol='BrandId',nameCol='BrandName';
            //     orderBy=' p.BrandSequence ';
            // }
            // else if(PSTableName.toLowerCase()==HierarchyTbls.Master_Product.toLowerCase()){
            //     idCol='ProductId',nameCol='ProductName';
            //     orderBy=' p.ProductSequence ';
            // }
            // else {
            //     idCol='CategoryId',nameCol='CategoryName';
            //     orderBy=' p.CategorySequence ';
            // }

            nameCol='ProgramName'
            idCol='ProgramId';
          

            let q=await getFilterQuery(storeData1,menu1,idCol,nameCol,orderBy,AllKPIFields);

            

            await db.transaction(async function (txn) {  

                // let q2=` SELECT CATEGORY_ID as CategoryId,CATEGORY as CategoryName FROM ${AppTables.STOCKWITHCAT_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    console.log('filters 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,menu1,data,idCol,nameCol,AllKPIFields);
                            data['isDone']=isDone;
                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                setColId(idCol);
                                setColName(nameCol);
                                setProductCats(arr);
                                setProcessing(false);
                            }                                
                        }
                        
                    }else{
                        setProcessing(false);
                    }
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);
                
                
            });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getFilterQuery(storeData1,menu1,idCol,nameCol,orderBy,AllKPIFields=[]){
        let {StoreId,ChainId,StateId,StoreTypeId,StoreCategoryId,StoreClassId}=storeData1;
        let {ScreenName,MenuId}=menu1;

        let isSpecificMapIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='SpecificMapping')
        let isSpecificMapKPIObj=isSpecificMapIndex>=0?AllKPIFields[isSpecificMapIndex]:{};
        let isSpecificMappingEnable=isSpecificMapIndex>=0?isSpecificMapKPIObj['KPIFieldEnable']:false;
        
        let sosCheckAssortmentI=AllKPIFields.findIndex(i=>i.KPIFieldName=='SOSCheckAssortment')
        let sosCheckAssortmentObj=sosCheckAssortmentI>=0?AllKPIFields[sosCheckAssortmentI]:{};
        let sosCheckAssortment=sosCheckAssortmentI>=0?sosCheckAssortmentObj['KPIFieldEnable']:false;

        let COMPStockAllow_Index=AllKPIFields.findIndex(i=>i.KPIFieldName=='COMPStockAllow' && i.ScreenName==ScreenName);
        let COMPStockAllow_Obj=COMPStockAllow_Index>=0?AllKPIFields[COMPStockAllow_Index]:{};
        let isCOMPStockAllow=COMPStockAllow_Index>=0?COMPStockAllow_Obj['KPIFieldEnable']:false;


        let ProgramStockAllow_Index=AllKPIFields.findIndex(i=>i.KPIFieldName=='PartialSaveAllow' && i.ScreenName==ScreenName);
        let ProgramStockAllow_Obj=ProgramStockAllow_Index>=0?AllKPIFields[ProgramStockAllow_Index]:{};
        let isProgramStockAllow=ProgramStockAllow_Index>=0?ProgramStockAllow_Obj['KPIFieldDisplayName']:"";

        let d1=new Date();
        let d2=moment(d1).format('MM/DD/YYYY');
    
        let q=``,join='',join2='',join3='',WindData={},joinKey='';
        switch(ScreenName){
            case 'STOCK':  
                join=` INNER join Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId `;
                q=`SELECT DISTINCT p.${idCol},p.${nameCol} from Product_Master p ${join} where mp.StoreId='${StoreId}' ${(isCOMPStockAllow==true?'':` and (p.IsCompetitor='0' or p.IsCompetitor= 0) `)}`;
                q+=` order by ${orderBy}`;
                return q;
            case 'PROMOTIONONEAPP':
                WindData=await getWindowFilterFields(storeData1,'Master_PromotionDefinition','Mapping_StorePromotion','PromoDefinitionId','PromoDefinitionId','PromoTable');
                WindData=WindData!=null?WindData:{};
                joinKey=WindData['filterIdsCol']!=null?WindData['filterIdsCol']:'';
                console.log('joinKey:',joinKey);
                join=` INNER join Master_PromotionDefinition d on p.${joinKey}=d.PromoValue `;
                join2=` INNER join Mapping_StorePromotion md on d.PromoDefinitionId=md.PromoDefinitionId `;
                q=`select DISTINCT p.${idCol},p.${nameCol} from Product_Master p ${join} ${join2} where md.StoreId='${StoreId}' `;
                q+=` order by ${orderBy}`;
                console.log("PROMOTIONONEAPP:",q);
                return q;

            case 'SOSONEAPP':
                WindData=await getWindowFilterFields(storeData1,'Master_ShareOfShelfDefinition','Mapping_StoreShareOfShelf','SOSDefinitionId','SOSDefinitionId','SOSHeaderTable');
                WindData=WindData!=null?WindData:{};
                joinKey=WindData['filterIdsCol']!=null?WindData['filterIdsCol']:'';
                join=` INNER join Master_ShareOfShelfDefinition d on p.${joinKey}=d.SOSHeaderValue `;
                join2=` INNER join Mapping_StoreShareOfShelf md on d.SOSDefinitionId=md.SOSDefinitionId `;
                if(sosCheckAssortment){
                    join3=`  INNER JOIN (select * from Mapping_ProductAssortmentStorewise mp 
                        where mp.StoreId='${StoreId}') mp1 
                        on p.ProductId=mp1.ProductId `;
                }
                q=`select DISTINCT p.${idCol},p.${nameCol} from Product_Master p ${join} ${join2} ${join3} where md.StoreId='${StoreId}' `;
                q+=` order by ${orderBy}`;
                console.log("SOSONEAPP:",sosCheckAssortment,q);
                return q;

            case 'PAIDVISIONEAPP':
                let tbname2=isSpecificMappingEnable?'Mapping_StoreVisibilitySpecific':'Mapping_StoreVisibility';
                
                WindData=await getWindowFilterFields(storeData1,'Master_VisibilityDefinition',tbname2,'VisibilityDefinitionId','VisibilityDefinitionId','VisibilityTable');
                WindData=WindData!=null?WindData:{};
                joinKey=WindData['filterIdsCol']!=null?WindData['filterIdsCol']:'';
                join=` INNER join Master_VisibilityDefinition d on p.${joinKey}=d.VisibilityValue and  d.MenuId='${MenuId}' `;
                join2=` INNER join ${tbname2} md on d.VisibilityDefinitionId=md.VisibilityDefinitionId `;
                
                q=`select DISTINCT p.${idCol},p.${nameCol} from Product_Master p ${join} ${join2} where md.StoreId='${StoreId}' `;
                q+=` order by ${orderBy}`;
                console.log("PAIDVISIONEAPP:",q);
                return q;
            case 'PROGRAMONEAPP':
                // let tbname3="Mapping_StoreProgram";
                
                // WindData=await getWindowFilterFields(storeData1,'Master_ProgramDefinition',tbname3,'ProgramDefinitionId','ProgramDefinitionId',"ProgramTable");
                // WindData=WindData!=null?WindData:{};
                // joinKey=WindData['filterIdsCol']!=null?WindData['filterIdsCol']:'';
                // join=` INNER join Master_VisibilityDefinition d on p.${joinKey}=d.ProgramValue and  d.MenuId='${MenuId}' `;
                // join2=` INNER join ${tbname3} md on d.VisibilityDefinitionId=md.VisibilityDefinitionId `;
                
                // q=`select DISTINCT p.${idCol},p.${nameCol} from Product_Master p ${join} ${join2} where md.StoreId='${StoreId}' `;
                // q+=` order by ${orderBy}`;

                q=`SELECT DISTINCT w.ProgramId, w.ProgramName FROM Master_ProgramDefinition w INNER JOIN Mapping_StoreProgram MW on W.ProgramDefinitionId=MW.ProgramDefinitionId WHERE StoreId='${StoreId}' and w.MenuId='${MenuId}' `
                console.log("PROGRAMONEAPP:",q);
                return q;

            default: return '';
        }
    }

    async function getCatDoneQuery(storeData1,menu1,cat,idCol,nameCol,AllKPIFields=[]){
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
        let {ScreenName,MenuId}=menu1;
        
        let IdVal=cat[idCol];
        let nameVal=cat[nameCol];

        console.log("Cat---",cat,IdVal)
        let PJP_Table=isBeatPlan==true?'JourneyPlan_RouteWise':(isAdhocScreen==true?'Adhoc_JourneyPlan':isNonMerchan==true?'NonMerchandising_JourneyPlan':isNonProg==true?'NonProgram_JourneyPlan': isStoreSearch==true?'StoreSearch_JourneyPlan':'Mapping_JourneyPlan');
        let d1=new Date();
        let d2=moment(d1).format('MM/DD/YYYY');

        let isSpecificMapIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='SpecificMapping')
        let isSpecificMapKPIObj=isSpecificMapIndex>=0?AllKPIFields[isSpecificMapIndex]:{};
        let isSpecificMappingEnable=isSpecificMapIndex>=0?isSpecificMapKPIObj['KPIFieldEnable']:false;
        
        
    
        let q=``,FilterIds=[],FilterIdsJoin='';
        switch(ScreenName){
            case 'STOCK':  
                q=` SELECT * FROM ${AppTables.STOCK2HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SUB_CATEGORY_ID='${IdVal}' `;
                return q;
            case 'PROMOTIONONEAPP':  
                FilterIds=await getWindowFilterIds(idCol,IdVal,storeData1,'Master_PromotionDefinition','Mapping_StorePromotion','PromoDefinitionId','PromoDefinitionId','PromoTable')
                FilterIds=FilterIds!=null?FilterIds:[];
                FilterIdsJoin=FilterIds.length>0?FilterIds.join(','):'';
                q=` SELECT * FROM ${AppTables.PROMO_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PROMO_VALUE in (${FilterIdsJoin}) `;
                return q;
            case 'SOSONEAPP':  
                FilterIds=await getWindowFilterIds(idCol,IdVal,storeData1,'Master_ShareOfShelfDefinition','Mapping_StoreShareOfShelf','SOSDefinitionId','SOSDefinitionId','SOSHeaderTable')
                FilterIds=FilterIds!=null?FilterIds:[];
                FilterIdsJoin=FilterIds.length>0?FilterIds.join(','):'';
                q=` SELECT * FROM ${AppTables.SOS_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SOS_HDR_VALUE in (${FilterIdsJoin}) `;
                return q;
            case 'PAIDVISIONEAPP':  
                let tbname2=isSpecificMappingEnable?'Mapping_StoreVisibilitySpecific':'Mapping_StoreVisibility';
                
                FilterIds=await getWindowFilterIds(idCol,IdVal,storeData1,'Master_VisibilityDefinition',tbname2,'VisibilityDefinitionId','VisibilityDefinitionId','VisibilityTable',true,menu1)
                FilterIds=FilterIds!=null?FilterIds:[];
                FilterIdsJoin=FilterIds.length>0?FilterIds.join(','):'';
                q=` SELECT * FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PVIS_VALUE in (${FilterIdsJoin}) `;
                return q;
            case 'PROGRAMONEAPP':
                // let tbname3="Mapping_StoreProgram";
                
                // WindData=await getWindowFilterFields(storeData1,'Master_ProgramDefinition',tbname3,'ProgramDefinitionId','ProgramDefinitionId',"ProgramTable");
                // WindData=WindData!=null?WindData:{};
                // joinKey=WindData['filterIdsCol']!=null?WindData['filterIdsCol']:'';
                // join=` INNER join Master_VisibilityDefinition d on p.${joinKey}=d.ProgramValue and  d.MenuId='${MenuId}' `;
                // join2=` INNER join ${tbname3} md on d.VisibilityDefinitionId=md.VisibilityDefinitionId `;
                
                // q=`select DISTINCT p.${idCol},p.${nameCol} from Product_Master p ${join} ${join2} where md.StoreId='${StoreId}' `;
                // q+=` order by ${orderBy}`;

                let tbname3="Mapping_StoreProgram";
                
                FilterIds=await getWindowFilterIds(idCol,IdVal,storeData1,'Master_ProgramDefinition',tbname3,'ProgramDefinitionId','ProgramDefinitionId','ProgramTable',true,menu1)
                FilterIds=FilterIds!=null?FilterIds:[];
                FilterIdsJoin=FilterIds.length>0?FilterIds.join(','):'';
                q=` SELECT * FROM ${AppTables.PROGRAM_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PROG_ID in (${FilterIdsJoin}) `;
                // q=`SELECT DISTINCT w.ProgramId, w.ProgramName FROM Master_ProgramDefinition w INNER JOIN Mapping_StoreProgram MW on W.ProgramDefinitionId=MW.ProgramDefinitionId WHERE StoreId='${StoreId}' `
                console.log("PROGRAMONEAPP---:",q);
                return q;

            default: return '';
        }
    }


    async function getWindowFilterIds(idCol,IdVal,storeData1,TableName1,TableName2,JoinCol1,JoinCol2,compareKey,AddMenuCase=false,menu1={}){
        
        try{
        let AllIds=[];
        let {StoreId}=storeData1
        let {ScreenName,MenuId}=menu1;

        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {
                let join=` inner join ${TableName2} s on w.${JoinCol1}=s.${JoinCol2}  `;
                let q=`Select w.* from ${TableName1} w ${join} where s.StoreId='${StoreId}' and w.ProgramId='${IdVal}' `;
                if(AddMenuCase){
                    q+=` and w.MenuId='${MenuId}' `;
                }
                
                console.log("done------",q)
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    if(txnres.rows.length>0){
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            let id_value=data["ProgramId"];
                            console.log(`done------${i}`,q,id_value)
                            AllIds.push(id_value);
                            if(i==txnres.rows.length-1){
                                resolve(AllIds)
                            }                                
                        }
                    }
                    else{
                        resolve([]);
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(AllIds) });

                  
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return AllIds;
        });
        }
        catch(err){
            console.log("err",err);
        }
    }

    async function getWindowFilterFields(storeData1,TableName1,TableName2,JoinCol1,JoinCol2,compareKey){
       
        try{
        let AllIds={};
        let {StoreId}=storeData1
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {
                let join=` inner join ${TableName2} s on w.${JoinCol1}=s.${JoinCol2}  `;
                let q=`Select w.* from ${TableName1} w ${join} where s.StoreId='${StoreId}' `;
                console.log("filter---------",q)
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    if(txnres.rows.length>0){
                        let Wind_data =txnres.rows.item(0);
                        let compareVal=Wind_data[compareKey]!=null?Wind_data[compareKey]:'';
                        console.log("compareVal1:",Wind_data,HierarchyTbls,compareVal);
                        let filterIdsCol='';
                        if(compareVal.toLowerCase()==HierarchyTbls.Master_Category.toLowerCase()){
                            filterIdsCol='CategoryId';
                        }
                        else if(compareVal.toLowerCase()==HierarchyTbls.Master_Brand.toLowerCase()){
                            filterIdsCol='BrandId';
                        }
                        else if(compareVal.toLowerCase()==HierarchyTbls.Master_Product.toLowerCase()){
                            filterIdsCol='ProductId';
                        }
                        else{
                            filterIdsCol='SubCategoryId';
                        }
                        Wind_data['filterIdsCol']=filterIdsCol;
                    
                        resolve(Wind_data)
                    }
                    else{
                        resolve(AllIds)
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(AllIds) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return AllIds;
        });
        }
        catch(err){
            console.log("err",err);
        }
    }
    

    async function isCatDone(storeData1,menu1,cat,idCol,nameCol,AllKPIFields=[]){
        // let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
        // let {MenuId, MenuName,ScreenName}=menu1;
        let q=await getCatDoneQuery(storeData1,menu1,cat,idCol,nameCol,AllKPIFields);  
        return await new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {
                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        resolve(true);
                    }else{
                        resolve(false);
                    }
                },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
                
              });   
        }).catch((err)=>{
            console.log(err);
            return false;
        })
    }

    function gotoCatProducts(cat={}){
        let obj={props,'screenname':ScreenName,'storeData':storeData,'MenuItem':currentMenu,'ShowCatWise':false,'CatData':cat,'BgNav':BgNav,'BgNavData':BgNavData,'isAdhocScreen':isAdhocScreen,'isBeatPlan':isBeatPlan,'isNonMerchan':isNonMerchan,'isNonProg':isNonProg,'isStoreSearch':isStoreSearch}
        goToMenuPage(obj);
    }


    function _renderFilterCategories(){
        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={-100} >  
            <FlatList 
            data={productCats}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.prodCatsScroll} 
            style={customStyle.prodCatsScroll_Outer}
            renderItem={({item,index})=>{
                const cat=item;
                let isDone=item.isDone;
                return(
                    <View style={customStyle.opening_Stock_wrap}>
                        <View style={customStyle.opening_Stock_cat}>   
                            <TouchableOpacity activeOpacity={0.5} style={customStyle.opening_Stock_catHdr} onPress={()=>{gotoCatProducts(cat)}}>                  
                                <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                    <Text style={customStyle.opening_Stock_catText}>{item[ColName]}</Text>
                                </LinearGradient>
                                {(item.isDone!=null && item.isDone==true) && <View style={[customStyle.stockCatDone_check]}><AntDesign color={'green'} size={23} name='checkcircle'/></View>}
                            </TouchableOpacity>  
                        </View>
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView>   
        )
    }
    
    
   
    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props}showaddstore={true} title={"Program List"} />        
       
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper,customStyle.pageCWrap2]}>
          
          <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}>{ST.StoreId+':'}</Text>
                        <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                    </View>                    
                    <View style={[customStyle.storel_codeCon]}>
                        <Text style={customStyle.storel_codeLbl}>{ST.StoreCode+':'}</Text>
                        <Text style={customStyle.storel_codeText}>{storeData.StoreCode}</Text>
                    </View>
                </View>
            </View>        
                         
            </View> 

          </View>
          <View style={customStyle.prodCatsHdr}>
            <Text style={customStyle.prodCatsHdrText}>{currentMenu.MenuName}</Text>
          </View>
          {Object.keys(storeData).length>0 &&     
            _renderFilterCategories()
          }
           
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}

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