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 [webviewurl, setWebviewurl] = useState(false);
    const [processing, setProcessing] = useState(true);
    const [isDataFound, setisDataFound] = useState(false);
    const [reportData, setReportData] = useState([]);
    const [designation, setDesignation] = useState('');
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
      getData();
    }, []);
    

    async function getData(){        
      try {   
        let loginInfo=await get_item('loginInfo');
        const loginDetails=JSON.parse(loginInfo);
        let desg=loginDetails.Designation || '';
        setDesignation(desg);
        await db.transaction(async function (txn) {        
          
          let q=`SELECT * from Mapping_JourneyPlan where VisitDate='${d2}'`;
          let q2=`SELECT * from Adhoc_JourneyPlan where VisitDate='${d2}'`;
          await txn.executeSql(q,[],async function (txn2, txnres) { 
              if(txnres.rows.length>0){
                setisDataFound(true);
                let dd=await getReportData();
                setProcessing(false);
              }
              else{
                await txn.executeSql(q2,[],async function (txn2, txnres) { 
                  if(txnres.rows.length>0){
                    setisDataFound(true);
                    let dd=await getReportData();
                    setProcessing(false);
                  }
                  else{
                    setProcessing(false);
                  }
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);
              }
          },function (txnE,txnerr) { console.log(txnerr); setProcessing(false);},);
          
        });          
      } catch (err) {
        setProcessing(false);
        console.log(err);          
      }        
    }


    async function getReportData(){
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) { 
          let q=`SELECT * from Report_PromoterMerchandiserPerformance`;
          await txn.executeSql(q,[],async function (txn2, txnres) { 
            let arr=[]
            if(txnres.rows.length>0){
              for(var i=0;i<txnres.rows.length;i++){
                let data=txnres.rows.item(i);
                arr.push(data);
                if(i==txnres.rows.length-1){
                  console.log('reportData:',arr);
                  setReportData(arr);
                  resolve(true);
                }
              }
            }
            else{
              setReportData(arr);
              resolve(true);
            }
            
          },function (txnE,txnerr) { console.log(txnerr); resolve(false);},);
          
        }); 
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        return false;
      });  
       
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        <CustomHeader {...props} showaddstore={true} title={ST.Report}/>
        <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.reportCon}>
                    <View  style={customStyle.reportConHdr}>
                    <Text style={customStyle.reportConHdrText}>{ST.Performance}</Text>
                    </View>
                    
                    <View style={customStyle.report_TblHeader}>
                      <View style={[customStyle.report_TblHeaderBox,customStyle.report_TblHeaderBox1]}>
                        <Text style={[customStyle.report_TblHeaderTxt,{textTransform:'uppercase'}]}>{ST.Kpi}</Text>
                      </View>
                      <View style={[customStyle.report_TblHeaderBox,customStyle.report_TblHeaderBox2]}>
                        <Text style={customStyle.report_TblHeaderTxt}>{ST.Target}</Text>
                      </View>
                      <View style={[customStyle.report_TblHeaderBox,customStyle.report_TblHeaderBox3]}>
                        <Text style={customStyle.report_TblHeaderTxt}>{ST.Achivement}</Text>
                      </View>
                    </View>
                    <View style={customStyle.report_TblBody}>
                    {
                      reportData.length>0 &&
                      reportData.map((item,index)=>{
                        return(
                          <View style={[customStyle.reportItem,((index<(reportData.length-1))?customStyle.reportItemB:{})]} key={index}>
                            <View style={[customStyle.reportItemCol,customStyle.reportItemCol1]}>
                              <Text style={customStyle.reportItemColText}>{item.KPI}</Text>
                            </View>
                            <View style={[customStyle.reportItemCol,customStyle.reportItemCol2]}>
                              <Text style={customStyle.reportItemColText}>{item.Target}</Text>
                            </View>
                            <View style={[customStyle.reportItemCol,customStyle.reportItemCol3]}>
                              <Text style={customStyle.reportItemColText}>{item.Achivement}</Text>
                            </View>
                          </View>
                        )
                      })
                    }
                    </View>
                  </View>
                </ScrollView>
              }
                
            </View>
          }
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

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