import React,{useState,useEffect,useRef} 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,BackHandler, Animated} 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 {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';


function StoreImages(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();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [ImageTypes, setImageTypes] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        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 bgRedirFlag=params.redirect || false;
        let BgNavData=params.BgNavData || {};

        setIsAdhocScreen(isAdhoc);
        setIsBeatPlan(isBeat);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1,menu1);
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        const unsubscribeFocus= props.navigation.addListener('focus', () => {getData(storeData1,menu1);});
        if(bgRedirFlag==true && Object.keys(BgNavData).length>0){
          BgNavToStoreImageCap(BgNavData)  
        }

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

    function BgNavToStoreImageCap(BgNavData){
      let {
          storeData,
          menu,
          isAdhocScreen,
          isBeat,
          imageType}=BgNavData
          props.navigation.navigate('StoreImagesCap',{'storeData':storeData,'menu':menu,'isAdhoc':isAdhocScreen,'isBeat':isBeat,'imageType':imageType})
      // props.navigation.navigate('SurveyView',{'surveyData':surveyData,'storeData':storeData,'menu':menu,'isAdhocScreen':isAdhocScreen,'isBeat':isBeat,'ShowCat':ShowCat});
    }

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

    async function getData(storeData1,menu1){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
        
          await db.transaction(async function (txn) {  
            
            let q=`Select * From Master_ImageType order by ImageSequence`;
            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                if(txnres2.rows.length>0){
                    let arr=[];
                    for(var i=0;i<txnres2.rows.length;i++){
                        let data =txnres2.rows.item(i);
                        let imageCount=await getImagesCount(storeData1,data);
                        data['ImageCount']=imageCount;
                        arr.push(data);
                        if(i==txnres2.rows.length-1){
                            setImageTypes(arr);
                            setProcessing(false);
                        }                                
                    }
                }
            },function (txnE,txnerr) { console.log(txnerr); },);

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

    async function getImagesCount(storeData1,imageType){
      return await new Promise((resolve,reject)=>{
        let {StoreId}=storeData1;
        db.transaction(async function (txn) {  
            
          let q=`Select count(*) as ImageCount From ${AppTables.STORE_IMAGES} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and IMAGE_TYPE_ID='${imageType.ImageTypeId}'`;
          await txn.executeSql(q,[],async function (txn2, txnres2) { 
              if(txnres2.rows.length>0){
                let data =txnres2.rows.item(0);
                let count=data.ImageCount;
                
                resolve(count);
              }
              else{
                resolve(0);
              }
          },function (txnE,txnerr) { console.log(txnerr);resolve(0); },);

        });  
      }).catch((err)=>{
        console.log(err);
        return 0;
      })
    }
   
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper,customStyle.zIndex0]}>
          <View style={[customStyle.pageContentWrapper,customStyle.ImageTypesPageWrap]}>
            <View style={customStyle.ImageTypesLHd}>
                <Text  style={customStyle.ImageTypesLHdText}>{ST.ImageTypes}</Text>
            </View>
          { Object.keys(storeData).length>0 &&            
            <FlatList 
            data={ImageTypes}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.ImageTypesL} 
            style={customStyle.ImageTypesLOuter}
            renderItem={({item,index})=>{
                let ImageCount=item.ImageCount!=null?item.ImageCount:0;
                return(
                    <TouchableOpacity style={customStyle.ImageTypesLCon} key={'ImageType'+index} onPress={()=>{props.navigation.navigate('StoreImagesCap',{storeData:storeData,menu:currentMenu,'isAdhoc':isAdhocScreen,'isBeat':isBeatPlan,imageType:item})}}>
                        <Text style={customStyle.ImageTypesLName}>{item.ImageType}</Text>
                        {ImageCount>0 &&
                          <View style={customStyle.ImageTypesLImageCountBox}>
                            <Text style={customStyle.ImageTypesLImageCountText}>{ImageCount}</Text>
                          </View>
                        }
                    </TouchableOpacity>
                );
            }}
            />
          }
         </View>    
         
       </LinearGradient> 
       
      </Container>   
    ); 
}
  
  

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