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 [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;
        let bgRedirFlag = params.redirect || false;
        let BgNavData = params.BgNavData || {};

        setIsAdhocScreen(isAdhoc);
        setIsBeatPlan(isBeat);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
        getData(storeData1, menu1);
        console.log("testing66666",bgRedirFlag,BgNavData)
        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

        // console.log('go to SurveyCat',ShowCat);
        if (ShowCat == 1 || ShowCat == 'true' || ShowCat == true) {
            console.log('go to SurveyCat', ShowCat);
            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}'`;
                console.log("survey list q2222:", 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);
                             console.log("data---------",data)
                            let ShowCat = data.ShowCat;
                            let isshowcat = (ShowCat == 1 || ShowCat == 'true' || ShowCat == true);
                            let isDone = await checkIf_surveyDone(storeData1, data.SurveyId, 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);
                                }
                            }
                        }

                    }
                    else {
                        setProcessing(false);
                        notify('No Data Found!')
                    }
                }, function (txnE, txnerr) { setProcessing(false); 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, 'menu': currentMenu, 'isAdhocScreen': isAdhocScreen, 'isBeat': isBeatPlan, 'ShowCat': true });
        }
        else {
            props.navigation.navigate('SurveyView', { 'surveyData': item, 'storeData': storeData, 'menu': currentMenu, 'isAdhocScreen': isAdhocScreen, 'isBeat': isBeatPlan, 'ShowCat': false });
        }
    }
    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.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)