
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, getDownloadJson1, get_rowColSettings} 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, MaterialCommunityIcons} 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';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';

function DashboardReportDetail(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 [AllReports, setAllReports] = useState([]);
    const [aggrData, setAggrData] = useState({});
    const [cols, setcols] = useState([]);
    const [colWidth, setColWidth] = useState('100%');
    const [currentReportMenu, setCurrentReportMenu] = useState({});
    const [KPIId, setKPIId] = useState("");

    const [designation, setDesignation] = useState('');
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
      let params=props.route.params? props.route.params:{};
      let ReportMenu=params.ReportData || {};
      let AdKPIId=params.AdKPIId || "";

      setCurrentReportMenu(ReportMenu);
      setKPIId(AdKPIId);
      getData(ReportMenu);
    }, []);
    

    async function getData(ReportMenu){        
      try {
        let {DashboardId,DashboardName,ParentId}=ReportMenu
        db.transaction(async function (txn) { 
          // get data for report 
          let q=`Select * from Master_MenuAppDashboard where ParentId='${DashboardId}' `;
          console.log("Detailed reports q:",q);
          txn.executeSql(q,[],async function (txn2, txnres2) { 
              console.log("Detailed reports count:",txnres2.rows.length);
              if(txnres2.rows.length>0){
                let arr=[];
                for(var i=0;i<txnres2.rows.length;i++){
                  let data =txnres2.rows.item(i);
                  arr.push(data);
                  if(i==txnres2.rows.length-1){
                    setisDataFound(true);
                    setAllReports(arr);
                    setProcessing(false);
                  }                                
                } 
              }else{
                setisDataFound(false);
                setAllReports([]);
                setProcessing(false);
              }
          },function (txnE,txnerr) { console.log(txnerr); setAllReports([]); setProcessing(false);},);

        });   
        

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

    
    function _renderTabularReport(item){
      let report_key=item.DownloadKey;
      let reportContentObj=props.AppDashboardReports!=null && typeof props.AppDashboardReports=='object' && props.AppDashboardReports[report_key]!=null && props.AppDashboardReports[report_key]!=''?props.AppDashboardReports[report_key]:{};
      
      let report_data=reportContentObj['report_data']!=null?reportContentObj['report_data']:[];
      let filtered_data=report_data.length>0?report_data.filter(i=>i.AdKPIId==KPIId):[];
      let report_colWidth=reportContentObj['report_colWidth']!=null?reportContentObj['report_colWidth']:'50%';
      let report_cols=reportContentObj['report_cols']!=null?reportContentObj['report_cols']:[];
      // console.log("report_cols:",report_cols);
  
      return (
        <View style={customStyle.DashBTbl_ReportWrap} >
        <ScrollView horizontal={true} style={{width:'100%'}} contentContainerStyle={{}}>
          {/* render columns */}
          <View>
            {/* render header */}
            <View style={customStyle.DashBTbl_ReportHdr}>
            {report_cols.map((column,index)=>{
              return(
                <View style={[customStyle.DashBTbl_ReportHdrCol,customStyle.DashBTbl_ReportColW]}>
                  <Text  style={customStyle.DashBTbl_ReportHdrColTxt}>{column.colname}</Text>
                </View>
              )
            })}
            </View>
            {/* render content */}
            <View style={[customStyle.DashBTblBody]}>
              {filtered_data.map((row,row_index)=>{
                
                return(
                  <View style={[customStyle.DashBTbl_Item,(row_index==filtered_data.length-1?{}:customStyle.DashBTbl_ItemB)]}>
                    {report_cols.map((column,index)=>{
                      let colValue=row[column.actual_colname]!=null?row[column.actual_colname]:'';
                      
                      let color_obj=get_rowColSettings(colValue,column.actual_colname,row);
                    
                      let cust_style={},bg_style={};
                      if(color_obj.color!=null && color_obj.color!=''){
                        bg_style["backgroundColor"]=color_obj.color;
                        cust_style["color"]='#fff'
                      }
                      if(color_obj.fontsize!=null && color_obj.fontsize!=''){
                        cust_style["fontSize"]=color_obj.fontsize
                      }
                      if(color_obj.bold==1){
                        cust_style["fontWeight"]="600"
                      }
                      return(
                        <View style={[customStyle.DashBTbl_ItemCol,customStyle.DashBTbl_ReportColW,bg_style]}>
                          <Text  style={[customStyle.DashBTbl_ItemColText,cust_style]}>{colValue}</Text>
                        </View>
                      )
                    })}
                  </View>
                )
              })}
            </View>
          </View>
          
        </ScrollView>
        </View>
      )
    }
  
    function _renderDashboardReports(){
      
      return (
        <View>
          {AllReports.map((item,index)=>{
          console.log("report in detail page:",item);
          return (
            <View style={customStyle.DashB_ReportCon} key={index}>
              <View style={customStyle.DashB_ReportConHdr}> 
                <Text style={customStyle.DashB_ReportConHdrTxt}>{item.DashboardName}</Text>
              </View>
              <View style={customStyle.DashB_ReportContent}> 
                {item.DashboardType=='Tabular' && 
                  _renderTabularReport(item)
                }
              </View>
            </View>
          )
          })}
        </View>
      )
    }
    


    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        <CustomHeader {...props} showaddstore={true} title={'Dashboard 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]}>
          <View style={[customStyle.ImageTypesLHd,customStyle.ml10,customStyle.mr10]}>
            <Text  style={customStyle.ImageTypesLHdText}>{currentReportMenu.DashboardName+' Detail'}</Text>
          </View>
          {!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}
              >
                {_renderDashboardReports()}
              </ScrollView>
            }
              
          </View>
          }
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

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