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

function ReportDetail(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 [reportConfig, setReportConfig] = useState([]);
    const [aggrData, setAggrData] = useState({});
    const [cols, setcols] = useState([]);
    const [colWidth, setColWidth] = useState('100%');
    const [currentReportMenu, setCurrentReportMenu] = 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 || {};

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

    async function getData(ReportMenu){        
      try {
        let allReportData= await DownloadReport(ReportMenu);
        console.log('allReportData',ReportMenu?.ColumnConfig,"-----",allReportData);
        if(allReportData.length>0){
            let data=allReportData[0];
            console.log('data--h',data);
            if(data.ReportValue!=null && data.ReportValue!=''){
                let TotalIndex=allReportData.findIndex(i=>i.ReportValue=='Total');
                console.log('TotalIndex:',TotalIndex)
                if(TotalIndex>=0 && currentReportMenu?.ReportType=='Tabular')
                {
                    let aggrgateData=allReportData[TotalIndex];
                    console.log('aggrgateData',aggrgateData);
                    setAggrData(aggrgateData);
                    let newReports=allReportData
                    newReports.splice(TotalIndex,1);
                    console.log('newReports',newReports);
                    setReportData(newReports);
                }
                else{
                    setReportData(allReportData);
                }
            }
            else{
                setReportData(allReportData);
            }
            let allCols=[];
            let i=0;
            let keylen=Object.keys(data).length;
             
            let repoLen=ReportMenu?.ColumnConfig;
            if(repoLen && repoLen.length){
               let repoLenStr=repoLen.replace(/[$$]/g,' ').replace(/Percent/g,'%');
              let config=JSON.parse(repoLenStr)
              if(config && config.length>0){
                console.log("config------",config)
                setReportConfig(config)
              }
            }else{
              setReportConfig([])
            }
        

            for(let key in data)
                {
                    let obj={'actual_colname':key};
                    let colname=key.replace(/[$$]/g,' ').replace(/Percent/g,'%');
                    obj['colname']=colname;
                    let dontShowCol=(colname=='Srno');
                    // let dontShowCol=(colname=='Srno' || colname=='ReportValue');
                    if(!dontShowCol){
                      allCols.push(obj);
                }
                    
                    if(i==keylen-1)
                    {
                      console.log('allCols:',allCols);
                        setcols(allCols);
                        let colLen=allCols.length;
                        let width=97/colLen;
                        setColWidth(width+'%');
                    }
                    i++;
                }
            

            setProcessing(false);
            setisDataFound(true);
        }
        else
        {
            notify('No data found');
            setProcessing(false);
        }
        

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

    async function DownloadReport(ReportMenu){
        let downloadKey=ReportMenu.DownloadKey;
        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
        const url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
        let data={
          Downloadtype:downloadKey,
          Username: loginDetails.UserId,
          Param1: '',
          Param2: '',
        };
  
        console.log(url,data);
        return await getDownloadJson12(url,data)
        .then(async(res)=>{  
          if (res[downloadKey]) {
            let data_arr = res[downloadKey] || []; 
            return data_arr;
          }
          else{
            return [];
          }        
        })
        .catch((err)=>{
          console.log('onPage Team error',err);
          return [];
        }); 
    }

    


    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        <CustomHeader {...props} title={'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,customStyle.ImageTypesPageWrap]}>
            <View style={customStyle.ImageTypesLHd}>
                <Text  style={customStyle.ImageTypesLHdText}>{currentReportMenu.ReportName}</Text>
            </View>
            { !props.isDataDownloaded && <NoDataComponent {...props}/>}
            { props.isDataDownloaded==true && 
              <View style={{ flex: 1 }}>
                { isDataFound==false && 
                  <View style={customStyle.noDataCon}>
                    <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
                  </View>
                }
                {
                  isDataFound &&
                  <ScrollView contentContainerStyle={customStyle.geotag_scroll} style={{}}>
                  { currentReportMenu.ReportType=='Tabular' &&
                    <ScrollView
                        horizontal={true}
                      >
                        <View key={1} 
                        // style={{height:'100%'}}
                        >
                          <View style={customStyle.report_TblHeader} >
                            {
                              cols.length>0 &&
                              cols.map((item,index)=>{
                                let colorObj=reportConfig.find(i=>i.FieldName==item.colname);
                                if(reportConfig.length>0 && colorObj!==undefined && colorObj!="" ){
                                  console.log("colorObj------",colorObj)
                                  if(colorObj?.Show=="Y"){
                                    return(
                                      <View style={[customStyle.report_TblHeaderBox,{width:100},(index==0?{marginLeft:0}:{}),(index==(cols.length-1)?{marginRight:0}:{})]} key={index}>
                                        <Text style={[customStyle.report_TblHeaderTxt]}>{item.colname}</Text>
                                      </View>
                                    )
                                  }else{
                                    return
                                  }

                                }
                                return(
                                  <View style={[customStyle.report_TblHeaderBox,{width:100},(index==0?{marginLeft:0}:{}),(index==(cols.length-1)?{marginRight:0}:{})]} key={index}>
                                    <Text style={[customStyle.report_TblHeaderTxt]}>{item.colname}</Text>
                                  </View>
                                )})
                            }
                          </View>
                        
                          <View 
                          // style={[customStyle.report_TblBody,{padding:10}]}
                          style={[{
                            backgroundColor:PageTheme.$bg_color,
                            borderRadius:10,
                            paddingLeft:5,paddingBottom:10,marginBottom:60,paddingRight:5,
                            paddingTop:5, elevation:3,shadowColor:'#5f5f5f',shadowOffset: { width: 0, height: 2 } , shadowOpacity:1.0
                          },
                          {padding:10}]}
                          >
                          {
                            reportData.length>0 &&
                            reportData.map((item,index)=>{
                              let colorCodeBg="";
                              if(item?.ReportValue=='Total'){
                                  colorCodeBg="#FFFF00"
                                }
                              return(
                                <View   
                                key={index} 
                                style={[customStyle.DYStSC_RItem,((index<(reportData.length-1))?customStyle.StSC_RtemB:{})]} 
                                >
                                  {cols.map((col,colindex)=>{
                                        {/* let colorCode=item && col? ( col.Color=="Y"?(item.COLOR||"black") :"black") :"black"; */}

                                        let colorObj=reportConfig.find(i=>i.FieldName==col.actual_colname);
                                        if(reportConfig.length>0 && colorObj!==undefined && colorObj!="" ){
                                          if(colorObj?.Show=="Y"){
                                            let colorCode= colorObj.Color=="Y"?(colorObj?.ColorValue||"black") :"black";
                                            let colorCodeStr= colorCode.toLowerCase()
                                            
                                            return (
                                                <View key={colindex} style={[customStyle.DYreportItemCol,{width:100,backgroundColor:colorCodeBg},(colindex==0?{marginLeft:0}:{}),(colindex==(cols.length-1)?{marginRight:0}:{alignItems:"left"}),{justifyContent:"center",alignItems:"center"}]}>
                                                    <Text style={[customStyle.reportItemColText,{color:colorCodeStr}]}>{col.actual_colname!=null?item[col.actual_colname]:''}</Text>
                                                </View>
                                                )
                                          }else{
                                            return
                                          }
                                        }

                                        return (
                                        <View key={colindex} style={[customStyle.DYreportItemCol,{width:100,backgroundColor:colorCodeBg},(colindex==0?{marginLeft:0}:{}),(colindex==(cols.length-1)?{marginRight:0}:{alignItems:"left"}),{justifyContent:"center",alignItems:"center"}]}>
                                            <Text style={[customStyle.reportItemColText,{color:"black"}]}>{col.actual_colname!=null?item[col.actual_colname]:''}</Text>
                                        </View>
                                        )
                                    })}
                                </View>
                              )
                            })
                          }
                          </View>
                        </View>
                    </ScrollView>
                    }
                  {currentReportMenu.ReportType=='Card' &&
                  <View style={customStyle.reportCon}>
                    <View style={customStyle.report_CardsWrap}>
                      {Object.keys(aggrData).length>0 && 
                          <View style={[customStyle.report_CardI,customStyle.report_CITotal]} key={'Total'}>
                              <View style={[customStyle.report_CardITHdr]}>
                                  <Text style={[customStyle.report_CardITHdrText]}>{'Total'}</Text>
                              </View>
                              {
                              isDataFound==true &&
                              <ScrollView
                              contentContainerStyle={customStyle.rp_scrollViewInner}
                                style={customStyle.rp_scrollView}
                              >
                              <View style={[customStyle.report_CardITBody]}>
                              {cols.map((col,colindex)=>{
                                  let colindex1=colindex;
                                  return (
                                  <View style={[customStyle.report_CardIRow,(colindex1<(cols.length-1)?customStyle.report_CIRT_BorderBtm:{})]}>
                                      <Text style={[customStyle.report_CardIRow_Lbl,customStyle.report_CIR_LblTotal]}>{col.colname+' :'}</Text>
                                      <Text style={[customStyle.report_CardIRow_Val,customStyle.report_CIR_ValTotal]}>{col.colname!=null?aggrData[col.actual_colname]:''}</Text>
                                  </View>
                                  )
                              })
                              }
                              </View>
                              </ScrollView>
    }
                          </View>
                      }
                      {
                      
                      isDataFound==true &&
                      <ScrollView
                      contentContainerStyle={customStyle.rp_scrollViewInner}
                        style={customStyle.rp_scrollView}
                      >
                      {
                      reportData.length>0 &&
                      reportData.map((item,index)=>{
                          let isEvenRow=index%2!=0;
                          return(
                          <View style={[customStyle.report_CardI,((index<(reportData.length-1))?customStyle.reportItemB:{})]} key={index}>
                              {cols.map((col,colindex)=>{
                                  let colindex1=colindex;
                                  return (
                                  <View style={[customStyle.report_CardIRow,(colindex1<(cols.length-1)?customStyle.report_CardIRow_BorderBtm:{})]}>
                                      <Text style={customStyle.report_CardIRow_Lbl}>{col.colname+' :'}</Text>
                                      <Text style={customStyle.report_CardIRow_Val}>{col.colname!=null?item[col.actual_colname]:''}</Text>
                                  </View>
                                  )
                              })
                              }
                          </View>
                          )
                      })
                    }
                      </ScrollView>
                      }
                    </View>
                  </View>
                  }
                </ScrollView>
                }
                
              </View>
            }
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

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