import React,{useState,useEffect} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme, WP } from "../styles/Global";
import {Image,View,Text,ScrollView,TouchableOpacity,Platform,FlatList} from 'react-native';
import { connect} from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {checkRange,marktext1,marktext2, UploadData, UploadData2, UploadFormData} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {db, gMap_key} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import {SvgXml} from 'react-native-svg';
import MapView,{ Marker,AnimatedRegion,Polyline,PROVIDER_GOOGLE } from 'react-native-maps';
import { _checkLocationPermission } from '../components/geolocation';
// import Geolocation from '@react-native-community/geolocation';
import Geolocation from 'react-native-geolocation-service';
import { useRef } from 'react';
import GradientButton from '../components/gradientButton';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';

import cameraImg from '../assets/performics/camera_front_image.svg'
import { AppTables } from '../constants/tableConstants';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';

function ShowMap(props) { 
    const route = useRoute();
  
    // 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(false);
    
    const [storeData, setStoreData] = useState({});
    const [StoreImage, setStoreImage] = useState('');
    const [StoreImgPath, setStoreImgPath] = useState('');
    
    const [currentLocation, setCurrentLocation] = useState({});
    const [markerCoordinate, setMarkerCoordinate] = useState();
    const [markerPos, setMarkerPos] = useState({});
    const [markerTitle, setMarkerTitle] = useState('');
    const [markerPlaceText, setMarkerPlaceText] = useState('');
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeDistanceText, setStoreDistanceText] = useState('0 m');
    const [storeDistance, setStoreDistance] = useState(0);
    
    const MyMap=useRef(null);
    const MyMarker=useRef(null);
    const isCancelled = useRef(false);
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
   
    useEffect(() => { 
      let params=props.route.params? props.route.params:{};
      let storeData1=params.storeData || {};
      let isAdhoc=params.isAdhoc || false;
      setIsAdhocScreen(isAdhoc);
      setStoreData(storeData1);
      getCurrentPosition(storeData1);
      getLocationUpdates(storeData1);
      return () => {isCancelled.current = true; Geolocation.clearWatch()};
    }, []);

    async function getCurrentPosition(storeData1){
        Geolocation.getCurrentPosition(
          async (position) => {
            OnLocation(position,storeData1);   

            // let coords={latitude:position.coords.latitude,longitude:position.coords.longitude}
            // animateCamera(coords);
          },
          (error) => {
              notify('Cannot get user position');
          },
          { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
        );
    }

    async function getLocationUpdates(storeData1){
        Geolocation.watchPosition(
          async (position) => {
            OnLocation(position,storeData1); 
            
          },
          (error) => {
            notify('Cannot get user position');
          },
          { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000, }
        )
    }
  
    async function OnLocation(position,storeData1){
        let loc={lat:position.coords.latitude,lng:position.coords.longitude};
        let storeLat=parseFloat(storeData1.Latitude),storeLng=parseFloat(storeData1.Longitude);
        setMarkerPos({ lat:storeLat, lng: storeLng });
       
        setMarkerCoordinate(new AnimatedRegion({ latitude:storeLat, longitude: storeLng }));
        setMarkerInfo({ latitude:storeLat, longitude: storeLng });
        setCurrentLocation(loc);
  
  
        var distance = checkRange(loc.lat,loc.lng,storeData1.Latitude,storeData1.Longitude);
        // console.log('distance:',distance);
        let dinKM=(distance / 1000);
        let distanceinM=(distance=='' || distance==null || isNaN(distance))?' 0 m':( dinKM > 1 ? dinKM.toFixed(1) + ' Km' : distance + ' m');
        setStoreDistanceText(distanceinM);
        setStoreDistance(distance);  
        
        
    }

    async function setMarkerInfo(coords){
      if(MyMap.current!=null){
        MyMap.current.addressForCoordinate(coords)
        .then((res)=>{
         
          if(res!=null){
            let title=res.name;
            let placeText=`${res.subLocality}, ${res.locality}, ${res.administrativeArea} ${res.postalCode}`;
            setMarkerTitle(title);
            setMarkerPlaceText(placeText);
          }
        })
      }
    }

    async function animateCamera(coords) {
      if(MyMap.current!=null){
      const camera = await MyMap.current.getCamera();
      camera.heading = 7;
      camera.pitch = 7;
      camera.altitude = 100;
      camera.zoom = 19;
      camera.center.latitude = coords.latitude;
      camera.center.longitude = coords.longitude;
      MyMap.current.animateCamera(camera, { duration: 2000 });
      console.log('animate camera');
      }
    }


    function _renderMap(){
      const lat =currentLocation.lat?currentLocation.lat:28.579660;
      const lng=currentLocation.lng?currentLocation.lng:77.321110;
      
      if(currentLocation.lat!=null)
      {
        return (
          <View style={[customStyle.mapWrapCon,(Platform.OS==='ios'?customStyle.mapWrapConIOS:{})]}>
          <View style={[customStyle.mapWrapper,customStyle.mapWrapperView]}>            
            <MapView  
              ref={MyMap}
              // provider={PROVIDER_GOOGLE}
              style={customStyle.mapStyle}               
              showsUserLocation={true}  
              zoomEnabled={true} 
              // initialRegion={{  
              //   latitude: lat,   
              //   longitude: lng,  
              //   latitudeDelta: 0.0922,  
              //   longitudeDelta: 0.0421,  
              // }}  
              initialCamera={{
                center: {
                  latitude: lat,   
                  longitude: lng,
                },
                pitch: 7,
                heading: 7,
                altitude: 100,
                zoom: 19,
              }}
              
          >
              <Marker.Animated 
                ref={MyMarker}
                coordinate={ markerCoordinate}                  
                pinColor={'#ff78b6'}
                title={markerTitle}  
                description={markerPlaceText}      
              />  
              
              <Polyline
                coordinates={[{latitude:currentLocation.lat,longitude:currentLocation.lng},{latitude:markerPos.lat,longitude:markerPos.lng}]}
                strokeColor={'#00a4eb'} // fallback for when `strokeColors` is not supported by the map-provider
                strokeColors={['#00a4eb']}
                strokeWidth={4}
              />
            </MapView> 
          </View>  
          </View>            
        );
      }
      else{
        return(<View></View>)
      }
    }

    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={'Store Location'}/>        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper]}>
          { Object.keys(storeData).length>0 &&
            <ScrollView contentContainerStyle={[customStyle.geotag_scroll]} style={{}}>            
            
              <View style={[customStyle.storel,customStyle.storeInfo_wrap]}>

              <View style={customStyle.storel_card_outer}> 
                <View style={customStyle.storel_card}>
                  <View style={customStyle.storel_card_content}>
                    <Text style={customStyle.storel_card_title}>{storeData.StoreName}</Text>
                  </View>                  
                </View>
                <View style={customStyle.storel_details}>
                  <View style={customStyle.storel_code}>
                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
                      <Text style={customStyle.storel_codeLbl}>Store Id:</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                    </View>                    
                    <View style={[customStyle.storel_codeCon]}>
                      <Text style={customStyle.storel_codeLbl}>Store Code:</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreCode}</Text>
                    </View>
                  </View>
                  <View style={customStyle.storel_code}>                    
                    <View style={[customStyle.storel_codeCon]}>
                      <Text style={customStyle.storel_codeLbl}>Address:</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.Address}</Text>
                    </View>
                  </View>                                 
                </View>                
              </View> 

              </View>
              { _renderMap()} 
              <View style={[customStyle.gTag_btnWrap,customStyle.mt10]}>
                {
                  <View  style={[customStyle.gTag_distanceAway,{backgroundColor:'#dcf4ff'}]}>
                  <Text style={[customStyle.gTag_distanceAwayLbl,{color:'#1f7dbc'}]}>{`You are ${storeDistanceText} away from the store!`}</Text>
                  </View>
                }
              </View>  
            </ScrollView>
          }
         </View>      
       </LinearGradient>       
        
      </Container>   
    ); 
  }
  


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