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';
import { AppTables } from '../constants/tableConstants';


function MissedCallList(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 [surveys, setSurveys] = useState([]);
    const [Isdone, setIsdone] = 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.isAdhocScreen || 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);
        if(bgRedirFlag==true && Object.keys(BgNavData).length>0){
            BgNavToSurveyView(BgNavData)
            
        }
        const willFocusSubscription = props.navigation.addListener('focus', () => {
            console.log('onfocus');
            getData(storeData1,menu1);
        });

        return willFocusSubscription;
    }, []);


    useEffect(() => {
        console.log('on AutoGoToPrev change (in list view)',props.AutoGoToPrev);
        if(props.AutoGoToPrev==true){
            let params=props.route.params? props.route.params:{};
            let storeData1=params.storeData || {};
            console.log("survey list currentMenu:",currentMenu)
            getData(storeData1,currentMenu,true);
        }
    }, [props.AutoGoToPrev]);

    function BgNavToSurveyView(BgNavData){
        let {
            surveyData,
            storeData,
            menu,
            isAdhocScreen,
            isBeat,
            ShowCat}=BgNavData
            if(ShowCat==1 || ShowCat=='true' || ShowCat==true){
                console.log('go to SurveyCat');
                props.navigation.navigate('SurveyCat',{'surveyData':surveyData,'storeData':storeData,'menu':menu,'isAdhocScreen':isAdhocScreen,'isBeat':isBeat,'ShowCat':ShowCat});
            }
            else{
                props.navigation.navigate('SurveyView',{'surveyData':surveyData,'storeData':storeData,'menu':menu,'isAdhocScreen':isAdhocScreen,'isBeat':isBeat,'ShowCat':ShowCat});
            }
    }
    
   
    async function getData(storeData1,menu1={},isAutoBack=false){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          
          await db.transaction(async function (txn) {   
            // let q2=`SELECT DISTINCT T.SurveyName as SurveyName,T.SurveyId as SurveyId,T.ShowCat FROM Master_SurveyQuestion T INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId WHERE M.StoreId='${StoreId}' and T.MenuId='${menu1.MenuId}'`;
            let q2=`SELECT * FROM ${AppTables.MISSED_CALL} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`;

            await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                if(txnres2.rows.length>0){
                    setIsdone(true)
                }else{
                    setIsdone(false)
                }
                setProcessing(false);
            },function (txnE,txnerr) { setProcessing(false); console.log(txnerr); },);
           
          });          
        } catch (err) {
            setProcessing(false);
            console.log(err);          
        }        
    }

    
    function openSurveyView(){

        props.set_autoback({'AutoGoToPrev':false});
        props.navigation.navigate('MissedCallView',{'storeData':storeData,'menu':currentMenu,'isAdhocScreen':isAdhocScreen,'isBeat':isBeatPlan});
    }
    
  
    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.roundScrollZIndex]}>
          <View style={[customStyle.pageContentWrapper,customStyle.surveyPageWrapper]}>
          
          {/* { Object.keys(storeData).length>0 &&            
            <FlatList 
            data={[{},{}]}
            contentContainerStyle={customStyle.surveyListInner} 
            style={customStyle.surveyList}
            renderItem={({item,index})=>{
                return( */}
                <View style={customStyle.surveyListInner}>
                    <TouchableOpacity style={customStyle.surveyItem} onPress={()=>{openSurveyView()}}>
                        <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}>{"S"}</Text>
                            </View>
                            <Text style={customStyle.surveyItem_name}>{"SALE"}</Text>
                            {Isdone && <View style={customStyle.surveyItem_Check}><AntDesign color={'green'} size={23} name='checkcircle'/></View>}
                        </LinearGradient>
                    </TouchableOpacity>
                    
                </View>
                {/* );
            }}
            /> 
          }  */}
         </View> 
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

export default connect(mapStateToProps, mapDispatchToProps)(MissedCallList)