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 { marktext1, marktext2, UploadData, UploadData2, UploadFormData,fetchProjectConfig } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { db, URL_IMAGE } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, EvilIcons } 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_icon.svg'
import { AppTables } from '../constants/tableConstants';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import CustomCamera from '../components/Camera';

function GeoTag(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(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();
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [EmpData, setEmpData] = useState([]);
  const [showCamera, setShowCamera] = useState(false);
  const [IsSearchedStore, setIsSearchedStore] = useState(false);
  const [isDistributor, setIsDistributor] = useState(false);
  const [isNPNDScreen, setisNPNDScreen] = useState(false);

  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(() => {
    setLoaderTitle(ST.Loading + '...')
    _getCurrentLocation();
    let params = props.route.params ? props.route.params : {};
    let isDistributor1 = params.isDistributor != null ? params.isDistributor : false;
    let storeData1 = params.storeData || {};
    let empData1 = params.empData || {};
    let isAdhoc = params.isAdhoc || false;

     fetchProjectConfig(props.ManagerAppConfig)
        .then(storewisePjp => {
          setIsSearchedStore(storewisePjp.StoreSearch);
           console.log('storewisePjpGeoTag:', storewisePjp.StoreSearch);
        })
        .catch(err => {
          console.error('Config error', err);
        });

    
    // let IsSearchedStore1 = params.IsSearchedStore != null && params.IsSearchedStore == 1 ? true : false;
    let isNPND = params.isNPND != null ? params.isNPND : false;
    //console.log('GeoTag params:', IsSearchedStore1);

    setisNPNDScreen(isNPND)
    setIsAdhocScreen(isAdhoc);
   // setIsSearchedStore(IsSearchedStore1);
    setEmpData(empData1);
    setStoreData(storeData1);
    setIsDistributor(isDistributor1);

    const onBackSubscription = props.navigation.addListener('beforeRemove', onBeforeRemove);

    return function cleanup() {
      isCancelled.current = true;
      props.navigation.removeListener('beforeRemove', onBeforeRemove);
      return onBackSubscription;
    };
  }, []);

  useEffect(() => {
    console.log('show camera changes:', showCamera);
    props.navigation.removeListener('beforeRemove', onBeforeRemove);
    const onBackSubscription = props.navigation.addListener('beforeRemove', onBeforeRemove);
    return onBackSubscription;
  }, [showCamera]);

  function onBeforeRemove(e) {
    if (showCamera == true) {
      e.preventDefault();
      setShowCamera(false);
    }
    else {
      return;
    }
  }

  async function _getCurrentLocation() {
    const hasPermission = await _checkLocationPermission();
    if (hasPermission == true) {
      Geolocation.getCurrentPosition(
        async (position) => {
          let loc = { lat: position.coords.latitude, lng: position.coords.longitude };
          setMarkerPos(loc);
          setMarkerCoordinate(new AnimatedRegion({ latitude: loc.lat, longitude: loc.lng }));
          setMarkerTitle('Current Location');
          setMarkerPlaceText(`${loc.lat}, ${loc.lng}`)
          setCurrentLocation(loc);
        },
        (error) => {
          notify(ST.Cannotgetuserposition);
        },
        { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
      );
    }
    else {
      notify(ST.Pleaseallowlocationpermission);
    }
  }

  async function submitGeoTag(IsSearchedStore) {
    console.log('submitGeoTag called', IsSearchedStore);
    if (validate()) {
      setLoaderTitle(ST.UploadingData + '...');
      setProcessing(true);
      await InsertGeoTag(IsSearchedStore);
    }
  }


  async function InsertGeoTag(IsSearchedStore) {
    try {

      db.transaction(async function (txn) {
        let { StoreId, MerchandiserId } = storeData;

        let { lat, lng } = markerPos;
        lat = lat;
        lng = lng;
        console.log('geotag lat:', lat, 'lng:', lng);
        let status = 'N';
        let tb1 = isDistributor ? AppTables.DB_GEOTAG : AppTables.GEOTAG;
        let values = '', q = '', delq = '';

        if (isDistributor) {
          values = ` ('${StoreId}','${lat}','${lng}','${status}','${status}','${StoreImgPath}','${d2}') `;
          q = `INSERT INTO ${tb1}(STORE_ID,LATITUDE,LONGITUDE,GEO_TAG,STATUS,FRONT_IMAGE,ADDED_DATE) VALUES ${values} `;
          delq = `Delete from ${AppTables.DB_GEOTAG} where STORE_ID='${StoreId}' and ADDED_DATE='${d2}'`;
        }
        else {
          values = ` ('${MerchandiserId}','${StoreId}','${lat}','${lng}','${status}','${status}','${StoreImgPath}','${d2}') `;
          q = `INSERT INTO ${tb1}(EMP_ID,STORE_ID,LATITUDE,LONGITUDE,GEO_TAG,STATUS,FRONT_IMAGE,ADDED_DATE) VALUES ${values} `;
          delq = `Delete from ${AppTables.GEOTAG} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' and ADDED_DATE='${d2}'`;
        }

        txn.executeSql(delq, [], async function (txn2, txnres2) {
          console.log('old geotag removed');
          txn.executeSql(q, [], async function (txn2, txnres3) {
            console.log('geotag  added');
            uploadGeoTagData(IsSearchedStore);
          }, function (txn2, txnerr) { console.log(txnerr); });
        }, function (txn2, txnerr) { console.log(txnerr); });

        // await txn.executeSql(`Select * from ${AppTables.GEOTAG} where STORE_ID='${StoreId}' and ADDED_DATE='${d2}'`,[],async function (txn2, txnres2) {
        //   console.log('geotag added'); 
        //   if(txnres2.rows.length>0){
        //     console.log('geotag already added');
        //     uploadGeoTagData();
        //   } 
        //   else{
        //     await txn.executeSql(q,[],async function (txn2, txnres3) {
        //       console.log('geotag  added');
        //       uploadGeoTagData();
        //     },function(txn2,txnerr){console.log(txnerr);});
        //   }
        // },function(txn2,txnerr){console.log(txnerr);});
      });

    }
    catch (e) {
      console.log(e); setProcessing(false);
    }
  }

  async function uploadGeoTagData(IsSearchedStore) {
    let { lat, lng } = markerPos;
    lat = lat;
    lng = lng;
    let geotag_obj = {};
    if (isDistributor) {
      geotag_obj["DISTRIBUTOR_ID"] = storeData.StoreId;
    } else {
      geotag_obj["STORE_ID"] = storeData.StoreId;
    }
    geotag_obj["VISIT_DATE"] = d2,
      geotag_obj["LATITUDE"] = lat,
      geotag_obj["LONGITUDE"] = lng,
      geotag_obj["FRONT_IMAGE"] = StoreImage;


    let allGeoTags = [geotag_obj];
    let data = {
      "MID": "0",
      "JsonData": JSON.stringify(allGeoTags),
      "UserId": (props.UserId || ''),
    };

    if (isDistributor) {
      data["Keys"] = "DB_GeoTag";
    } else {
      data["Keys"] = "GeoTag";
    }

    var data1 = new FormData();
    data1.append('file', {
      uri: StoreImgPath,
      type: 'image/jpg',
      name: StoreImage,
    });

    let foldername = getFolderName(StoreImage);
    data1.append('Foldername', foldername);
    data1.append('Path', d2);

    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    const url1 = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);
    console.log(url, data);

    await UploadData2(url, data)
      .then(async (res) => {
        console.log(res);

        if (res.UploadJsonResult && res.UploadJsonResult.includes('Success')) {
          await UpdateGeoTagStatus(IsSearchedStore);
          // Upload Image 

          await UploadFormData(url1, data1)
            .then(async (res1) => {
              console.log('res1:', res1);

              if (typeof res1 === 'string' && res1.includes('Success')) {
                console.log('image uploaded');

                // image delete
                RNFS.unlink(StoreImgPath).catch(() => { });

                // ✅ VERY IMPORTANT
                setProcessing(false);
                exit(storeData,IsSearchedStore);
              } else {
                setProcessing(false);
                notify('Image upload failed');
              }
            })

        }
        else {
          setProcessing(false);
          notify(ST.Cannotuploadgeotag)
        }
      })
      .catch((err) => {
        console.log(err); setProcessing(false);
      });

  }

  function exit(storeData1 = {},IsSearchedStore) {
    console.log('exit called===>',IsSearchedStore);

    notify(ST.GeoTagDataUploadedSuccessfully, 'LONG');
    setProcessing(false);
    // props.navigation.goBack();
    // props.navigation.pop();
    if (isDistributor) {
      props.navigation.replace('DistributorCheckIn', { storeData: storeData1, 'isAdhoc': isAdhocScreen, 'isDistributor': isDistributor, 'isNPND': isNPNDScreen })
    }
    else {
     // props.navigation.replace('StoreCheckin', { storeData: storeData1, 'isAdhoc': isAdhocScreen, 'isDistributor': isDistributor, 'isNPND': isNPNDScreen })
       props.navigation.navigate('StoreCheckin', { storeData: storeData1, empData: EmpData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': IsSearchedStore, 'isNPND': isNPNDScreen });
    }
  }

  async function UpdateGeoTagStatus(IsSearchedStore) {
    console.log('UpdateGeoTagStatus called', IsSearchedStore);
    try {
      db.transaction(async function (txn) {
        let { StoreId, MerchandiserId, EmpId } = storeData;
        let { lat, lng } = markerPos;
        lat = lat;
        lng = lng;
        let status = 'Y';
        let tb1 = isDistributor ? AppTables.DB_GEOTAG : AppTables.GEOTAG;
        let JcpType = "";
        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
        const configData = (() => {
          try {
            return typeof props.ManagerAppConfig === "string"
              ? JSON.parse(props.ManagerAppConfig)
              : props.ManagerAppConfig;
          } catch (e) {
            return null;
          }
        })();

        const configArray = configData?.ManagerAppConfig ?? [];
        const currentConfig = configArray.find(
          item => item.Designation?.toLowerCase() === loginDetails?.Designation.toLowerCase()
        );

        const storewisePjp = currentConfig?.StorewisePJP;

        console.log("currentConfigGeoTag:", currentConfig);
        console.log("storewisePjpGeoTag:", storewisePjp);
        console.log("IsSearchedStoreGeoTag:", IsSearchedStore);


        if (IsSearchedStore) {
          JcpType = "Sup_JourneyPlan";
        }
        else if (isDistributor) {
          JcpType = "Sup_MasterDistributor";
        }
        else if (storewisePjp == true) {
          JcpType = isAdhocScreen == true ? "Sup_JourneyPlanStorewiseSup_Adhoc" : isNPNDScreen ? "Sup_NPNDStore" : "Sup_JourneyPlanStorewiseSup";
        }
        else {
          JcpType = isAdhocScreen == true ? "Sup_AdhocJourneyPlan" : isNPNDScreen ? "Sup_NPNDStore" : "Sup_JourneyPlan";
        }
        console.log("MerchandiserId----1", tb1);
        let q = `Update ${tb1} set GEO_TAG='${status}',STATUS='${status}'  where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId || EmpId}' and ADDED_DATE='${d2}'`;
        txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('geotag update', q);

          let q2 = `Update ${JcpType} set GeoTag='${status}',Latitude='${lat}',Longitude='${lng}'  where ${isDistributor ? 'DistributorId' : 'StoreId'}='${StoreId}'`;
          txn.executeSql(q2, [], async function (txn2, txnres2) {
            console.log('geotag updated in store');
            // update geotag locally
            let stored_new = storeData;
            console.log('stored_new before update--:', storeData);
            console.log('stored_new before update:', stored_new);
            stored_new['GeoTag'] = 'Y';
            stored_new['Latitude'] = lat;
            stored_new['Longitude'] = lng;
            setStoreData(stored_new);

            exit(stored_new,IsSearchedStore);
          }, function (txn2, txnerr) { console.log(txnerr); notify(ST.Geotaguploadedbutcannotupdategeotagstatus, 'LONG'); setProcessing(false); });

        }, function (txn2, txnerr) { console.log(txnerr); notify(ST.Geotaguploadedbutcannotupdategeotagstatus, 'LONG'); setProcessing(false); });
      });
    }
    catch (e) {
      console.log(e);
      notify(ST.Geotaguploadedbutcannotupdategeotagstatus, 'LONG'); setProcessing(false);
    }
  }

  function validate() {
    if (markerPos == '' || markerPos == null || markerPos.lat == '' || markerPos.lat == null || markerPos.lng == '' || markerPos.lng == null) {
      notify(ST.Pleaseclickstorefrontimage, 'SHORT');
      return false;
    }
    else if (StoreImage == '' || StoreImage == null) {
      notify((isDistributor ? 'Please click distributor front image' : ST.Pleaseclickstorefrontimage), 'SHORT');
      return false;
    }
    return true;
  }

  async function getImage(imgdata) {

    if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
      notify(ST.Cameraunavailable);
    }
    else if (typeof imgdata == 'object' && imgdata.uri != null) {
      const img = imgdata;
      const imgurl = img.uri, imgWidth = img.width, imgHeight = img.height;


      let picture_clicked_time = new Date();
      picture_clicked_time = moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')


      const mark_text1 = picture_clicked_time;
      let mark_text2 = '';
      if (isDistributor) {
        mark_text2 = 'Distributor Name:' + storeData.StoreName + ' | Distributor Id:' + storeData.StoreId + ' | User Id:' + props.UserId + ' | Image Type: DB Geo Tag' + ' | Date:' + picture_clicked_time;
      }
      else {
        mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + props.UserId + ' | Merch Id:' + storeData.MerchandiserId + ' | Image Type: Geo Tag' + ' | Date:' + picture_clicked_time;
      }
      await marktext1(mark_text1, imgurl)
        .then((res) => {
          if (res.success) {
            let uri = res.uri;
            marktext2(mark_text2, uri, imgWidth, imgHeight)
              .then((res) => {
                if (res.success) {
                  let picture_clickedd = new Date();
                  let picture_clicked_date = moment(picture_clickedd).format('YYYYMMDD');
                  let picture_clicked_time = moment(picture_clickedd).format('HHmmss');
                  let filename = '';
                  if (isDistributor) {
                    filename = storeData.StoreId + '_' + props.UserId + '_DBGeoTag-' + picture_clicked_date + '_' + picture_clicked_time + '.jpg';
                  }
                  else {
                    filename = storeData.StoreId + '_' + props.UserId + '_' + storeData.MerchandiserId + '_GeoTag-' + picture_clicked_date + '_' + picture_clicked_time + '.jpg';
                  }
                  setStoreImage(filename);
                  // renamefile
                  let imagePath = `${RNFS.DocumentDirectoryPath}/${filename}`;
                  RNFS.copyFile(res.uri, imagePath)
                    .then(resn => {
                      let uri = 'file://' + imagePath;
                      console.log('image marker', uri);
                      setStoreImgPath(uri);
                    })
                    .catch(err => {
                      console.log(ST.Errorimagefilewritefailed + '!!!');
                      console.log(err.message, err.code);
                    });

                }
                else {
                  if (res.imagenotfound) {
                    notify(ST.Pleasecaptureaimage);
                  }
                  else {
                    notify(res.error);
                  }
                }
              });
          }
          else {
            if (res.imagenotfound) {
              notify(ST.Pleasecaptureaimage);
            }
            else {
              notify(res.error);
            }
          }
        });
    }
  }

  async function openCamera() {
    setShowCamera(true);
    // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
  }


  function moveMarkerToPos(e) {

    let coords = e.nativeEvent.coordinate;
    console.log('moveMarkerToPos', coords)

    // if(MyMap.current!=null){
    //   MyMap.current.animateToRegion({  
    //     latitude: coords.latitude,   
    //     longitude: coords.longitude,  
    //     latitudeDelta: 0.0922,  
    //     longitudeDelta: 0.0421,  
    //   },1000);
    // }
    animateCamera(coords);
    animateMarkerToRegion(coords);
    setMarkerInfo(coords);
    let loc = { lat: coords.latitude, lng: coords.longitude };
    setMarkerPos(loc);
  }

  function animateMarkerToRegion(coords) {
    const newCoordinate = coords;
    const new_animated_coords = new AnimatedRegion({ latitude: coords.latitude, longitude: coords.longitude });
    if (Platform.OS === 'android') {
      if (MyMarker) {
        MyMarker.current.animateMarkerToCoordinate(newCoordinate, 1000);
      }
    } else {
      // `useNativeDriver` defaults to false if not passed explicitly
      markerCoordinate.timing({ ...newCoordinate, useNativeDriver: false, duration: 1000 }).start();
    }
    setTimeout(() => { setMarkerCoordinate(new_animated_coords); }, 1000);

  }

  async function setMarkerInfo(coords) {
    if (MyMap.current != null) {
      MyMap.current.addressForCoordinate(coords)
        .then((res) => {
          console.log('res:', res);
          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 = 90;
      // camera.pitch = 45;
      // camera.altitude = 1000;
      // camera.zoom = 1000;
      camera.center.latitude = coords.latitude;
      camera.center.longitude = coords.longitude;
      MyMap.current.animateCamera(camera, { duration: 2000 });
    }
  }


  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.mapWrapperSmall]}>
            <MapView
              ref={MyMap}
              style={customStyle.mapStyle}
              // provider={PROVIDER_GOOGLE}
              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,
              }}
              moveOnMarkerPress={true}
              // onCalloutPress={(e)=>{console.log('on press')}}
              // onRegionChangeComplete={(region,details)=>{console.log('on region change',region)}}
              onPress={moveMarkerToPos}

            >
              <Marker.Animated
                ref={MyMarker}
                draggable={true}
                onDragEnd={(e) => { console.log('on drag end:', e.nativeEvent.coordinate) }}
                coordinate={markerCoordinate}
                pinColor={'#ff78b6'}
                title={markerTitle}
                description={markerPlaceText}
              />
            </MapView>
          </View>
          {_render_captureImage()}
        </View>
      );
    }
    else {
      return (<View></View>)
    }
  }

  function _render_captureImage() {
    const isImageAvlbl = StoreImage != '' && StoreImage != null && StoreImgPath != '' && StoreImgPath != null;

    return (
      <View style={customStyle.gtag_sImageWrap}>
        <View style={customStyle.gtag_sImagelbl}>
          <View style={customStyle.gtag_sImage_View}>
            {isImageAvlbl && <Image style={customStyle.gTag_Image} source={{ uri: StoreImgPath }} />}
            {!isImageAvlbl && <Image style={customStyle.gTag_Image} source={require('../assets/image/greybg.jpg')} />}
          </View>
          <TouchableOpacity style={customStyle.gTag_sImageBtn} onPress={() => { openCamera() }}>
            {<Entypo size={20} color={'#fff'} name='camera' />}
          </TouchableOpacity>
          <Text style={customStyle.gtag_sImagelblText}>{(isDistributor ? 'Click distributor front image' : ST.ClickStoreFrontImage)}</Text>
        </View>

      </View>
    );
  }

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      <CustomHeader {...props} title={ST.Geotag} />
      <CustomCamera cameraType={'back'} onImageCaptured={(imgData) => { setShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { setShowCamera(false); }} />

      <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}>{ST.StoreId + ':'}</Text>
                        <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                      </View>
                      <View style={[customStyle.storel_codeCon]}>
                        <Text style={customStyle.storel_codeLbl}>{ST.StoreCode + ':'}</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}>{ST.Address + ':'}</Text>
                        <Text style={customStyle.storel_codeText}>{storeData.Address}</Text>
                      </View>
                    </View>
                  </View>
                </View>

              </View>
              {
                // isCancelled.current==false &&
                _renderMap()
              }
              <View style={customStyle.gTag_btnWrap}>
                <GradientButton {...props} title={ST.UploadGeotag} colors={[PageTheme.$red_light100, PageTheme.$red, PageTheme.$red]} style={{ shadowColor: PageTheme.$red }} onPress={() => { submitGeoTag(IsSearchedStore) }} />
              </View>

            </ScrollView>
          }
        </View>
      </LinearGradient>

    </Container>
  );
}



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