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_surveyDone } from '../constants/ConstantQueries';
import { AntDesign } from '../components/icons';


function SurveyList(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 [isNPNDScreen, setisNPNDScreen] = 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 empData1=params.empData || {};
        let menu1=params.menu || {};
        let isAdhoc=params.isAdhocScreen || false;
        let isNPND=params.isNPND!=null?params.isNPND:false;
      

        setisNPNDScreen(isNPND);
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setEmpData(empData1);
        setCurrentMenu(menu1);
        getData(storeData1,false,menu1);
        console.log('AA TO RHA H');
        

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

        return willFocusSubscription;
    }, []);

    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let menu1=params.menu || {};
        console.log('on AutoGoToPrev change (in list view)',props.AutoGoToPrev);
        if(props.AutoGoToPrev==true){
            getData(storeData,true,menu1);
        }
    }, [props.AutoGoToPrev]);
    
   
    async function getData(storeData1,isAutoBack=false,menu1){ 
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          
          await db.transaction(async function (txn) {   
            let q2=`SELECT DISTINCT T.SurveyName,T.SurveyId,T.ShowCat FROM Sup_Master_SurveyQuestion T INNER JOIN Mapping_SurveySup M ON T.SurveyId=M.SurveyId WHERE T.MenuId='${menu1?.MenuId}'  AND M.StoreId='${StoreId}'  `;
           
           console.log('q2q2========0------------->',q2);
           
            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);
                        let isDone=await checkIf_surveyDone(storeData1,data.SurveyId,isshowcat,menu1)
                        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('SurveyCat',{'surveyData':item,'storeData':storeData,'empData':EmpData,'menu':currentMenu,'isAdhocScreen':isAdhocScreen,'isNPND':isNPNDScreen});
        }
        else{
            props.navigation.navigate('SurveyView',{'surveyData':item,'storeData':storeData,'empData':EmpData,'menu':currentMenu,'isAdhocScreen':isAdhocScreen,'isNPND':isNPNDScreen,'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,{padding:10}]}>
                            <View style={customStyle.surveyItemCircle}>
                                <Text style={customStyle.surveyItemCircle_Text}>{item.SurveyName.substring(0,1)}</Text>
                            </View>
                            <Text style={customStyle.surveyItem_name}>{item.SurveyName}</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)(SurveyList)