import React,{useState,useEffect, useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles,GetPageTheme, STATUSBAR_HEIGHT } from "../styles/Global";
import {Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,FlatList, Alert,Animated} from 'react-native';
import { connect  } 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 {db,} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { checkIf_VisiAuditDone, checkIf_surveyDone } from '../constants/ConstantQueries';
import { AntDesign } from '../components/icons';


function VisibilityAuditList(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 [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [surveys, setSurveys] = useState([]);
    const [EmpData, setEmpData] = useState([]);
    
    
    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 empData1=params.empData || {};
        let menu1=params.menu || {};
        let isAdhoc=params.isAdhocScreen || false;

       
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setEmpData(empData1);
        setCurrentMenu(menu1);
        getData(storeData1,false);

        const willFocusSubscription = props.navigation.addListener('focus', () => {
            console.log('onfocus');
            getData(storeData1,false);
        });

        return willFocusSubscription;
    }, []);

    useEffect(() => {
        console.log('on AutoGoToPrev change (in list view)',props.AutoGoToPrev);
        if(props.AutoGoToPrev==true){
            getData(storeData,true);
        }
    }, [props.AutoGoToPrev]);
    
   
    async function getData(storeData1,isAutoBack=false){ 
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          
          await db.transaction(async function (txn) {   
            let q2=`SELECT  s.StoreId,w.VisibilityDefinitionId,w.VisibilityId,w.VisibilityName,s.VisibilityQuestion,s.VisibilityImages from Sup_Master_VisibilityDefinition w   
                    inner join Sup_VisibilityAudit s on w.VisibilityDefinitionId=s.VisibilityDefinitionId   
                    where s.StoreId='${StoreId}'`

            await txn.executeSql(q2,[],async function (txn2, txnres) { 
                if(txnres.rows.length>0){
                    let arr=[],isAllSurveyDone=true;
                    for(var i=0;i<txnres.rows.length;i++){
                        let data =txnres.rows.item(i);
                        let ShowCat=data.ShowCat;
                        let isshowcat=(ShowCat==1 || ShowCat=='true' || ShowCat==true);
                        console.log("aksanf----",data)
                        let isDone= await checkIf_VisiAuditDone(storeData1,data,isshowcat)
                        data['isDone']=isDone;
                        arr.push(data);
                        if(!isDone){
                            isAllSurveyDone=false;
                        }
                        if(i==txnres.rows.length-1){
                            setSurveys(arr);
                            setProcessing(false);
                            console.log('isAllSurveyDone surveylist :',isAllSurveyDone,props.AutoGoToPrev,isAutoBack)
                            if(isAllSurveyDone==true && props.AutoGoToPrev==true && isAutoBack==true){
                                // props.set_autoback({'AutoGoToPrev':true});
                                setTimeout(() => {
                                    props.navigation.goBack();
                                }, 1500);
                            }
                        }
                    }
                    
                }
                
            },function (txn2, txnerr) { console.log(txnerr); },);
           
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    
    function openSurveyView(item){
        let {ShowCat}=item
        console.log('ShowCat:',ShowCat);
        props.set_autoback({'AutoGoToPrev':false});
        if(ShowCat==1 || ShowCat=='true' || ShowCat==true){
            console.log('go to SurveyCat');
            props.navigation.navigate('VisibilityAudit',{'surveyData':item,'storeData':storeData,'empData':EmpData,'menu':currentMenu,'isAdhocScreen':isAdhocScreen});
        }
        else{
            props.navigation.navigate('VisibilityAudit',{'surveyData':item,'storeData':storeData,'empData':EmpData,'menu':currentMenu,'isAdhocScreen':isAdhocScreen,'ShowCat':false});
        }
    }
    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} 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.roundScrollZIndex]}>
          <View style={[customStyle.pageContentWrapper,customStyle.surveyPageWrapper]}>
          
          { Object.keys(storeData).length>0 &&            
            <FlatList 
            data={surveys}
            contentContainerStyle={customStyle.surveyListInner} 
            style={customStyle.surveyList}
            renderItem={({item,index})=>{
                return(
                    <TouchableOpacity style={customStyle.surveyItem} onPress={()=>{openSurveyView(item)}}>
                        <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$gradient2]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.surveyItem_tile}>
                            <View style={customStyle.surveyItemCircle}>
                                <Text style={customStyle.surveyItemCircle_Text}>{item.VisibilityName.substring(0,1)}</Text>
                            </View>
                            <Text style={customStyle.surveyItem_name}>{item.VisibilityName}</Text>
                            {(item.isDone!=null && item.isDone==true) && <View style={customStyle.surveyItem_Check}><AntDesign color={'green'} size={23} name='checkcircle'/></View>}
                        </LinearGradient>
                    </TouchableOpacity>
                );
            }}
            />
          }  
         </View> 
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

export default connect(mapStateToProps, mapDispatchToProps)(VisibilityAuditList)