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 SamplingList(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 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;
        setIsAdhocScreen(isAdhoc);
        setIsBeatPlan(isBeat);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
        getData(storeData1,menu1);

        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]);
    
   
    async function getData(storeData1,menu1={},isAutoBack=false){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;

          
          await db.transaction(async function (txn) {   
           
            let join=`Left Outer Join ${AppTables.SAMPLING_LIST} l on l.SAMPLING_DEFINITION_ID=T.SamplingDefinitionId and l.STORE_ID='${StoreId}' and l.VISIT_DATE='${d2}' `;
            let q2=`SELECT T.*,(CASE  WHEN (l.ISFILLED=='1' ) THEN 1  ELSE 0 END) SamplingDone FROM Master_SamplingDefinition T INNER JOIN Mapping_StoreSampling M ON T.SamplingDefinitionId=M.SamplingDefinitionId ${join} WHERE M.StoreId='${StoreId}'`;
            // console.log("Sampling list q:2",q2,menu1)
            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= data.SamplingDone==1 ? true :false;
                        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){
                                setTimeout(() => {
                                    props.navigation.goBack();
                                }, 1000);
                            }
                        }
                    }
                    
                }
                else{
                    setProcessing(false);
                    notify('No Data Found!')
                }
            },function (txnE,txnerr) { setProcessing(false);console.log(txnerr); },);
           
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    
    function openSurveyView(item){
        props.set_autoback({'AutoGoToPrev':false});
        props.navigation.navigate('SamplingView',{'SamplingData':item,'storeData':storeData,'menu':currentMenu});
    }
    
  
    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={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.SamplingDefinitionName.substring(0,1)}</Text>
                            </View>
                            <Text style={customStyle.surveyItem_name}>{item.SamplingDefinitionName}</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)(SamplingList)