import React,{useState,useEffect, memo, 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,TouchableHighlight,Platform,PermissionsAndroid,FlatList, DeviceEventEmitter} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {db,} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import NoDataComponent from '../components/NoDataComponent';
import { _checkLocationPermission } from '../components/geolocation';
import {  Q_getContractFormStoresList, } from '../constants/ConstantQueries';
import DownloadDataModal from '../components/downloadDataModal';

const StoreItem=memo((props)=>{
  const route = useRoute();
  const PageTheme=GetPageTheme(props.DarkMode,route.name);
  const customStyle=customStyles(props.DarkMode,route.name);
  const item=props.item;

  const ST=props.StaticText || {};

  async function go_to_programs(data){
    props.navigation.navigate("ContractPrograms",{storeData:data});
  }

  return(
    <TouchableOpacity
      style={customStyle.storel}
      key={props.index}          
      onPress={() => {go_to_programs(item)}}> 
      <View style={customStyle.storel_card_outer}> 
        <View style={customStyle.storel_card}>
          <View style={customStyle.storel_card_content}>
            <Text style={customStyle.storel_card_title}>{item.StoreName}</Text>
          </View>                  
        </View>
        <View style={customStyle.storel_details}>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder,customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.StoreId+':'}</Text>
              <Text style={customStyle.storel_codeText}>{item.StoreId}</Text>
            </View>                    
            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.StoreType+':'}</Text>
              <Text style={[customStyle.storel_codeText,{width:'50%'}]}>{item.StoreType}</Text>
            </View>
          </View>
          <View style={customStyle.storel_code}>                    
            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{'Store Category:'}</Text>
              <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.StoreCategory}</Text>
            </View>
          </View>
          <View style={customStyle.storel_code}>                    
            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.StoreCode+':'}</Text>
              <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.StoreCode}</Text>
            </View>
          </View>
          {item.DistributorName!=null && item.DistributorId!=null && item.DistributorName!='' && item.DistributorId!='' &&
            <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>                    
            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{'Distributor:'}</Text>
              <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.DistributorName}</Text>
            </View>
          </View>
          }
          <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>                    
            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.Address+':'}</Text>
              <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.Address}</Text>
            </View>
          </View>
          {((item.LastVisitDate!=null && item.LastVisitDate!='' && item.LastVisitDate!='undefined') || (item.Score!=null && item.Score!='' && item.Score!='undefined')) &&
            <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>
              {(item.LastVisitDate!=null && item.LastVisitDate!='' && item.LastVisitDate!='undefined') && 
              <View style={[customStyle.storel_codeCon,((item.Score!=null && item.Score!='' && item.Score!='undefined') ?customStyle.storel_codeBorder:{}),customStyle.storel_codeConAddr]}>
                <Text style={customStyle.storel_codeLbl}>{'Last Visit Date:'}</Text>
                <Text style={customStyle.storel_codeText}>{item.LastVisitDate}</Text>
              </View>  }                  
              {(item.Score!=null && item.Score!='' && item.Score!='undefined') &&
              <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                <Text style={customStyle.storel_codeLbl}>{'Last Visit Score:'}</Text>
                <Text style={[customStyle.storel_codeText,{width:'50%'}]}>{item.Score}</Text>
              </View>}
            </View>
          }
          {(item.MTDMerchandised!=null && item.MTDMerchandised!='' && item.MTDMerchandised!='undefined') &&
            <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>
              <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                <Text style={customStyle.storel_codeLbl}>{'MTD Merchandised Count:'}</Text>
                <Text style={customStyle.storel_codeText}>{item.MTDMerchandised}</Text>
              </View>  
            </View>  
          }
        </View>
      </View> 
    </TouchableOpacity>
  );
});

