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} 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 config=ReportMenu?.ColumnConfig
    //     let configValue= (config && JSON.parse(config))||[]
    //     let configArr=configValue.length>0? configValue : []
    //     setReportConfig(configArr)

    //     let allReportData= await DownloadReport(ReportMenu);
    //     console.log('allReportData',allReportData);
    //     console.log('ReportMenu',ReportMenu);
    //     if(allReportData.length>0){
    //         let data=allReportData[0];
    //         console.log('data dynamicdata-----',data);
    //         let ShowField= ShowField ? JSON.parse(data.ShowField) :''
          
    //         console.log(ShowField, "ShowField")


    //         if(data.ReportValue!=null && data.ReportValue!=''){
    //             let TotalIndex=allReportData.findIndex(i=>i.ReportValue=='Total');
    //             console.log('TotalIndex:',TotalIndex)
    //             if(TotalIndex>=0){
    //                 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);
    //         }

    //         console.log("Object.key---",Object.keys(data).length)
    //         let allCols=[];
    //         let i=0;
    //         let keylen=Object.keys(data).length;
             

    //         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' || colname=='ReportValue');
    //             if(!dontShowCol){
    //               allCols.push(obj);
    //             }
                
    //             if(i==keylen-1){
    //               console.log('allCols:',allCols);
    //                 setcols(allCols);
    //                 let colLen=allCols.length;
    //                 let width=94/colLen;
    //                 setColWidth(width+'%');
    //             }
    //             i++;
    //         }


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

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


    
    // async function getData(ReportMenu) {
    //   try {
    //     let config = ReportMenu?.ColumnConfig;
    //     let configValue = (config && JSON.parse(config)) || [];
    //     let configArr = configValue.length > 0 ? configValue : [];
    //     setReportConfig(configArr);
    
    //     let allReportData = await DownloadReport(ReportMenu);
    //     console.log('allReportData', allReportData);
    //     console.log('ReportMenu', ReportMenu);
    
    //     if (allReportData.length > 0) {
    //       let data = allReportData[0];
    //       console.log('data dynamicdata-----', data);
    //       let ShowField =  data.ShowField ?  JSON.parse(data.ShowField) : [];
    //       let ColorField = data.ColorField ?  JSON.parse(data.ColorField) : [];
    //       console.log(ShowField, "ShowField");
    
    //       if (data.ReportValue != null && data.ReportValue != '') {
    //         let TotalIndex = allReportData.findIndex(i => i.ReportValue === 'Total');
    //         console.log('TotalIndex:', TotalIndex);
    
    //         if (TotalIndex >= 0) {
    //           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 = [];
    //       if (ShowField.length > 0) {
    //         for (let i = 0; i < ShowField.length; i++) {
    //           let data1 = ShowField[i];
    //           if (data1.Show === "Y") {
    //             let obj = { actual_colname: data1.FieldName };
    //             let colname = data1.FieldName.replace(/[$$]/g, ' ').replace(/Percent/g, '%');
    //             obj['colname'] = colname;
    
    //             let colorobj = ColorField.find(c => c.FieldName === data1.FieldName);
    //             if (colorobj) {
    //               obj["Color"] = colorobj.Color;
    //             }
    
    //             console.log("Item,--", obj);
    //             allCols.push(obj);
    //           }
    //         }
    
    //         console.log('allCols:', allCols);
    //         setcols(allCols);
    //         let colLen = allCols.length;
    //         let width = 94 / colLen;
    //         setColWidth(width + '%');
    //       }
    
    //       setProcessing(false);
    //       setisDataFound(true);
    //     } else {
    //       notify('No data found');
    //       setProcessing(false);
    //     }
    //   } catch (err) {
    //     setProcessing(false);
    //     console.log(err, "errorr");
    //   }
    // }
    
    ///////////////////////////

    async function getData(ReportMenu) {
      try {
        // Extract and parse configuration
        let config = ReportMenu?.ColumnConfig;
        let configValue = (config && JSON.parse(config)) || [];
        let configArr = configValue.length > 0 ? configValue : [];
        setReportConfig(configArr);
    
        // Download report data
        let allReportData = await DownloadReport(ReportMenu);
        console.log('allReportData:', allReportData);
        console.log('ReportMenu:', ReportMenu);
    
        if (allReportData.length > 0) {
          let data = allReportData[0];
          console.log('data dynamicdata-----', data);
          let ShowField = data.ShowField ? JSON.parse(data.ShowField) : '';
          let ColorField = data.ColorField ? JSON.parse(data.ColorField) : '';
          console.log('ShowField:', ShowField);
          console.log('ColorField:', ColorField);
    
          if (ShowField.length > 0) {
            let allCols = [];
            for (let i = 0; i < ShowField.length; i++) {
              let data1 = ShowField[i];
              if (data1.Show === "Y") {
                let obj = { actual_colname: data1.FieldName };
                let colname = data1.FieldName.replace(/[$$]/g, ' ').replace(/Percent/g, '%');
                obj['colname'] = colname;
    
                let colorobj = ColorField.find(c => c.FieldName === data1.FieldName);
                if (colorobj) {
                  obj["Color"] = colorobj.Color;
                }
    
                console.log("Item,--", obj);
                allCols.push(obj);
              }
            }
    
            console.log('allCols:', allCols);
            setcols(allCols);
            let colLen = allCols.length;
            let width = 94 / colLen;
            setColWidth(width + '%');
          } else {
            // If ShowField is empty, fall back to processing keys directly from data
            let allCols = [];
            let keylen = Object.keys(data).length;
            let i = 0;
    
            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' || colname === 'ReportValue');
              if (!dontShowCol) {
                allCols.push(obj);
              }
    
              if (i === keylen - 1) {
                console.log('allCols:', allCols);
                setcols(allCols);
                let colLen = allCols.length;
                let width = 94 / colLen;
                setColWidth(width + '%');
              }
              i++;
            }
          }
    
          // Set the report data
          setReportData(allReportData);
          setProcessing(false);
          setisDataFound(true);
        } else {
          notify('No data found');
          setProcessing(false);
        }
      } catch (err) {
        setProcessing(false);
        console.error('Error:', err);
      }
    }
    
    
    

    async function DownloadReport(ReportMenu){
        let downloadKey=ReportMenu.DownloadKey;
        console.log(downloadKey , "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 getDownloadJson1(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={currentReportMenu?.ContentType || '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 || currentReportMenu?.ContentType}</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}
                >
                  
                  {currentReportMenu.ReportType=='Tabular' &&
                  <ScrollView
                  horizontal={true}
                >
                  <View style={[customStyle.reportCon,{width:"100%"}]}>
                    
                    <View style={customStyle.report_TblHeader}>
                        {cols?.map((col,colindex)=>{
                            return (
                            <View style={[customStyle.report_TblHeaderBox,{minWidth:120,maxWidth:120},(colindex==0?{marginLeft:0}:{}),(colindex==(cols.length-1)?{marginRight:0}:{})]}>
                                <Text style={[customStyle.report_TblHeaderTxt]}>{col.actual_colname?.replace(/\$\$/g, ' ')}</Text>
                            </View>
                            )
                        })
                        }
                    </View>
                    <View style={[customStyle.report_TblBody, {paddingBottom :50}]}>
                    {
                      reportData?.length>0 &&
                      reportData?.map((item,index)=>{

                        let FieldName=reportConfig[0]?.FieldName
                        let FieldNameObj=reportConfig?.find((val)=>{
                          return item[val?.FieldName]==val?.FieldValue
                        })
                        let configValueMatch=item[FieldNameObj?.FieldName]==FieldNameObj?.FieldValue
                        
                        
                        return(
                          <View style={[customStyle.reportItem,{paddingVertical:0},(index%2!=0?customStyle.reportItemBg:{}),((index<(reportData.length-1))?customStyle.reportItemB:{})]} key={index}>
                            {cols.map((col,colindex)=>{
                              let keyValue=col.actual_colname!=null?item[col.actual_colname]:''

                              let ColorArr= configValueMatch? FieldNameObj?.Color : null
                              let str=String(keyValue).replace("%","")
                              let ColorCode=ColorArr?.find((item)=>{
                                  if(!isNaN(str)){
                                    return eval(str+(item?.MinRange||""))&& (eval(str+(item?.MaxRange||"")))
                                  }
                                  return false
                                })

                                return (
                                <View style={[customStyle.reportItemCol,{minWidth:120,maxWidth:120,paddingVertical:8, alignItems:'flex-start', marginLeft :2},(colindex==0?{marginLeft:0}:{}),(colindex==(cols.length-1)?{marginRight:0}:{}),(ColorCode?.Color?{backgroundColor:ColorCode?.Color}:null)]}>
                                  <Text style={[customStyle.reportItemColText,{paddingLeft :10} ,(ColorCode?.Color?{backgroundColor:ColorCode?.Color,color:"white"}:null)]}>{keyValue}</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>
                                    <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>
                                </View>
                            }
                            {
                            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>
                                )
                            })
                            }
                        </View>
                    </View>
                  }
                </ScrollView>
              }
                
            </View>
          }
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

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