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, StyleSheet, Dimensions,BackHandler} 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';
import { DataTable } from 'react-native-paper'; 

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 [isFromStoreWises, setIsfromStoreWise] = useState('');
    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');
    const { height } = Dimensions.get('window');

    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let ReportMenu=(params.ReportData||params?.ExtraData?.ReportData) || {};
       // console.log("ReportMenuNew---",JSON.stringify(ReportMenu))
        setCurrentReportMenu(ReportMenu);
        getData(ReportMenu,params);

    //    if(isFromStoreWises==true){
    //        BackHandler.addEventListener('hardwareBackPress', () => {
    //   // Return true to prevent default behavior (going back)
    //      props.navigation.replace('StoreList');
    //     return true;
    // });

    //    }
        
    }, []);

  
    
    async function getData(ReportMenu,params){        
      try {
        let config=ReportMenu?.ColumnConfig
        let configValue= (config && JSON.parse(config))||[]
        let configArr=configValue.length>0? configValue : []
        setReportConfig(configArr)

        let allReportData= await DownloadReport(ReportMenu,params);
        console.log('allReportData',allReportData);
        console.log('ReportMenu',ReportMenu);
        if(allReportData.length>0){
            let data=allReportData[0];
            console.log('data',data);
            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=[];
            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 DownloadReport(ReportMenu,params){
        let downloadKey=ReportMenu?.DownloadKey;
        ///new changes
        let storeInfo = params.storeData || {};
        let _fromStoreWise = params._fromStoreWise!=null && params._fromStoreWise!=''?params._fromStoreWise : false
        setIsfromStoreWise(_fromStoreWise)
        console.log("checkdownloadkey---",params + "\n\n\n"+ ReportMenu)
        let NavigateBy=ReportMenu?.NavigateBy;
        let storeData=ReportMenu?.storeData;
        let IsLocalDB=ReportMenu?.IsLocalDB=="true" || ReportMenu?.IsLocalDB==true 
        console.log("checkislocaldb-",IsLocalDB)

        if(IsLocalDB){

          let arr=[];
          return new Promise((resolve, reject) => {
           db.transaction(async function (txn) {  
            let q=`select * from ${downloadKey} `;
            await txn.executeSql(q,[],async function (txn2, txnres) { 
                console.log('added products subcats:',txnres.rows.length)
                if(txnres.rows.length>0){ 
                    for(var i=0;i<txnres.rows.length;i++){
                        let data =txnres.rows.item(i);
                        arr.push(data);
                        if(i==txnres.rows.length-1){
                            setProcessing(false);
                            console.log("ShowCatWise1- arr",arr)
                            resolve(arr);
                        }
                    }
                }
                else{
                    reject();
                    setProcessing(false);
                    notify("No Data Found!");
                }
                
            },function (txnE,txnerr) {  console.log('qerr:',txnerr); reject(txnerr);},);
          
            });
          })

        }else{

        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
        const url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
        console.log("logssTemp",_fromStoreWise , storeInfo + "\n"+_fromStoreWise ? storeInfo : NavigateBy=="storeMenu" ? storeData?.StoreId:'');
        
        let data={
          Downloadtype:downloadKey,
          Username: loginDetails.UserId,
          Param1: _fromStoreWise ? storeInfo?.StoreId : NavigateBy=="storeMenu" ? storeData?.StoreId:'',
          Param2: Platform.OS=="ios"?"iOS":"Android",
        };
  
        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 [];
        }); 
      }
    }

    const columnWidths = cols?.map((col, colIndex) => {
      const headerLength = col.actual_colname?.length || 0;

      let maxCellLength = 0;
      cols?.forEach(row => {
        const key = col?.coloum_name;
        const value = row[key] ? row[key].toString() : "";
        if (value.length > maxCellLength) {
          maxCellLength = value.length;
        }
      });

      // const maxTextLength = Math.max(headerLength, maxCellLength);
      // const width = Math.max(80, maxTextLength * 25); // 9px per character, min 80px

      const maxTextLength = Math.max(headerLength, maxCellLength);
      const estimatedWidth = maxTextLength * 15;

    // Clamp width between 80px and 150px
    const width = Math.min(Math.max(120, estimatedWidth), 200);

      return width;
    });

    function gotoDailyMenuScreen(props) {
       let params=props.route.params? props.route.params:{};
      let _fromStoreWise =
      params._fromStoreWise != null ? params._fromStoreWise : false;
    let isNonMerchan =
      params.isNonMerchans != null ? params.isNonMerchans : false;
    let isStoreSearch =
      params.isStoreSearch != null ? params.isStoreSearch : false;
    let isNonProgs = params.isNonProgs != null ? params.isNonProgs : false;
    let isAdhocScreen = params.isAdhoc != null ? params.isAdhoc : false;
    let isBeatPlan = params.isBeat != null ? params.isBeat : false;
    let storeData = params.storeData || {};
     props.navigation.replace('StoreDailyMenu', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProgs, isStoreSearch: isStoreSearch });
    }

    // Define handleBackPress function here
  const handleBackPress = () => {
    props.navigation.replace('StoreList'); // Navigate to StoreList on back press
  };

    return ( 
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
      {processing && <CustomLoader title={ST.Loading+"..."}/>}
      {/* {console.log("helooooo-->",isFromStoreWises)} */}
      <CustomHeader {...props} showaddstore={true} title={(currentReportMenu?.ContentType || currentReportMenu?.ReportName )||'Report'} onPress={isFromStoreWises ? handleBackPress : undefined}/>
      <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} contentContainerStyle={{minWidth:"100%",height:"100%",paddingBottom:100}}>
                    <View style={[customStyle.reportCon]}>
                      <DataTable> 
                        <DataTable.Header style={{ borderBottomWidth: 0, marginBottom: 10 }}>
                          <View
                            style={{
                              flexDirection: 'row',
                              height: 54,
                              backgroundColor: PageTheme.$primary_color,
                              borderRadius: 10,
                              // justifyContent: 'space-between', 
                            }}
                          >
                            {cols?.map((col, colindex) => (
                              <DataTable.Title
                                key={colindex}
                                style={{
                                  width: columnWidths[colindex],   // ✅ cell jaisa hi width
                                  justifyContent: 'center',
                                  alignItems: 'center',
                                }}
                              >
                                <View
                                  style={{
                                    backgroundColor: '#fff',
                                    paddingHorizontal: 8,          // ✅ normal padding
                                    paddingVertical: 1,
                                    borderRadius: 10,
                                  }}
                                >
                                  <Text
                                    style={[
                                      customStyle.report_TblHeaderTxt,
                                      {
                                        marginRight: 0,
                                        textAlign: 'center',
                                      },
                                    ]}
                                    numberOfLines={2}              // optional: bohot lamba title ho to 2 line me aa jaayega
                                  >
                                    {col.actual_colname}
                                  </Text>
                                </View>
                              </DataTable.Title>
                            ))}
                          </View>
                        </DataTable.Header>


                        <DataTable.Row> 
                          <View style={[customStyle.report_TblBody,{width:"100%"}]}>
                          {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 = false;
                              if (FieldNameObj) {
                                configValueMatch = item[FieldNameObj?.FieldName] == FieldNameObj?.FieldValue;
                              }

                              return (
                                <View
                                  key={index}
                                  style={[
                                    customStyle.reportItem,
                                    { paddingVertical: 0 },
                                    index % 2 !== 0 ? customStyle.reportItemBg : {},
                                    index < reportData.length - 1 ? customStyle.reportItemB : {}
                                  ]}
                                >
                                  {cols?.map((col, colindex) => {
                                    let keyValue = col?.actual_colname != null ? item[col?.actual_colname] : '';
                                    let isString = isNaN(keyValue);
                                    let str = String(keyValue).replace("%", "");

                                    let ColorArr = configValueMatch && FieldNameObj?.Color ? FieldNameObj.Color : null;
                                    let ColorCode = null;

                                    if (!isNaN(str) && ColorArr) {
                                      ColorCode = ColorArr.find((colorItem) => {
                                        return (
                                          eval(str + (colorItem?.MinRange || "")) &&
                                          eval(str + (colorItem?.MaxRange || ""))
                                        );
                                      });
                                    }

                                    return (
                                      <DataTable.Cell key={colindex} style={{width: columnWidths[colindex],justifyContent: 'center', alignItems:'center'}}>
                                        <View style={[ customStyle.reportItemCol,{ width: columnWidths[colindex],paddingVertical: 8 },colindex === 0 ? { marginLeft: 0 } : {},colindex === cols.length - 1 ? { marginRight: 0 } : {},ColorCode?.Color ? { backgroundColor: ColorCode?.Color } : {},{alignItems: 'center',justifyContent: 'center',// paddingLeft: 15,// paddingHorizontal: 15
                                            }]}>
                                          <Text style={[customStyle.reportItemColText,{ textAlign: 'center' , alignItems:'center'}, ColorCode?.Color ? { color: "white" } : {}]}>
                                            {keyValue}
                                          </Text>
                                        </View>
                                      </DataTable.Cell>
                                    );
                                  })}
                                </View>
                              );
                            })}
                          </View>
                        </DataTable.Row> 
                      </DataTable> 
                    </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) => (
                              <View key={colindex} style={[customStyle.report_CardIRow,colindex < 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) => (
                          <View style={[customStyle.report_CardI, index < reportData.length - 1 ? customStyle.reportItemB : {}]} key={index}>
                            {cols.map((col, colindex) => (
                              <View key={colindex} style={[ customStyle.report_CardIRow, colindex < 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>
     {props?.route?.params?._fromStoreWise === true && (
  <TouchableOpacity
    onPress={() => gotoDailyMenuScreen(props)}
    style={{
      position: 'absolute',
      bottom: 20,
      right: 20,
      backgroundColor: '#f0f0f0',
      paddingVertical: 10,
      paddingHorizontal: 20,
      borderRadius: 30,
      elevation: 4,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.3,
      shadowRadius: 3,
    }}
  >
    <Text style={{ fontSize: 16, color: '#000', fontWeight: 'bold' }}>
      Skip
    </Text>
  </TouchableOpacity>
)}

      
    </Container>
    ); 
  }

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