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

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 globalStyle=globalStyles(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':{}, item :{}});

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

    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();
    }, []);
    

    async function getData(){        
      try {
       
        db.transaction(async function (txn) { 
          // get data for report 
          let q=`Select * from Sup_MenuAppDashboard where DashboardSection ='DetailScreen' order by DisplayOrder`;
          console.log("Dashboard 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);          
      }        
    }

    const [activeTab, setActiveTab] = useState(0);

    const mainScreenTabs = AllReports?.filter(item => item?.DashboardSection == "DetailScreen")?.map(item => item?.TabName)?.filter(tabName => tabName); 


    const uniqueTabs = [...new Set(mainScreenTabs)];
 
       const tabs = uniqueTabs.map((tabName) => ({
         title: tabName, 
        //  content: '' , 
       }));
 
    
    const filteredData = AllReports?.filter((item) => item?.TabName?.includes(tabs[activeTab]?.title));

    function _renderTabularReport(item, index ,filteredData){
    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 tabName = item?.TabName || '' ;
    // {"report_data":data_arr,"report_colWidth":columnWidth,"report_cols":allCols}
    let report_data=reportContentObj['report_data']!=null?reportContentObj['report_data']:[];
    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} >
      {/* render No data */}
      {report_data.length<=0 && <View style={customStyle.DashBTbl_NoDataCon}><Text style={customStyle.DashBTbl_NoDataText}>No Data</Text></View>}
      {report_data.length>0 && <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.DashBTblBodyNB1]}>
            <View style={[customStyle.DashBTblBodyNB2]}>
              {report_data.map((row,row_index)=>{
                return(
                  <TouchableOpacity disabled={row.KPIDrilldown?false:true} style={[customStyle.DashBTbl_Item,{backgroundColor:'', paddingVertical:0},(row_index==report_data.length-1?{}:customStyle.DashBTbl_ItemB)]} 
                  onPress={()=>{props.navigation.navigate("DashboardDrilldown",{"ReportData":row,"AdKPIId":row["AdKPIId"] , "tabName" : tabName , "data" : filteredData})}}
                  >
                    {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  
                          // disabled={row.KPIDrilldown?false:true}
                          style={[customStyle.DashBTbl_ItemCol,customStyle.DashBTbl_ReportColW,bg_style]} 
                          onLongPress={()=> toggleModal(column.colname,colValue, row , item)}
                          onPress={()=>{props.navigation.navigate("DashboardDrilldown",{"ReportData":row,"AdKPIId":row["AdKPIId"] , "tabName" : tabName , "data" : filteredData})}}
                        >
                          <Text  style={[customStyle.DashBTbl_ItemColText,cust_style]}>{colValue}</Text>
                        </TouchableOpacity>
                      )
                    })}
                  </TouchableOpacity>
                )
              })}
            </View>
          </View>
        </View>
        
      </ScrollView>}
      </View>
    )
  }
  

  function _renderCardReport(item,index, filteredData){

    let tabName = item?.TabName || '' ;

    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]:{};
    // {"report_data":data_arr,"report_colWidth":columnWidth,"report_cols":allCols}
    let report_data=reportContentObj['report_data']!=null?reportContentObj['report_data']:[];
    let report_colWidth=reportContentObj['report_colWidth']!=null?reportContentObj['report_colWidth']:'50%';
    let report_cols=reportContentObj['report_cols']!=null?reportContentObj['report_cols']:[];
    let ShowGraph = item?.ShowGraph ;
    let isLastItem = report_data.length % 2 !== 0 && index == report_data.length - 1;
    console.log(isLastItem,"isLastItem", report_data)

    const renderItemcardNew = (item, index, tabName, ShowGraph, isLastItem, isOdd) => {
      let gset_obj = item["Color"] != null && item["Color"] !== '' ? item["Color"] : {};

      const chartConfig = {
        backgroundGradientFrom: "#fff",
        backgroundGradientTo: "#fff",
        color: (opacity = 1, dataIndex) => {
          // If there's a color available for the current dataIndex, use it, else set it transparent
          const color = gset_obj; // Get the color based on index
          return color ? `${color}${Math?.floor(opacity * 255)?.toString(16)?.padStart(2, '0')}` : `rgba(255, 255, 255, 0)`; 
        },
        strokeWidth: 2,
        barPercentage: 0.5,
        useShadowColorFromDataset: false ,
      };

        let label=[];
        let labelVal=[];
        let barColor=[];

        label.push(item?.KPI); 
        let percentage = item?.PER?.replace('%', '');

        if(percentage > 100) {
          labelVal.push(parseFloat(100) / 100);
        } else {
        labelVal.push(parseFloat(item?.PER) / 100);  
        }

        barColor.push(() => item?.Color);  

        let showgraph = ShowGraph ? ShowGraph : false;
        // let itemStyle = isOdd && isLastItem ? { flex: 0.98, marginLeft: 'auto', marginRight: 'auto', width: '95%' } : { flex: 0};
        
      return(
        <TouchableOpacity
          disabled={item.KPIDrilldown ? false : true}
          style={[
            customStyle.DashBCard_ItemNB1,
            { width: WP(isOdd && isLastItem ? '92%' : '45%'),margin: 5,paddingVertical:0,paddingHorizontal:0 }
          ]}
          onPress={() => {
            props.navigation.navigate("DashboardDrilldown", {
              "ReportData": item,
              "AdKPIId": item["AdKPIId"],
              "tabName" : tabName,
              "data" : filteredData
            });
          }}
        >

        <View style={[ customStyle.DashBCard_ItemNB2,{ width: WP(isOdd && isLastItem ? '92%' : '45%'),margin: 0,paddingVertical:0 }]}>
          <View style={[customStyle.DashBCard_ItemContent, {paddingVertical:10}]}>

          <View style={{flexDirection:'row',alignItems:'center', justifyContent:'space-between'}}>
            {item?.KPI != null && item?.KPI != undefined  && <Text style={{color :'#000', fontSize:13,fontWeight:'700'}}>{item?.KPI}</Text>}

            {item.KPIDrilldown && <View style={[globalStyle.drawerItemIcon, {width :15}]}><Feather name="chevron-right" size={20} color={'#787878'}/></View>}
          </View>

          {item?.TGT != null && item?.TGT != undefined &&
            <View style={{flexDirection:'row', alignItems:'center', marginTop:10}}>
              <Text style={{color :'#000', fontSize:13,fontWeight:'400'}}>Target: </Text>
              <Text style={{color :'#000', fontSize:16,fontWeight:'500'}}>{item?.TGT}</Text>
            </View>
            }

            {item?.ACT != null && item?.ACT != undefined && (
              !showgraph ? (
                <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 15, marginBottom: 10}}>
                  <View>
                    <Text style={{color: '#000', fontSize: 24, fontWeight: '700'}}>{item?.ACT}</Text>
                    <Text style={{color: '#000', fontSize: 13, fontWeight: '400'}}>Achievement</Text>
                  </View>
                  <View style={{alignSelf: 'center', marginTop: 10, borderColor: `${gset_obj}`, borderWidth: 1, borderRadius: 5, padding: 8}}>
                    <Text style={{color: `${gset_obj}`, fontSize: 18, fontWeight: '500'}}>{item?.PER}</Text>
                  </View>
                </View>
              ) : (
                  <View style={{flexDirection: 'row',justifyContent: 'space-between',alignItems: 'center', marginTop: 10 }}>
                    <View>
                      <Text style={{color: '#000', fontSize: 24, fontWeight: '700'}}>{item?.ACT}</Text>
                      <Text style={{color: '#000', fontSize: 13, fontWeight: '400'}}>Achievement</Text>
                    </View>
                    <View style={styles.chartContainer}>
                      <ProgressChart
                        absolute
                        data={labelVal}
                        width={WP('21.5%')}
                        height={HP('10%')}
                        strokeWidth={5}
                        radius={30}
                        chartConfig={chartConfig}
                        hideLegend={true}
                        style={{
                          marginVertical: 1,
                          borderRadius: 16,
                          backgroundColor:"transparent"
                        }}
                      />
                      <View style={styles.percentageContainer}>
                        <Text style={{color: `${gset_obj}`, fontSize: 18, fontWeight: '500'}}>{item?.PER}</Text>
                      </View>
                    </View>
                </View>
              )
            )}

          </View>
        </View>
        </TouchableOpacity>
      )
    }

   
    return (
      <View style={customStyle.DashBTbl_ReportWrap} >
      {/* render No data */}
      {report_data.length<=0 && <View style={customStyle.DashBTbl_NoDataCon}><Text style={customStyle.DashBTbl_NoDataText}>No Data</Text></View>}
      {report_data.length>0 && 
        <View>
          {/* render content */}
          <View style={[customStyle.DashBCard_Wrap,]}>
             <FlatList
              data={report_data}
              renderItem={({ item, index }) => renderItemcardNew(item, index, tabName , ShowGraph,index === report_data.length - 1,report_data.length % 2 !== 0 )}
              ItemSeparatorComponent={
              <View style={{marginVertical:0, marginHorizontal:0}}/>}
              keyExtractor={(item, index) => index.toString()}
              numColumns={2} 
              columnWrapperStyle={{ 
                justifyContent: 'space-between' 
              }} 
              contentContainerStyle={{ marginHorizontal: 0 }}
            />
          </View>
        </View>
      }
      </View>
    )
  }

    const renderItem = ( item, index , filteredData) => {

      return (
        <View style={[customStyle.DashB_DetailReport]} key={index}>
          <View style={customStyle.DashB_ReportConHdr}> 
            <Text style={[customStyle.DashB_ReportConHdrTxt, {marginBottom:10, marginLeft:10}]}>{item.DashboardName}</Text>
            
            {/* Render attendance data separately */}
            {/* isAttendance == true && _renderAttendanceReport(item) */}

            {/* Render custom view for Attendance reports */}
            {item.DashboardType === 'Card' && _renderCardReport(item,index,filteredData)}
            
            {item.DashboardType === 'Tabular' && _renderTabularReport(item,index,filteredData)}

            {/* Uncomment if needed */}
            {/* {item.DrillDown && 
            <TouchableOpacity style={customStyle.DashB_ReportConHdrIcon} onPress={() => { }}>
              <MaterialCommunityIcons name="arrow-right-thick" size={20} color={PageTheme.$accent_color} />
            </TouchableOpacity>} */}
          </View>
        </View>
      );
    };

    const excludeKeys = ['AdKPIId', 'Color', 'KPIDrilldown', 'DisplayOrder'];

    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        <CustomHeader {...props} title={'Dashboard Detail'}/>
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper,{paddingTop:0}]}>
          {!isDataFound && <NoDataComponent {...props} />}
          <View style={[customStyle.storelist_parentwrap,{paddingHorizontal:0}]}>

          <View style={[]}>
            {/* Custom Tab Bar */}
            <View style={styles.tabBar}>
                {tabs.map((tab, index) => (
                <TouchableOpacity
                    key={index}
                    style={[styles.tabButton, activeTab === index ? styles.activeTab  : styles.inActiveTab]}
                    onPress={() => setActiveTab(index)}
                >
                    <Text style={[styles.tabText, activeTab === index ? styles.activeTabText : styles.inActiveTabText]}>
                     {tab.title}
                    </Text>
                </TouchableOpacity>
                ))}
            </View>

            {/* Screen Content */}
             <View style ={[]}>
                <FlatList
                data={filteredData} 
                renderItem={({ item, index }) => renderItem(item, index, filteredData)}
                keyExtractor={(item, index) => index.toString()} 
                contentContainerStyle={{ paddingBottom: 0 }} 
              />
            </View>
          
          </View>
  
           <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}]}>{modaldata?.item.DashboardName+' 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>

       
          </View>
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

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

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F5F5F5',
      },
      tabBar: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        backgroundColor: '#b1e4de',
        paddingVertical:10
      },
      tabButton: {
        paddingHorizontal: 30,
        paddingVertical:10,
    
      },
      tabText: {
        fontSize: 16,
        color: '#000',
      },
      // activeTab: {
      //   borderBottomWidth: 4,
      //   borderBottomColor: '#00968e',
      // },
      // activeTabText: {
      //   color: '#00968e',
      // },

      activeTab: {
        borderWidth: 2,
        borderColor: '#00968e',
        borderRadius : 5, 
        backgroundColor: '#00968e', 
        
      },
      activeTabText: {
        color: '#FFF',
      },
       inActiveTab: {
        borderWidth: 2,
        borderColor: '#00968e',
        borderRadius : 5, 
        backgroundColor: 'transparent'
      },
      inActiveTabText: {
        color: '#000',
      },
      //KPI's 

      listContainer: {
        paddingHorizontal: 20,
        paddingVertical: 10,
      },
      itemContainer: {
        borderBottomWidth: 1,
        borderBottomColor: '#ccc',
        paddingVertical: 15,
      },
      row: {
        flexDirection: 'row',
        justifyContent: 'space-between',
      },
      kpiTitle: {
        fontWeight: 'bold',
        fontSize: 16,
        flex: 1,
      },
      value: {
        fontSize: 16,
        flex: 0.5,
        textAlign: 'right',
      },
      //header
      headerContainer: {
        borderBottomWidth: 2,
        borderBottomColor: '#000',
        paddingVertical: 10,
      },
      headerText: {
        fontWeight: 'bold',
        fontSize: 16,
        flex: 1,
        textAlign: 'center',
      },
       chartContainer: {
        position: 'relative',
        alignItems: 'center',
        marginTop:10
      },
      percentageContainer: {
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: [{ translateX: -18 }, { translateY: -12 }],
      },
})