function ContractFormStores(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 [loaderTitle, setLoaderTitle] = useState();
    const [processing, setProcessing] = useState((props.isDataDownloaded?true:false));
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [isNonMerchan, setIsNonMerchan] = useState(false);

    const [isNonProg, setIsNonProg] = useState(false);

    const [nodataFound, setNodataFound] = useState(false);
    const [showStoreVisitModal, setShowStoreVisitModal] = useState(false);
    const [showGeoTagModal, setShowGeoTagModal] = useState(false);
    const [showDistanceModal, setShowDistanceModal] = useState(false);
    const [currentStore, setCurrentStore] = useState({});
    const [storeDistance, setStoreDistance] = useState('0 M');
    const [storeDistanceinM, setStoreDistanceinM] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [checkOutStore,setCheckOutStore]=useState({});
    const [rerenderdata, setrerenderdata]= useState(false);
    let [state, setState] = useState({storeList:[]});
    const [globalStorelist, setGlobalStorelist] = useState([]);
    const [cancelCheckOutStore,setCancelCheckOutStore]=useState({});
    const [showCancelCIModal, setShowCancelCIModal]= useState(false);
    const [searchedItem, setSearchedItem]= useState('');
  

    const [CheckOutImage, setCheckOutImage] = useState('');
    const [CheckOutImagePath, setCheckOutImagePath] = useState('');
    const [CheckOutImageModal, setCheckOutImageModal] = useState(false);
    const [CheckOutLoc, setCheckOutLoc] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [showCamera, setShowCamera] = useState(false);
    const [GeoFenceEnable_Checkout, setGeoFenceEnable_Checkout] = useState(false);
    const [GeoFenceRadius_Checkout, setGeoFenceRadius_Checkout] = useState('');

    const [uploadedCount, setUploadedCount] = useState(0);
    const [TotalUpCount, setTotalUpCount] = useState(0);
    const [startUploading, setStartUploading] = useState(false);
    const [UploadingSubText, setUploadingSubText] = useState("");
    const [UploadingText, setUploadingText] = useState("Uploading Data...");
    const [showProgresssBar, setshowProgresssBar] = useState(false);
  

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');


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

      console.log('props.isDataDownloaded in storelist:',props.isDataDownloaded);
      getData();
      
      const unsubscribeFocus=props.navigation.addListener('focus', () => {
        getData();
      });
   
      return function cleanup() {
        return unsubscribeFocus;
      };
    }, []);

  

  
    async function getData(){
      let q=await Q_getContractFormStoresList(props);
      console.log('contractFormsStoresq:',q);
      
      await db.transaction(async function (txn) {   
        await txn.executeSql(q,[],async function (txn2, txnres2) {    
          console.log("contract stores :",txnres2.rows.length);
          if(txnres2.rows.length>0){ 
            // show from local
            var storeArr=[];
            for(var i=0;i<txnres2.rows.length;i++){
              let sdata=txnres2.rows.item(i); 
              storeArr.push(sdata);
              if(i==(txnres2.rows.length-1)){
                // console.log(storeArr);
                setState({storeList:storeArr});
                setGlobalStorelist(storeArr);
                setProcessing(false);
              }
            }            
          }
          else{            
            setProcessing(false); notify(ST.Nodatafound);setNodataFound(true);
          }
        },function(Etxn,txnerr){console.log(txnerr); setProcessing(false); notify(ST.Nodatafound);setNodataFound(true);});
      });      
    }


    function FilterStores(searchedQry){
      searchedQry=searchedQry.toLowerCase();
      console.log('searchedQry',searchedQry);
      let {storeList}=state;
      let arr=[]
      if(searchedQry!=null && searchedQry!=''){
        globalStorelist.map((item,index)=>{
          let {StoreName,StoreId,StoreCode}=item;
          StoreId=StoreId+'';
          if(StoreName.toLowerCase().includes(searchedQry) || StoreCode.toLowerCase().includes(searchedQry) || StoreId.includes(searchedQry)){
            arr.push(item);
          }
        });
      }
      else{
        arr=globalStorelist;
      }
      setState({storeList:arr});
      setrerenderdata(!rerenderdata)
    }


 
    
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        {(startUploading) && <DownloadDataModal title={UploadingText} downloadCount={uploadedCount} totalCount={TotalUpCount} subtitle={UploadingSubText} showProgresssBar={showProgresssBar}/>}
        <CustomHeader {...props} showaddstore={true} title={"Contract Form Stores"} />
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={customStyle.pageContentWrapper}>
          { !props.isDataDownloaded && <NoDataComponent {...props}/>}
          
         
          <View style={[customStyle.storelist_parentwrap]}>
          <View style={customStyle.storel_searchbar}>
              <TextInput 
                style={[customStyle.storel_searchInput]}
                placeholder={ST.Searchby+` ${ST.StoreName}, ${ST.StoreId}, ${ST.StoreCode}`}
                autoComplete='off' 
                placeholderTextColor={PageTheme.$placeholder_color} 
                value={searchedItem}
                onChangeText={(val)=>{setSearchedItem(val); FilterStores(val)}}
              />
              <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem)}}>
                <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
              </TouchableOpacity>
          </View>

          { nodataFound && 
          <View style={customStyle.noDataCon}>
            <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
          </View>
          }
          { (props.isDataDownloaded==true && !nodataFound) &&
          <View style={customStyle.Contract_storel_Con}>
          <FlatList
          data={state.storeList}
          extraData={rerenderdata}
          style={customStyle.listcon}
          initialNumToRender={4}
          contentContainerStyle={customStyle.iteml_con}
          renderItem={({ item, index, separators }) =>{
            return(
              <StoreItem  {...props} item={item} index={index} storeList={state.storeList} setLoaderTitle={setLoaderTitle} setProcessing={setProcessing}/>
            );
            }}
          /> 
          </View>
          }
          </View>
         
          
         </View>      
       </LinearGradient>       
       
      </Container>   
    ); 
  }
  


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