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 { METHODS, getMethodName } from '../constants/methodNames';

function DynamicStoreScore(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 [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    const [CalculatedPercent, setCalculatedPercent] = useState(0);
    const [TotalScore, setTotalScore] = useState(0);
    const [currentMenu, setCurrentMenu] = useState({});
    const [cols, setcols] = useState([]);

    const [reportData, setReportData] = useState([]);
    const [designation, setDesignation] = useState('');
    const [colWidth, setColWidth] = useState('100%');

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    
    useEffect(() => {
        console.log('CategoryExec:');
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        setStoreCameraAllow(cameraAllow);
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1,menu1);

    }, []);
    

    // async function getData(storeData1,menu1){        
    //   try {   
    //     console.log('reportData:1');
    //     let loginInfo=await get_item('loginInfo');
    //     const loginDetails=JSON.parse(loginInfo);
    //     let desg=loginDetails.Designation || '';
    //     setDesignation(desg);
    //     await db.transaction(async function (txn) { 
    //       let q=`SELECT * from Report_ComplianceScore where StoreId='${storeData1.StoreId}'`;//54975
    //       await txn.executeSql(q,[],async function (txn2, txnres) { 
    //           if(txnres.rows.length>0){
    //             let arr=[],totalScore=0,maxScorePerRow=10;
    //             for(var i=0;i<txnres.rows.length;i++){
    //               let data=txnres.rows.item(i);
    //               // if(i==0 || i==1){
    //               //   data.Score=5
    //               // }else{
    //               //   data.Score=10;
    //               // }
    //               let itemScore=data.Score!=null && data.Score!='' ?parseInt(data.Score):0;
    //               totalScore+=itemScore;
    //               arr.push(data);
    //               if(i==txnres.rows.length-1){
    //                 let MaxScore=maxScorePerRow*txnres.rows.length;
    //                 let percent=Math.floor((totalScore/MaxScore) * 100);
                    
    //                 console.log('reportData:',arr);
    //                 setReportData(arr);
    //                 setProcessing(false);
    //                 setCalculatedPercent(percent);
    //                 setTotalScore(totalScore);
    //               }
    //             }
    //           }
    //           else{
    //             setProcessing(false);
    //           }
    //       },function (txnE,txnerr) { console.log(txnerr); setProcessing(false);},);
          
    //     });          
    //   } catch (err) {
    //     setProcessing(false);
    //     console.log(err);          
    //   }        
    // }
  

    async function getData(storeData1,menu1){        
        try {
          
          let allReportData= await DownloadReport();
          console.log('allReportData',allReportData);
          if(allReportData.length>0){
              let data=allReportData[0];
              console.log('data dynamicdata-----',data);
              let ShowField=JSON.parse(data.ShowField)
              let ColorField=JSON.parse(data.ColorField)
              let arrCol=[]
              if(ShowField.length>0){

                for(var i=0;i<ShowField.length;i++){
                    let data1=ShowField[i];
                    
                    if(data1.Show=="Y"){
                        let obj={FieldName:data1.FieldName}
                        let colorobj=ColorField.find(i=>i.FieldName==data1.FieldName);
                        if(colorobj!==undefined && colorobj!=""){
                            obj["Color"]=colorobj.Color
                        }
                        console.log("ITesm,--",obj)
                        arrCol.push(obj);
                    }
                   
                    if(i==ShowField.length-1){
                        let colLen=arrCol.length;
                        let width=97/colLen;
                        setColWidth(width+'%');
                        setcols(arrCol);
                        console.log('reportData:',arrCol);
                        // setReportData(arr);

                    }
                }
              }

              let filterData=allReportData.filter((item)=>item.StoreId==storeData1.StoreId);
                setReportData(filterData);
                setProcessing(false);
              }
              
        } catch (err) {
          setProcessing(false);
          console.log(err);          
        }        
      }
  
      async function DownloadReport(){
          let downloadKey="Report_StoreDynamicScore";
          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 [];
          }); 
      }

    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        <CustomHeader {...props}showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        <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.StSC_HdrWrap}>
            <View  style={customStyle.StSC_RonHdr}>
              <Text style={customStyle.StSC_RConHdrText}>{'Previous Audit Score'}</Text>
            </View>
          </View> */}
          { !props.isDataDownloaded && <NoDataComponent {...props}/>}
          { true && 
            <View style={customStyle.StSC_ConWrap}>
                <View style={customStyle.StSC_RTblHeader}>
                {
                    cols.length>0 &&
                    cols.map((item,index)=>(
                        <View style={[customStyle.report_TblHeaderBox,{width:colWidth},(index==0?{marginLeft:0}:{}),(index==(cols.length-1)?{marginRight:0}:{})]}>
                                <Text style={[customStyle.report_TblHeaderTxt]}>{item.FieldName}</Text>
                        </View>
                       
                      ))
                }
                </View>
                <ScrollView
                  contentContainerStyle={customStyle.StSC_scrollViewInner}
                  style={customStyle.DYSC_scrollView}
                >
                  <View style={customStyle.StSCreportCon}>
                    <View style={[customStyle.StSC_RTblBody]}>
                    {
                      reportData.length>0 &&
                      reportData.map((item,index)=>{     
                        return(
                          <View style={[customStyle.DYStSC_RItem,((index<(reportData.length-1))?customStyle.StSC_RtemB:{})]} key={index}>
                          {cols.map((col,colindex)=>{
                            let colorCode=item && col? ( col.Color=="Y"?item.Color :"") :""
                                return (
                                <View style={[customStyle.DYreportItemCol,{width:colWidth},(colindex==0?{marginLeft:0}:{}),(colindex==(cols.length-1)?{marginRight:0}:{alignItems:"left"}),{backgroundColor:colorCode} ]}>
                                    <Text style={[customStyle.reportItemColText,{justifyContent:"center",alignItems:"center"}]}>{item[col.FieldName]}</Text>
                                </View>
                                )
                            })}
                          </View>
                        )
                      })
                    }
                    
                    </View>
                  </View>
                </ScrollView>
                {/* <View style={customStyle.StSC_RTblFooterWrap}>
                <View style={customStyle.StSC_RTblFooter}>
                  <View style={[customStyle.StSC_RTblFooterBox,customStyle.StSC_RTblFooterBox1]}>
                    <Text style={[customStyle.StSC_RTblHeaderLbl]}>{'Calculated :'}</Text>
                    <Text style={[customStyle.StSC_RTblHeaderVal, {color:CalculatedPercent > 75? "#32CD32":"red"}]}>{CalculatedPercent+'%'}</Text>
                  </View>
                  <View style={[customStyle.StSC_RTblFooterBox,customStyle.StSC_RTblFooterBox2]}>
                    <Text style={[customStyle.StSC_RTblHeaderLbl]}>{'Total Score :'}</Text>
                    <Text style={[customStyle.StSC_RTblHeaderVal]}>{TotalScore}</Text>
                  </View>
                </View>
                </View> */}
            </View>
          }
        </View>
        </LinearGradient>

      </Container>   
    ); 
}
  
  

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