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

function SurveyCat(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 [ActiveSurvey, setActiveSurvey] = useState({});
  const d1 = new Date();
  const d2 = moment(d1).format('MM/DD/YYYY');
  const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

  useEffect(() => {
    setLoaderTitle(ST.Loading + '...')
    let params = props.route.params ? props.route.params : {};
    let storeData1 = params.storeData || {};
    let surveydata = params.surveyData || {};
    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);
    setActiveSurvey(surveydata)
    setCurrentMenu(menu1);
    getData(surveydata, storeData1);
    navigateautoSurveyView(props, params)

    const willFocusSubscription = props.navigation.addListener('focus', () => {
      getData(surveydata, storeData1);
    });

    return willFocusSubscription;

  }, []);


  useEffect(() => {
    console.log('on AutoGoToPrev change', props.AutoGoToPrev);
    if (props.AutoGoToPrev == true) {
      let params = props.route.params ? props.route.params : {};
      let storeData1 = params.storeData || {};
      let surveydata = params.surveyData || {};
      getData(surveydata, storeData1, true);
    }
  }, [props.AutoGoToPrev]);


  async function navigateautoSurveyView(props, params) {
    let storeData1 = params.storeData || {};
    let surveydata = params.surveyData || {};
    let menu1 = params.menu || {};
    let isAdhoc = params.isAdhocScreen || false;
    let isBeat = params.isBeat != null ? params.isBeat : false;
    let windData = await get_item('storeData')
    if (windData != null && windData != '') {
      let StoreJson = JSON.parse(windData)
      let { CategoryInfo } = StoreJson
      console.log("windData in promooo1111:", CategoryInfo);
      await delay(400); // 1 second delay
      props.navigation.navigate('SurveyView', {
        'surveyData': surveydata, 'catData': CategoryInfo, 'storeData': storeData1,
        'menu': menu1, 'isAdhocScreen': isAdhoc, 'isBeat': isBeat, 'ShowCat': true
      });
    }
  }

  async function getData(surveydata, storeData1, isAutoBack = false) {
    try {

      let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;

      await db.transaction(async function (txn) {
        let q2 = `SELECT DISTINCT T.Category,T.CategoryId , T.CategorySequence FROM Master_SurveyQuestion T INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId WHERE M.StoreId='${StoreId}' and T.SurveyId='${surveydata.SurveyId}' order by T.CategorySequence`;
        await txn.executeSql(q2, [], async function (txn2, txnres) {
          console.log('survey cats:', txnres.rows.length);
          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 isDone = await checkIf_surveyCatDone(storeData1, surveydata.SurveyId, data.CategoryId, true)
              data['isDone'] = isDone;
              arr.push(data);
              if (!isDone) {
                isAllSurveyDone = false;
              }
              if (i == txnres.rows.length - 1) {
                setSurveys(arr);
                setProcessing(false);
                //console.log('isAllSurveyDone cat :',isAllSurveyDone,props.AutoGoToPrev,isAutoBack)
                if (isAllSurveyDone == true && props.AutoGoToPrev == true && isAutoBack == true) {
                  props.navigation.goBack();
                }
              }
            }
          }

        }, function (txnE, txnerr) { console.log(txnerr); },);

      });
    } catch (err) {
      console.log(err);
    }
  }



  function openSurveyView(item) {
    props.set_autoback({ 'AutoGoToPrev': false });
    console.log("item00000", item);
    props.navigation.navigate('SurveyView', { 'surveyData': ActiveSurvey, 'catData': item, 'storeData': storeData, 'menu': currentMenu, 'isAdhocScreen': isAdhocScreen, 'isBeat': isBeatPlan, 'ShowCat': true });
  }


  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]}>
          <View style={customStyle.SVn_activeSurvey}>
            <LinearGradient colors={[PageTheme.$primary_color, PageTheme.$gradient1]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.SVn_activeSurvey_tile}>
              <Text style={customStyle.SV_activeSurvey_name}>{(ActiveSurvey.SurveyName != null ? (ActiveSurvey.SurveyName.length > 26 ? ActiveSurvey.SurveyName.substring(0, 26) + '...' : ActiveSurvey.SurveyName) : '')}</Text>
            </LinearGradient>
          </View>
          {Object.keys(storeData).length > 0 &&
            <FlatList
              data={surveys}
              contentContainerStyle={customStyle.surveyListInner}
              style={[customStyle.surveyCatList]}
              renderItem={({ item, index }) => {
                { console.log("Item---", item) }
                return (
                  <TouchableOpacity activeOpacity={0.7} style={customStyle.surveyItem} onPress={() => { openSurveyView(item) }}>
                    <View style={customStyle.surveyCatItem}>
                      <View style={customStyle.surveyCatItem_Circle}>
                        <Text style={customStyle.surveyCatItem_CircleText}>{item.Category.substring(0, 1)}</Text>
                      </View>
                      <Text style={customStyle.surveyCatItem_name}>{item.Category}</Text>
                      {(item.isDone != null && item.isDone == true) && <View style={customStyle.surveyCatItem_Check}><AntDesign color={'green'} size={23} name='checkcircle' /></View>}
                    </View>
                  </TouchableOpacity>
                );
              }}
            />
          }
        </View>
      </LinearGradient>
    </Container>
  );
}



export default connect(mapStateToProps, mapDispatchToProps)(SurveyCat);