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';
import GradientButton from '../components/gradientButton';

function StoreReport(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 [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 [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [isNonMerchan, setIsNonMerchan] = useState(false);
    const [isNonProg, setIsNonProg] = useState(false);
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let ReportMenu=params.ReportData || {};

        let storeData1=params.storeData || {};
        let isAdhoc=params.isAdhoc || false;
        let isBeat=params.isBeat!=null? params.isBeat : false;
        let isNonMerchan1=params.isNonMerchans!=null? params.isNonMerchans : false;
        let isNonProgam=params.isNonProgs!=null? params.isNonProgs : false;
        setIsAdhocScreen(isAdhoc);
        setIsBeatPlan(isBeat);
        setIsNonMerchan(isNonMerchan1);
        setIsNonProg(isNonProgam)
        setStoreData(storeData1);
        console.log("storeData-------",storeData.StoreName)
        setCurrentReportMenu(ReportMenu);
        getData(storeData1);
    }, []);
    

    async function getData(storeData1){        
      try {
        
        let ReportDataStr= await get_item('Report_AferCheckIn');
        let ReportDataJson= (ReportDataStr && ReportDataStr && await JSON.parse(ReportDataStr))||[];
        // let allReportData= await DownloadReport(ReportMenu);
        let allReportData = ReportDataJson.filter((item)=>item.StoreId==storeData1.StoreId);
        console.log('allReportData',allReportData,storeData1.StoreId);
        if(allReportData.length>0){
            let data=allReportData[0];
            console.log('data',data);
            if(data && data){
              let ConfigStr=data?.Config
              let config=ConfigStr && ConfigStr && JSON.parse(ConfigStr)
              setCurrentReportMenu(config)
            }
            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){
        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: 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 gotoDailyMenu = ()=>{
      props.navigation.replace('StoreDailyMenu',{storeData:storeData,'isAdhoc':isAdhocScreen,'isBeat':isBeatPlan,"isNonMerchans":isNonMerchan,isNonProgs:isNonProg});
    }

    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        <CustomHeader {...props}showaddstore={true}  title={'Store 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}>{`Store Name: ${storeData.StoreName}`}</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,{height:"78%"}]}
                >
                  
                  {currentReportMenu.ReportType=='Tabular' &&
                  <ScrollView
                  horizontal={true}
                >
                  <View style={[customStyle.reportCon,{width:"100%"}]}>
                    
                    <View style={customStyle.report_TblHeader}>
                        {cols?.map((col,colindex)=>{
                          if(col.actual_colname=="Config" || col.actual_colname=="StoreId"){
                            return
                          } 
                            return (
                            <View style={[customStyle.report_TblHeaderBox,{minWidth:100},(colindex==0?{marginLeft:0}:{}),(colindex==(cols.length-1)?{marginRight:0}:{})]}>
                                <Text style={[customStyle.report_TblHeaderTxt]}>{col.actual_colname}</Text>
                            </View>
                            )
                        })
                        }
                    </View>
                    <View style={customStyle.report_TblBody}>
                    {
                      reportData?.length>0 &&
                      reportData?.map((item,index)=>{
                        return(
                          <View style={[customStyle.reportItem,(index%2!=0?customStyle.reportItemBg:{}),((index<(reportData.length-1))?customStyle.reportItemB:{})]} key={index}>
                            {cols.map((col,colindex)=>{
                              if(col.actual_colname=="Config" || col.actual_colname=="StoreId"){
                                return
                              } 
                                return (
                                <View style={[customStyle.reportItemCol,{minWidth:100},(colindex==0?{marginLeft:0}:{}),(colindex==(cols.length-1)?{marginRight:0}:{})]}>
                                  <Text style={customStyle.reportItemColText}>{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>
                                    <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 style={[customStyle.SChk_Btn]}>
                  <GradientButton {...props} title={"Next"} onPress={()=>{gotoDailyMenu()}} style={customStyle.SChk_BtnSave } /> 
              </View> 
            </View>
          }
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

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