
import React,{useState,useEffect} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme, WP } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Modal, StyleSheet, Pressable} 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';
import cross_icon from '../assets/icons/crossmodal.svg';
import { SvgXml } from 'react-native-svg';


function PeopleDrilldown(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 [modaldata, setModalData] = useState({colname: '', colValue:'', 'row':{}});


    // modal 
    const [modalVisible, setModalVisible] = useState(false);
    const toggleModal = (colname, colValue, row) => {
      setModalVisible(!modalVisible);
      setModalData({colname:colname , colValue: colValue, row:row})
    };

    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 || "";
      let data = params?.data || [];
      let empdata = params?.empdata || {};

    //   console.log("ReportMenu",ReportMenu ,"AdKPIId",AdKPIId , "data------ ", data[0] , "empdata--",empdata)
      setCurrentReportMenu(ReportMenu);
      setKPIId(AdKPIId);
      getData(AdKPIId ,data, empdata);

    }, []);

    async function getData(AdKPIId ,data,empdata){  
        setProcessing(true);

        try {
          let {DashboardId,DashboardName,ParentId}=data[0] ;
          db.transaction(async function (txn) { 
            // get data for report 
            let q=`Select * from Sup_MenuAppDashboard where ParentId='${DashboardId}' `;
            console.log("people brandwise reports q:",q);
            txn.executeSql(q,[],async function (txn2, txnres2) { 
                console.log("people brandwise 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){
                      getFTMBrandwiseData(AdKPIId,arr,empdata);
                    }                                
                  } 
                }else{
                  setisDataFound(false);
                  setProcessing(false);
                }
            },function (txnE,txnerr) { console.log(txnerr);  setProcessing(false);},);
  
          });   
          
  
        } catch (err) {
          setProcessing(false);
          console.log(err);          
        }        
      }

    // get data of drilldown
    async function getFTMBrandwiseData(AdKPIId, data, empdata) {
      
        try {
          let allData = await DownloadReport(AdKPIId,data,empdata);
      
          if (allData.length > 0) {
           
            let allCols = [];
            let columnWidth = '50%'; 
            let keylen = Object.keys(allData[0] || {}).length;  
            for (let row of allData) {
              let i = 0;
              for (let key in row) {
                if (i < keylen) {
                  let obj = { 'actual_colname': key }; 
      
                
                  let colname = key.replace(/[$$]/g, ' ').replace(/Percent/g, '%');
                  obj['colname'] = colname;
      
                  
                  let dontShowCol = (
                    colname === 'Srno' || 
                    colname === 'AdKPIId' || 
                    colname === 'Color' || 
                    colname === 'DisplayOrder' || 
                    colname === 'KPIDrilldown'
                  );
      
                  // Add unique columns to display
                  if (!dontShowCol && !allCols.some(col => col.actual_colname === key)) {
                    allCols.push(obj);
                  }
                }
                i++;
              }
            }
      
  
            if (allCols.length > 0) {
              let colLen = allCols.length;
              columnWidth = (94 / colLen) + '%';  
            }
      
           
            let defData = {
              "success": true,
              "data": {
                "report_data": allData,         
                "report_colWidth": columnWidth, 
                "report_cols": allCols        
              }
            };
      
          
            setAllReports(defData?.data);
            setProcessing(false);
            setisDataFound(true);
          } else {
            notify(ST.Nodatafound);
            setAllReports([]);
            setProcessing(false);
            setisDataFound(false);
          }
        } catch (err) {
          console.error('Error fetching data:', err);
          setAllReports([]);
          setProcessing(false);
          setisDataFound(false);
      }}
      
    
      async function DownloadReport(AdKPIId, data1, empdata){

        let downloadKey = data1[0]?.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: AdKPIId,
            Param2: empdata?.EmpId,
          };
    
          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 [];
          }); 
      }


    //end 

    
    function _renderTabularReport(){

     let filtered_data=AllReports?.report_data?.length>0?AllReports?.report_data.filter(i=>i.AdKPIId==KPIId):[];
  
      return (
        <View style={customStyle.DashBTbl_ReportWrap} >
        <ScrollView horizontal={true} style={{width:'100%'}} contentContainerStyle={{}}>
          {/* render columns */}
          <View>
            {/* render header */}
            <View style={customStyle.DashBTbl_ReportHdr}>
            {AllReports?.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.DashBTblBodyNB1]}>
             <View style={[customStyle.DashBTblBodyNB2]}>
              {filtered_data.map((row,row_index)=>{
                
                return(
                  <View style={[customStyle.DashBTbl_Item,(row_index==filtered_data.length-1?{}:customStyle.DashBTbl_ItemB)]}>
                    {AllReports?.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(
                         <TouchableOpacity style={[customStyle.DashBTbl_ItemCol,customStyle.DashBTbl_ReportColW,bg_style]} onLongPress={()=> toggleModal(column.colname,colValue, row)}>
                          <Text  style={[customStyle.DashBTbl_ItemColText,cust_style]}>{colValue}</Text>
                        </TouchableOpacity>
                        
                      )
                    })}
                  </View>
                )
              })}
             </View>
            </View>
          </View>
          
        </ScrollView>
        </View>
      )
    }
  
    function _renderDashboardReports(){
        return (
              <View style={customStyle.DashB_ReportContent}> 
                {
                  _renderTabularReport()
                }
              </View>
          )
    }

    const excludeKeys = ['AdKPIId'];

    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        <CustomHeader {...props} title={'People 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.KPI+' Detail'}</Text>
          </View>
         
          <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()}

                <Modal
                animationType="fade"
                transparent={true}
                visible={modalVisible}
                onRequestClose={() => {
                  Alert.alert('Modal has been closed.');
                  setModalVisible(!modalVisible);
                }}>
                <View style={customStyle.modalContainer}>
                  <View style={customStyle.centeredView}>
                    <View style={customStyle.modalView}>

                    <TouchableOpacity style={[customStyle.modalrow, {justifyContent:'space-between'}]} onPress={()=> setModalVisible(false)}>
                      <View><Text style={[customStyle.DashBTbl_ReportHdrColTxt, {color:'#000', fontWeight:'700', fontSize:16}]}>{currentReportMenu.KPI+' Detail'}</Text></View>
                      <View style={{marginLeft:10}}><SvgXml width={35} height={35} xml={cross_icon}/></View>
                    </TouchableOpacity>

                    <View style={customStyle.modalInView}>
                      {Object.entries(modaldata?.row)
                        .filter(([key]) => !excludeKeys.includes(key)) // Filter out excluded keys
                        .map(([key, value]) => (
                          <View key={key} style={customStyle.modalrow}>
                            <Text style={[customStyle.DashBTbl_ReportHdrColTxt, {color:'#000', fontWeight:'700'}]}>{key}: </Text>
                            <Text style={[customStyle.DashBTbl_ReportHdrColTxt, {color:'#000'}]}>{value.toString()}</Text>
                          </View>
                        ))}
                    </View>

                    </View>
                  </View>
                </View>
                </Modal>
              </ScrollView>
            }
              
          </View>
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

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


const styles = StyleSheet.create({
   // modal
})