import React, {useState, useEffect} from 'react';
import Container from '../components/container';
import {useRoute} from '@react-navigation/native';
import {globalStyles, customStyles, GetPageTheme} from '../styles/Global';
import {
  StatusBar,
  Image,
  TextInput,
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  Platform,
  PermissionsAndroid,
  FlatList,
} from 'react-native';
import {
  ReactReduxContext,
  connect,
  useSelector,
  useDispatch,
} from 'react-redux';
import {mapStateToProps, mapDispatchToProps} from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson, DownloadData} from '../controller/functions';
import {get_item, set_item, clear_item} from '../components/localStorage';
import {
  version,
  sloganline,
  appname,
  testurl,
  db,
} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card} from 'react-native-paper';
import {AntDesign} from '../components/icons';
import {WebView} from 'react-native-webview';
import CustomLoader from '../components/CustomLoader';
import NoDataComponent from '../components/NoDataComponent';
import LinearGradient from 'react-native-linear-gradient';

function ReportsMenu(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 [isDataFound, setisDataFound] = useState(false);
  const [reportData, setReportData] = useState([]);
  const [designation, setDesignation] = useState('');
  const [paramsState, setParamsState] = useState({});

  const d1 = new Date();
  const d2 = moment(d1).format('MM/DD/YYYY');

useEffect(() => {
  const params = route.params ?? props.route?.params ?? {};
  setParamsState(params);
  getData(params);
}, []);


  async function getData(props) {
    try {
      //let params=props.route.params? props.route.params:{};
      let params = props || {};
      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      let desg = loginDetails.Designation || '';
      let _fromStoreWise = params._fromStoreWise != null ? params._fromStoreWise : false;
      setDesignation(desg);
      console.log("_fromStoreWise---",_fromStoreWise);
      
      await db.transaction(async function (txn) {
        let q = `SELECT * from Master_MenuReports`;
        if (_fromStoreWise) {
          q = `SELECT * from Master_MenuReportStoreWise`;
        }

        txn.executeSql(
          q,
          [],
          async function (txn2, txnres) {
            console.log('txnres.rows.length:', txnres.rows.length,_fromStoreWise);
            if (txnres.rows.length > 0) {
              let arr = [];
              for (var i = 0; i < txnres.rows.length; i++) {
                let data = txnres.rows.item(i);
                arr.push(data);
                if (i == txnres.rows.length - 1) {
                  setReportData(arr);
                  setisDataFound(true);
                  setProcessing(false);
                }
              }

              if (_fromStoreWise && txnres.rows.length == 1) {
                console.log('txnres.rows.item(0)', txnres.rows.item(0));
                console.log("paramssss:",params)
                gotoReport(txnres.rows.item(0), params,true);
              }
            } else {
              setProcessing(false);
            }
          },
          function (txn2, txnerr) {
            console.log(txnerr);
            setProcessing(false);
          },
        );
      });
    } catch (err) {
      setProcessing(false);
      console.log(err);
    }
  }

  // function gotoReport(item, params) {
  //   console.log('item----', item + "\n"+params);
  //   let _fromStoreWise =
  //     params._fromStoreWise != null ? params._fromStoreWise : false;
  //   let isNonMerchans =
  //     params.isNonMerchans != null ? params.isNonMerchans : false;
  //   let isStoreSearch =
  //     params.isStoreSearch != null ? params.isStoreSearch : false;
  //   let isNonProgs = params.isNonProgs != null ? params.isNonProgs : false;
  //   let isAdhocScreen = params.isAdhoc != null ? params.isAdhoc : false;
  //   let isBeatPlan = params.isBeat != null ? params.isBeat : false;
  //   let storeData = params.storeData || {};
  //   if (item.ReportType == 'Graph') {
  //     props.navigation.navigate('ReportChart', {
  //       ReportData: item,
  //       _fromStoreWise: _fromStoreWise,
  //       'storeData': storeData,
  //       'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 
  //       'isNonMerchans': isNonMerchans, isNonProgs: isNonProgs, isStoreSearch: isStoreSearch
  //     });
  //   } else {
  //     props.navigation.navigate('ReportDetail', {
  //       ReportData: item,
  //       _fromStoreWise: _fromStoreWise,
  //       'storeData': storeData,
  //       'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 
  //       'isNonMerchans': isNonMerchans, isNonProgs: isNonProgs, isStoreSearch: isStoreSearch
  //     });
  //   }
  // }

   function gotoReport(item, params) {
    console.log('item----', item + "\n"+params);
    console.log("currentParams",currentParams);
    
     let currentParams = route.params || paramsState || {};
     let storeData = currentParams.storeData || {};    
     let _fromStoreWise = currentParams._fromStoreWise ?? false;

    let isStoreSearch =  currentParams.isStoreSearch ?? false;
    let isAdhocScreen = currentParams.isAdhoc ?? false;
    let isBeatPlan = currentParams.isBeat ?? false;
    let isNonMerchans = currentParams.isNonMerchans ?? false;
    let isNonProgs = currentParams.isNonProgs ?? false;

    if (item.ReportType == 'Graph') {
      props.navigation.navigate('ReportChart', {
        ReportData: item,
        _fromStoreWise: _fromStoreWise,
        'storeData': storeData,
        'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 
        'isNonMerchans': isNonMerchans, isNonProgs: isNonProgs, isStoreSearch: isStoreSearch
      });
    } else {
      props.navigation.navigate('ReportDetail', {
        ReportData: item,
        _fromStoreWise: _fromStoreWise,
        'storeData': storeData,
        'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 
        'isNonMerchans': isNonMerchans, isNonProgs: isNonProgs, isStoreSearch: isStoreSearch
      });
    }
  }

  return (
    <Container
      {...props}
      pt={0}
      avoidSafeArea={Platform.OS == 'ios' ? true : false}>
      {processing && <CustomLoader title={ST.Loading + '...'} />}
      <CustomHeader {...props} showaddstore={true} title={'Reports Menu'} />
      <LinearGradient
        colors={[PageTheme.$gradient1, PageTheme.$primary_color]}
        start={{x: 0, y: 0}}
        end={{x: 1, y: 0}}
        style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper]}>
          {!props.isDataDownloaded && <NoDataComponent {...props} />}
          {props.isDataDownloaded == true && (
            <View>
              {isDataFound == false && (
                <View style={customStyle.noDataCon}>
                  <Text style={customStyle.noDataText}>
                    {ST.NoDataAvailable}
                  </Text>
                </View>
              )}

              {isDataFound == true && (
                <ScrollView
                  contentContainerStyle={customStyle.rp_scrollViewInner}
                  style={customStyle.rp_scrollView}>
                  <View style={[customStyle.vlUinfo_Card]}>
                    <View
                      style={[
                        customStyle.vlUinfo_CardRow,
                        customStyle.vlUinfo_CardBorder,
                      ]}>
                      <Text style={customStyle.vlUinfo_lbl}>
                        {ST.Username + ' :'}
                      </Text>
                      <Text style={customStyle.vlUinfo_text}>
                        {props.UserId}
                      </Text>
                    </View>
                    <View style={customStyle.vlUinfo_CardRow}>
                      <Text style={customStyle.vlUinfo_lbl}>
                        {ST.Designation + ' :'}
                      </Text>
                      <Text style={customStyle.vlUinfo_text}>
                        {designation}
                      </Text>
                    </View>
                  </View>
                  <View style={customStyle.reportMenuCon}>
                    {reportData.length > 0 &&
                      reportData.map((item, index) => {
                        return (
                          <TouchableOpacity
                            style={[customStyle.reportMenuItem]}
                            key={index}
                            onPress={() => {
                             // gotoReport(item, props);
                             {console.log("checkprops:","--item",item, "----route",  route?.params, "paramsState--",paramsState )}
                              gotoReport(item, route?.params || paramsState);

                            }}>
                            <Text style={customStyle.reportMenuItemText}>
                              {item.ReportName}
                            </Text>
                          </TouchableOpacity>
                        );
                      })}
                  </View>
                </ScrollView>
              )}
            </View>
          )}
        </View>
      </LinearGradient>
    </Container>
  );
}

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