import React, {useState, useEffect, useRef} 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 CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons } from '../components/icons';
import NoDataComponent from '../components/NoDataComponent';
import WebView from 'react-native-webview';
import { AntDesign, Entypo } from "../components/icons";
import { ConfirmSaveAlert } from '../components/alert';
import { AppTables } from '../constants/tableConstants';
import { getMethodName, METHODS } from '../constants/methodNames';
import { getBeatDownloadTask, getPostData, insert_TaskDownloadedData } from '../components/downloadTasks';
import DownloadDataModal from '../components/downloadDataModal';


function BeatPlan(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(false);
  const [loaderTitle, setLoaderTitle] = useState();
  const [BeatList, setBeatList] = useState([]);
  const [showAlert, setShowAlert] = useState(false);
  const [selectedBeat, setSelectedBeat] = useState({});
  const [isDisabled, setIsDisabled] = useState(false);
  const [IsDownloadStart, setIsDownloadStart] = useState(false);
  const [downloadingText, setDownloadingText] = useState('');
  const [dowloadedCount, setDowloadedCount] = useState(-1);
  const [totalCount, setTotalCount] = useState(0);
  const [AllTableQueries, setAllTableQueries] = useState([]);
  const [DownloadTasks, setDownloadTasks] = useState([]);
  const [TaskResponse, setTaskResponse] = useState([]); 
  // const [IsPJPMandatory, setIsPJPMandatory] = useState(true);
  


  const d2=moment().format("MM/DD/YYYY");

  useEffect(() => {
    setLoaderTitle(ST.Loading+'...')
    getData();

    props.navigation.addListener('focus', () => {getData();});

    return function cleanup() {
      props.navigation.removeListener('focus', () => {getData();});
    };

  }, []);

  useEffect(() => {
    console.log('dowloadedCount change:',dowloadedCount);
    if(dowloadedCount<=totalCount && IsDownloadStart==true){
      executeTasks();
    }
    else{
      setIsDownloadStart(false);
      notify(ST.DataDownloaded,'SHORT');
    }
  }, [dowloadedCount]);

  useEffect(() => {
    if(IsDownloadStart && TaskResponse!=null){
      console.log('increment dowloadedCount changed');
      let count=dowloadedCount+1;
      setDowloadedCount(count);
    }
  }, [TaskResponse]);

  // async function checkData(){
  //   let projectInfo=await get_item('projectInfo');
  //   let projectDetails=JSON.parse(projectInfo);
  //   let isPJPMand=projectDetails.PJPMandatory!=null?projectDetails.PJPMandatory:true;
  //   setIsPJPMandatory(isPJPMand);
  // }

  async function getData(){        
      try {   
        let List=[];
        await db.transaction(async function (txn) {    
          let q=`Select m.*,b.ROUTE_ID as InsertedRouteId from Master_Route m left outer join ${AppTables.BEAT_PLAN} b on m.RouteId=b.ROUTE_ID and VISIT_DATE='${d2}' `;
          await txn.executeSql(q,[],async function (txn2, txnres2) { 
              if(txnres2.rows.length>0){
                let isfound=false;
                for(let i=0;i<txnres2.rows.length;i++){
                    let data =txnres2.rows.item(i);
                    if(data.TodayRoute=='Y'){
                      isfound=true;
                      setSelectedBeat(data);
                    }
                    List.push(data);
                    if(i==txnres2.rows.length-1){
                      if(isfound){
                        setIsDisabled(true);
                      }
                      setBeatList(List);
                    }
                }
                
              }
          },function (txnE,txnerr) { console.log(txnerr); },);
        });          
      } catch (err) {
        console.log(err);          
      }        
  }

  async function selectBeatplan(){
    
    let {RouteId,RouteName}=selectedBeat;
    let loginInfo=await get_item('loginInfo');
    const loginDetails=JSON.parse(loginInfo);
    
    setShowAlert(false);
    setLoaderTitle('Processing...');
    setProcessing(true);
    try{
      let postdata={
        Downloadtype:"InsertUserDailyRoute",
        Username: loginDetails.UserId,
        Param1: RouteId,
        Param2: d2,
      };
      let url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url,postdata); 
      await getDownloadJson1(url, postdata)
      .then(async(res) => {     
        console.log('res from upload selected Beat',res);
        if(res!=null && res.InsertUserDailyRoute!=null && res.InsertUserDailyRoute[0].success!=false){
          let isUpdated=await updateSelectedBeat();
          if(isUpdated==true){
            setProcessing(false);
            beforeExecuteTasks();
          }
        }
        else{
          setProcessing(false);
          notify('Cannot Update Beat!');
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
      });

      

    }
    catch(err){
      console.log('err:',err);
    }
    
  }

  async function gotoStore(){
    props.navigation.navigate('StoreList',{'isAdhoc': false,'isBeat':true});
  }

  async function updateSelectedBeat(){
    
    let {RouteId,RouteName}=selectedBeat;
    return await new Promise((resolve,reject)=>{
      db.transaction(async function (txn) {    
        let q=`Select * from ${AppTables.BEAT_PLAN} where ROUTE_ID='${RouteId}' and VISIT_DATE='${d2}' `;
        await txn.executeSql(q,[],async function (txn2, txnres2) { 
            if(txnres2.rows.length>0){
              let isUpdated=await updateBeatStatus();
              resolve(true);
            }else{
              // insert selected Beat 
              let values=`('${RouteId}','${RouteName}','1','${d2}','${d2}')`;
              let in_q=`INSERT INTO ${AppTables.BEAT_PLAN} (ROUTE_ID,ROUTE_NAME,STATUS,VISIT_DATE,ADDED_DATE) values ${values} `
              await txn.executeSql(in_q,[],async function (txn3, txnres3) { 
                console.log('inserted selected route');
                let isUpdated=await updateBeatStatus();
                resolve(true);
              },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
            }
        },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
      });  
    }).then((val)=>{
      return val;
    }).catch((err)=>{
      return false;
    })
  }

  async function updateBeatStatus(){
    
    let {RouteId,RouteName}=selectedBeat;
    return await new Promise((resolve,reject)=>{
      db.transaction(async function (txn) {    
        let q=`update Master_Route set TodayRoute='Y' where RouteId='${RouteId}' `;
        await txn.executeSql(q,[],async function (txn2, txnres2) { 
            resolve(true);
        },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
      });  
    }).then((val)=>{
      return val;
    }).catch((err)=>{
      return false;
    })
  }

  
  // download functionality start
  async function startDownload() {
    console.log('startDownload');
    setIsDownloadStart(true);
    setDowloadedCount(0);
  }


  async function beforeExecuteTasks(){
    console.log('beforeExecuteTasks:');
    let DownloadTasks1=await getBeatDownloadTask();
    console.log('All BeatDownloadTask',DownloadTasks1.length);
    setDownloadTasks(DownloadTasks1);
    setTotalCount((DownloadTasks1.length-1));
    startDownload();
  }

  async function executeTasks(){
    console.log('executeTasks');
    let {RouteId,RouteName}=selectedBeat;
    // var DownloadTasks=getDownloadDataTask();
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    var currentIndex=dowloadedCount;

    console.log('currentIndex:',currentIndex); 
    if(currentIndex>=0){
      let dk_data=DownloadTasks[currentIndex]; 
      console.log('dk_data',dk_data);
      let key=dk_data.DownloadKey || '';
      setDownloadingText(key);

      var data =key=='JourneyPlan_RouteWise'?
      {
        Downloadtype:key,
        Username: loginDetails.UserId,
        Param1: RouteId,
        Param2: Platform.OS=="ios"?"iOS":"Android",
      }: await getPostData(DownloadTasks,currentIndex);

      var url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url,data); 
      await getDownloadJson1(url, data)
      .then(async(res) => {     
        let isAdded=await updateTaskRes(res,currentIndex,1);
        if(isAdded==true){
          if(currentIndex==DownloadTasks.length-1){
            console.log('last found all downloaded');
            onDownloadComplete();
          }
          else{
            console.log('all downloaded but last not found ');
          }
          
        }
        else{
          console.log('Cannot download all Data');
        }
        
      })
      .catch(err => {
        console.log('onPage Team error', err);
      });
    }
    
  }

  async function onDownloadComplete(){    
    let count=dowloadedCount+1;      
    setIsDownloadStart(false);
    setDowloadedCount(count);    
    notify(ST.DataDownloaded,'SHORT');
    props.navigation.navigate('StoreList',{'isAdhoc': false,'isBeat':true,'BeatData':selectedBeat});
  }

  async function onTaskError(){      
    notify(ST.Cannotdownloaddata); 
    setIsDownloadStart(false);
  }
  
  async function onNoData(data=[],shouldStop=false,tbname=''){
  
    if(tbname!=''){
      db.transaction(function(txn) {
        // delete all today data
        txn.executeSql(`delete from ${tbname} where 1=1`,[],function(txn1,txnres){
          console.log('deleted all data for '+tbname);
        },function(Etxn,err){
          console.log('err:',err);
        });                                        
      });  
    }
    
    if(shouldStop==true){
      let msg=ST.Nodatafoundfor+tbname+'';
      if(tbname=='JourneyPlan_RouteWise'){
        msg=ST.Youhavenojourneyplanfortoday;
      }
      notify(msg); 
      setIsDownloadStart(false);
    }
    else{
      setTaskResponse(data); 
    } 
  }
  
  async function updateTaskRes(res,index,count){
    // var DownloadTasks=getDownloadDataTask();   
   
    const todate=new Date();
    const today=moment(todate).format("MM/DD/YYYY");
    let d2 =today;
    let dk_data=DownloadTasks[index];
    let key=dk_data.DownloadKey || '';
    let IsMandatory=dk_data.IsMandatory=='true' || dk_data.IsMandatory==1?true:false;

    return new Promise(async (resolve,reject)=>{
      switch(key){
        
        case 'JourneyPlan_RouteWise': {
          if (res.JourneyPlan_RouteWise) {
            let data_arr = res.JourneyPlan_RouteWise || [];          
           
            var values=[];
            data_arr.map((data_obj)=>{  
              let {MID,ChannelId,StoreId,StoreCode,EmpId,VisitDate,ChainId,ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, ExpiryStock,InTime,OutTime,CameraAllow,AddVisiAllow,LastVisitDate,Score,MinTimeTaken,StoreCategoryId,StoreCategory,StoreClassId,StoreClass,TaxType,GSTno,GSTImage}=data_obj;
              values.push(` ('${MID}', '${ChannelId}','${StoreId}','${StoreCode}','${EmpId}', '${VisitDate}','${ChainId}','${ChainName}','${StoreName}', '${Address}','${Location}','${Landmark}','${CityId}', '${CityName}','${StateId}','${StateName}','${RegionId}', '${StoreTypeId}', '${StoreType}', '${Pincode}', '${Latitude}', '${Longitude}', '${Phone}', '${Mobile}', '${ContactPerson}', '${Email}', '${UploadStatus}', '${GeoTag}', '${GeoFenceRadius}', '${ExpiryStock}','${InTime}','${OutTime}','${CameraAllow}','${AddVisiAllow}','${LastVisitDate}','${Score}','${MinTimeTaken}','${StoreCategoryId}','${StoreCategory}','${StoreClassId}','${StoreClass}','${TaxType}','${GSTno}','${GSTImage}')`);
            });
  
            var all_vals=values.join(',');
            
            var sql_stmnt=`INSERT INTO JourneyPlan_RouteWise(MID, ChannelId, StoreId, StoreCode, EmpId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, ExpiryStock,InTime,OutTime,CameraAllow, AddVisiAllow,LastVisitDate,Score,MinTimeTaken,StoreCategoryId,StoreCategory,StoreClassId,StoreClass,TaxType,GSTno,GSTImage) 
            values ${all_vals}`;
            
            db.transaction(function(txn) {
              // delete all today data
              txn.executeSql(`delete from JourneyPlan_RouteWise where 1=1`,[],function(txn1,txnres){
                  // insert or refresh all today data
                  txn.executeSql(sql_stmnt,[],function(txn1,txnres){
                      console.log('JourneyPlan_RouteWise added');
                      setTaskResponse(data_arr);
                      resolve(true);
                  },function(Etxn,err){
                      console.log('err:',err);
                      resolve(true);
                  });                         
              },function(Etxn,err){
                console.log('err:',err);
                resolve(true);
              });                                        
            });  
            
          }
          else if(res!=null && typeof(res)=='object' && res[0]!=null && (res.success==false || (res[0]!=null && res[0].Result!=null))){
            console.log('No data found');
            await onNoData(['No data for JourneyPlan_RouteWise'],true,'JourneyPlan_RouteWise');
            resolve(true);
          }
          else{  
            true?await onTaskError(): await onNoData(['No data for JourneyPlan_RouteWise']); 
            resolve(true); 
          }
          break;
        }
        case 'Mapping_ProductAssortmentStorewise':{
          let colList=['StoreId', 'ProductId', 'MSL','MBQ'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_ProductAssortmentStorewise',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        case 'Mapping_StoreWindow':{
          let colList=['StoreId', 'WindowDefinitionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_StoreWindow',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        case 'Mapping_WindowQuestion':{
          let colList=['WindowDefinitionId', 'WindowQuestionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_WindowQuestion',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        
        case 'Mapping_StorePOSM':{
          let colList=['StoreId', 'POSMDefinitionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_StorePOSM',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }

        case 'Mapping_POSMQuestion':{
          let colList=['POSMDefinitionId', 'POSMQuestionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_POSMQuestion',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }

        case 'Mapping_StoreShelfTalker':{
          let colList=['StoreId', 'StDefinitionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_StoreShelfTalker',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }

        case 'Mapping_ShelfTalkerQuestion':{
          let colList=['StDefinitionId', 'StQuestionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_ShelfTalkerQuestion',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }

        case 'Mapping_StoreVisibility':{
          let colList=['StoreId', 'VisibilityDefinitionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_StoreVisibility',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }

        case 'Mapping_VisibilityQuestion':{
          let colList=['VisibilityDefinitionId', 'VisibilityQuestionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_VisibilityQuestion',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        case 'Mapping_StorePromotion':{
          let colList=['StoreId', 'PromoDefinitionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_StorePromotion',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        case 'Mapping_PromotionQuestion':{
          let colList=['PromoDefinitionId', 'PromoQuestionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_PromotionQuestion',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        case 'Mapping_StoreShareOfShelf':{
          let colList=['StoreId', 'SOSDefinitionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_StoreShareOfShelf',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        case 'Mapping_DisplayChecklist':{
          let colList=['DisplayId', 'ChecklistId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_DisplayChecklist',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        case 'Mapping_Survey':{
          let colList=['StoreId', 'SurveyId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_Survey',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        case 'Mapping_StoreCategory':{
          let colList=['StoreId', 'CategoryDefinitionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_StoreCategory',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
        case 'Mapping_CategoryQuestion':{
          let colList=['CategoryDefinitionId', 'CategoryQuestionId'];
          let i_res=await insert_TaskDownloadedData(res,'Mapping_CategoryQuestion',colList,props);
          console.log('i_res:',i_res);
          let data_arr=i_res['data_arr'];
          setTaskResponse(data_arr);
          let r=i_res['r'];
          console.log('r:',r);
          resolve(r);
          break;
        }
       
      
  
      }
    }).catch((err)=>{
      console.log('error in downloading',err);
      return false;
    });
    
  }


  // download functionality end


  function onRoutePress(item){
    setSelectedBeat(item);
    setShowAlert(true);
  }

  function onCancel(){
    setSelectedBeat({});
    setShowAlert(false);
  }
 

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
      {processing && <CustomLoader title={loaderTitle}/>}
      <CustomHeader {...props}showaddstore={true} title={'Beat Plan'} />
      {(IsDownloadStart && dowloadedCount<=totalCount) && <DownloadDataModal title={ST.DownloadingData} downloadCount={dowloadedCount} totalCount={totalCount} subtitle={downloadingText}/>}
      {ConfirmSaveAlert(props,showAlert,onCancel,selectBeatplan,'Select this Beat Plan!')}
      <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.beatPlan_pageWrapper]}>
        { !props.isDataDownloaded && <NoDataComponent {...props}/>}
        <View  style={[customStyle.trainingHdr]}>
            <Text style={customStyle.trainingHdrText}>Beats</Text>
        </View>
        <ScrollView
        style={customStyle.beatPlan_scrollView}
        contentContainerStyle={customStyle.beatPlan_scrollViewInner}
        >
        {BeatList.length>0 && 
        BeatList.map((item,i)=>{
          let isSelected=selectedBeat.RouteId==item.RouteId;
          return (
            <TouchableOpacity style={[customStyle.beatPlan_listItem,(isDisabled && !isSelected?({backgroundColor:PageTheme.$tertiary_color}):{})]} disabled={(isDisabled && !isSelected)} onPress={()=>{
              // (isSelected)?gotoStore():
              onRoutePress(item);
              }} key={i}>
                <View style={customStyle.beatPlan_lI_Wrap}>
                    <Text style={customStyle.beatPlan_lI_Title}>{item.RouteName}</Text>
                </View>
            </TouchableOpacity>
          )
        })
        }
        </ScrollView>
        </View>      
      </LinearGradient>    
    </Container>
  );
}

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