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} 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';

function StoreScore(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 [reportData, setReportData] = useState([]);
    const [designation, setDesignation] = useState('');

    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);          
      }        
    }
  
    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}>
                  <View style={[customStyle.StSC_RTblHeaderBox,customStyle.StSC_RTblHeaderBox1]}>
                    <Text style={[customStyle.StSC_RTblHeaderTxt,{textTransform:'uppercase'}]}>{ST.Kpi}</Text>
                  </View>
                  <View style={[customStyle.StSC_RTblHeaderBox,customStyle.StSC_RTblHeaderBox2]}>
                    <Text style={customStyle.StSC_RTblHeaderTxt}>{'Question Category'}</Text>
                  </View>
                  <View style={[customStyle.StSC_RTblHeaderBox,customStyle.StSC_RTblHeaderBox3]}>
                    <Text style={customStyle.StSC_RTblHeaderTxt}>{'Obtain Score'}</Text>
                  </View>
                </View>
                <ScrollView
                  contentContainerStyle={customStyle.StSC_scrollViewInner}
                  style={customStyle.StSC_scrollView}
                >
                  <View style={customStyle.StSCreportCon}>
                    <View style={[customStyle.StSC_RTblBody]}>
                    {
                      reportData.length>0 &&
                      reportData.map((item,index)=>{
                        let imgPath=item.WindowIcon!=null && item.WindowIcon!=''?item.IconPath+item.WindowIcon:'';
                        let colorCode=item ? ( item.Score==5? "#FFBF00":item.Score==0?"#ff0000":item.Score==10?"#32CD32":"") :""
                        return(
                          <View style={[customStyle.StSC_RItem,((index<(reportData.length-1))?customStyle.StSC_RtemB:{})]} key={index}>
                            <View style={[customStyle.StSC_RItemCol,customStyle.StSC_RItemCol1]}>
                              {imgPath!='' && <Image source={{uri:imgPath}} style={customStyle.StSC_RItemColIcon}/>}
                              <Text style={[customStyle.StSC_RItemColText,{paddingVertical:10}]}>{item.KPI}</Text>
                            </View>
                            <View style={[customStyle.StSC_RItemCol,customStyle.StSC_RItemCol2]}>
                              <Text style={[customStyle.StSC_RItemColText,{paddingVertical:10}]}>{item.Name}</Text>
                            </View>
                            <View style={[customStyle.StSC_RItemCol,customStyle.StSC_RItemCol3,{backgroundColor:colorCode} ]}>
                              <Text style={[customStyle.StSC_RItemColText,{paddingVertical:11}]}>{item.Score}</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)(StoreScore);