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, DeviceEventEmitter, Keyboard } 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, restore_ImageWithMetaData, UpdateStoreStatus, UploadData, UploadData2, UploadFormData } from '../controller/functions';
import { AppVersion, common_ImagePath, ImageFolderPath, db, gMap_key, URL_IMAGE, CoverageImagePath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import MapView, { Marker, AnimatedRegion, Polyline, PROVIDER_GOOGLE } from 'react-native-maps';
import { _checkLocationPermission } from '../components/geolocation';
import Geolocation from 'react-native-geolocation-service';
import { useRef } from 'react';
import GradientButton from '../components/gradientButton';
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';
import { getAvailblQuery, getIfAvlbl, Q_MenuList } from '../constants/ConstantQueries';
import { executeTasks, getPostData, getReDownloadTasks1, startRedownload } from '../components/downloadTasks';
import DownloadDataModal from '../components/downloadDataModal';
import CustomModal from '../components/CustomModal';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import { ConfirmSaveAlert } from '../components/alert';
import { get_item } from '../components/localStorage';


function StoreCheckin(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({ latitude: 0, longitude: 0 });

  const [markerPos, setMarkerPos] = useState({});
  const [markerTitle, setMarkerTitle] = useState('');
  const [markerPlaceText, setMarkerPlaceText] = useState('');
  const [loaderTitle, setLoaderTitle] = useState();
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [isBeatPlan, setIsBeatPlan] = useState(false);
  const [storeDistanceText, setStoreDistanceText] = useState('0 m');
  const [storeDistance, setStoreDistance] = useState(0);
  const [showCamera, setShowCamera] = useState(false);
  const [getImageProps, setGetImageProps] = useState({});
  const [isNonMerchan, setIsNonMerchan] = useState(false);

  const [isNonProg, setIsNonProg] = useState(false);
  const [isStoreSearch, SetIsStoreSearch] = useState(false);
  const [isDataDownloaded, setisDataDownloaded] = useState(false);
  const [startDownload, setStartDownload] = useState(false);
  const [TaskResponse, setTaskResponse] = useState([]);
  const [downloadingText, setDownloadingText] = useState('');
  const [dowloadedCount, setDowloadedCount] = useState(-1);
  const [totalCount, setTotalCount] = useState(-1);
  const [DownloadTasks, setDownloadTasks] = useState([]);

  const [DErrorMsg, setDErrorMsg] = useState({});
  const [showDErrAlert, setshowDErrAlert] = useState(false);

  const [SelectedImg, setSelectedImg] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [showImageSaveOp, setShowImageSaveOp] = useState(true);

  const [showAlert, setShowAlert] = 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 + '...')
    let params = props.route.params ? props.route.params : {};
    let storeData1 = params.storeData || {};
    let isAdhoc = params.isAdhoc || false;
    let isBeat = params.isBeat != null ? params.isBeat : false;
    let isNonMerchan1 = params.isNonMerchans != null ? params.isNonMerchans : false;
    let isNonProgam = params.isNonProgs != null ? params.isNonProgs : false;
    let isStoreSearch = params.isStoreSearch != null ? params.isStoreSearch : false;
    setIsAdhocScreen(isAdhoc);
    setIsBeatPlan(isBeat);
    setIsNonMerchan(isNonMerchan1);
    setIsNonProg(isNonProgam)
    SetIsStoreSearch(isStoreSearch)
    setStoreData(storeData1);
    calLocatDistance(storeData1);
    getLocationUpdates();
    getCurrentPosition();
    getData();

    const onImageCapturedSubs = DeviceEventEmitter.addListener('onImageCaptured', (imgData) => { getImage(imgData) });

    return function cleanup() {
      isCancelled.current = true;
      Geolocation.clearWatch()
      onImageCapturedSubs.remove();

    };

  }, []);

  useEffect(() => {
    const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
    return unsubscribe;
  }, [showCamera]);



  useEffect(() => {
    console.log('on totalCount change:', totalCount, startDownload);
    if (startDownload == true && totalCount > -1) {
      setDowloadedCount(0);
    }
  }, [totalCount]);

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


  useEffect(() => {
    console.log('dowloadedCount onchange:', dowloadedCount);
    if (dowloadedCount <= totalCount) {
      executeTasks(props, storeData, DownloadTasks, dowloadedCount, totalCount, setDowloadedCount, setDownloadingText, onDownloadComplete, setTaskResponse, showErrorModal);
    }
    else {
      setStartDownload(false);
    }
  }, [dowloadedCount]);

  function onBeforeRemove(e) {
    console.log('onBeforeRemove:', showCamera);
    if (showCamera == true) {
      e.preventDefault();
      setShowCamera(false);
    }
    else {
      return;
    }
  }

  async function getData() {
    console.log('getData checkin');
    let Tasks = await getReDownloadTasks1(props);
    console.log('Tasks redownload len:', Tasks.length)
    setDownloadTasks(Tasks);
  }

  function cancelImage() {
    // setImage1('');
    setSelectedImg('');
    setShowModal(false);
  }

  async function calLocatDistance() {

    const hasPermission = await _checkLocationPermission();
    if (hasPermission == true) {
      getLocationUpdates();
      getCurrentPosition();

    }
    else {
      notify(ST.Pleaseallowlocationpermission);
    }

  }


  async function getCurrentPosition() {
    Geolocation.getCurrentPosition(
      async (position) => {
        OnLocation(position);
        console.log(position, 'position....');
        const { coords } = position;
        setMarkerCoordinate({ latitude: coords.latitude, longitude: coords.longitude });

      },
      (error) => {
        notify(ST.Cannotgetuserposition);
      },
      { enableHighAccuracy: true, distanceFilter: 10, interval: 1000, fastestInterval: 2000 }
    );
  }

  async function getLocationUpdates(storeData1) {
    Geolocation.watchPosition(
      async (position) => {
        OnLocation(position, storeData1);
      },
      (error) => {
        notify(ST.Cannotgetuserposition);
      },
      { enableHighAccuracy: true, distanceFilter: 1, interval: 10000, fastestInterval: 5000, maximumAge: 0 }
    )
  }

  async function OnLocation(position) {
    let { lat, lng } = currentLocation;
    let { Latitude, Longitude } = locationdata
    let { LATITUDE, LONGITUDE, Status } = locationdata2
    let latitude = (parseFloat(Latitude) || parseFloat(LATITUDE)) || position?.coords?.latitude;
    let longitude = (parseFloat(Longitude) || parseFloat(LONGITUDE)) || position?.coords?.longitude;

    latitude = parseFloat(parseFloat(latitude).toFixed(8).replace("-e", ""));
    longitude = parseFloat(parseFloat(longitude).toFixed(8).replace("-e", ""));

    let loc = { lat: latitude, lng: longitude };

    setMarkerCoordinate(new AnimatedRegion({ latitude: latitude, longitude: longitude }));
    setMarkerInfo({ latitude: latitude, longitude: longitude });
    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 getPosition_global(successCallback) {
    Geolocation.getCurrentPosition(
      async (position) => {
        successCallback(position);
      },
      (error) => {
        notify(ST.Cannotgetuserposition);
      },
      { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
    );
  }

  async function submitCheckIn() {

    if (validate()) {
      // setLoaderTitle(ST.ProcessingCheckIn+'...');
      setProcessing(true);

      async function posSuccessCallback(position) {
        let latitude = position.coords.latitude;
        let longitude = position.coords.longitude;
        latitude = parseFloat(parseFloat(latitude).toFixed(8).replace("-e", ""));
        longitude = parseFloat(parseFloat(longitude).toFixed(8).replace("-e", ""));


        let loc = { lat: latitude, lng: longitude };
        // await uploadCheckIn(loc)
        InsertHomeLocationData(loc)

        //   var distance = checkRange(loc.lat,loc.lng,storeData.Latitude,storeData.Longitude);
        //   console.log('distance in submitCheckIn:',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);  
        //   (isAdhocScreen==true || isBeatPlan==true  || isNonMerchan==true || isNonProg==true)? await createJCP(loc): await uploadCheckIn(loc);
        // }
      }
      await getPosition_global(posSuccessCallback);
    }
  }

  async function createJCP(loc) {
    console.log('createJCP');
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let data = { "UserId": (props.UserId || ''), "JcpType": (isBeatPlan == true ? 2 : (isNonMerchan == true ? 3 : (isNonProg == true ? 5 : 1))), "StoreId": storeData.StoreId, "VisitDate": d2 }
    const url = props.baseurl + getMethodName(METHODS.CREATEJP_METHOD);
    console.log(url, data);
    await UploadData2(url, data)
      .then(async (res) => {
        console.log(res);
        if (res != null && res != '' && res != '0' && parseInt(res) > 0) {
          updateMID(res, loc);// update mid in db
        }
        else {
          setProcessing(false); notify(ST.OopsSomethingwentwrongcannotcreateJCP, 'SHORT');
        }

      })
      .catch((err) => {
        setProcessing(false); console.log(err);
      });

  }
  async function updateMID(MID = 0, loc) {
    try {
      let JcpType = isBeatPlan == true ? 'JourneyPlan_RouteWise' : (isNonMerchan == true ? 'NonMerchandising_JourneyPlan' : isNonProg == true ? 'NonProgram_JourneyPlan' : 'Adhoc_JourneyPlan');

      await db.transaction(async function (txn) {
        let q = `UPDATE  ${JcpType} SET MID='${MID}' WHERE StoreId='${storeData.StoreId}' `;
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('mid updated', storeData.StoreId, MID);
          let new_st = storeData;
          new_st['MID'] = MID;
          setStoreData(new_st);
          uploadCheckIn(loc);

        }, function (Etxn, txnerr) { setProcessing(false); console.log(txnerr); });
      });
    }
    catch (e) {
      setProcessing(false);
      notify(ST.CouldnotcreateJCP, 'SHORT');
    }
  }




  async function onStoreStatusUpdate(txnres2) {
    setProcessing(false);
    if (props.ShowStoreChecklist == true) {
      props.navigation.replace('StoreChecklist', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg });
    }
    else if (props.ShowCompactStoreProfile == true) {
      props.navigation.replace('StoreProfileKyc', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg });
    }
    else if (props.ShowStoreProfile == true) {
      props.navigation.replace('StoreProfile', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg });
    } else if (props.ShowReportAfterCheckIn == true) {
      props.navigation.replace('StoreReport', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg });
    }
    else {
      let allMenuList = await getMenuList();
      if (allMenuList.length > 0) {
        props.navigation.replace('StoreDailyMenu', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg });
      }
      else {
        props.navigation.goBack();
      }
    }

  }

  // **************************** download functionality start ***********************************


  async function startRedownload1() {
    notify(ST.CheckInDataUploadedsuccessfully, 'SHORT');
    if (DownloadTasks.length > 0 && (isAdhocScreen == true || isBeatPlan == true || isNonMerchan == true || isNonProg == true)) {
      setStartDownload(true);
      startRedownload(props, DownloadTasks, dowloadedCount, totalCount, setDowloadedCount, setTotalCount);
    }
    else {
      onStoreStatusUpdate();
    }
  }



  async function onDownloadComplete() {
    setisDataDownloaded(true);
    let count = dowloadedCount + 1;
    setStartDownload(false);
    setDowloadedCount(count);
    notify(ST.DataDownloaded, 'SHORT');
    onStoreStatusUpdate();
  }

  // hide redownload modal and show error modal 
  async function showErrorModal(obj = {}) {
    setDErrorMsg(obj);
    setProcessing(false);
    setStartDownload(false); // hide download modal
    setshowDErrAlert(true); // show alert modal
  }


  async function checkAvailability(storeData1, data) {

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q2 = getAvailblQuery(data.ScreenName, storeData1);
        if (q2 != '' && q2 != null) {

          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            let isAvlbl = getIfAvlbl(data.ScreenName, txnres2, storeData1);
            resolve(isAvlbl);
          }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
        }
        else {
          let isAvlbl = getIfAvlbl(data.ScreenName, {}, storeData1);
          resolve(isAvlbl);
        }
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return false;
    });
  }

  async function getMenuList() {
    let { StoreId, ChannelId, RegionId, StoreTypeId } = storeData;
    return new Promise((resolve, reject) => {

      db.transaction(async function (txn) {
        let q = Q_MenuList(storeData);
        await txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            let arr = [];//txnres.rows.raw();   
            console.log('menulist on checkn:', arr);
            // resolve(arr);
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);
              arr.push(data);
              if (i == (txnres.rows.length - 1)) {
                resolve(arr);
              }
            }
          }
          else {
            resolve([])
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve([]); },);
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log('')
      return []
    })
  }



  function validate() {
    let { lat, lng } = currentLocation;
    if (lat == '' || lat == null) {
      notify("Location not found", 'SHORT');
      return false;
    } else if (lng == '' || lng == null) {
      notify("Location not found", '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 storeDataDetail = imgdata.storeData || {}
      const imgurl = img.uri, imgWidth = img.width, imgHeight = img.ExtendedHeight;
      let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
      let picture_clickedd = isImgFromGallery == true ? img.datetime : new Date();
      let picture_clicked_time = moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
      let picture_clicked_time_for_pic_name = moment(picture_clickedd).format('MMDDYYYY_HHmmss')
      console.log("time", picture_clicked_time);
      console.log("time1", picture_clicked_time_for_pic_name);


      let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
      let calculate_tym_date_over_img = picture_clicked_time;

      let filename = (props.UserId || '') + '_StoreImg-' + calculate_tym_date_for_filename + '.jpg';

      const mark_text1 = calculate_tym_date_over_img;
      const mark_text2 = ' User Id:' + storeDataDetail.EmpId + ' | Image Type: Check In' + ' | Date:' + calculate_tym_date_over_img;

      setStoreImage(filename);
      let imagePath = `${CoverageImagePath}${filename}`;
      console.log("checkin imgurl:", imgurl);
      RNFS.copyFile(imgurl, imagePath)
        .then(async (resn) => {
          // render data with clicked image
          let uri = 'file://' + imagePath;
          setStoreImgPath(uri);
          setSelectedImg(uri)
          // add metdata then resize image and restored back to the imagePath
          let restore_data = { "destFilePath": imagePath, "imgurl": imgurl, imgWidth, imgHeight, mark_text1, mark_text2 }
          let is_restored = await restore_ImageWithMetaData(restore_data, imgdata);
          console.log("image restored:", is_restored);
        }).catch(err => {
          console.log('ERROR: image file write failed!!!', err);
          console.log(err.message, err.code);
        });
    }
    // setProcessing(false);
  }

  async function openCamera() {
    // setShowCamera(true);
    props.navigation.navigate('CameraScreen', { 'getImage': getImage, 'cameraType': (props.CheckinOpenBackCamera ? 'back' : 'front'), 'CheckInCameraGallery': props.CheckInCameraGallery, storeData: storeData, enableCameraFlip: (props.CheckInSwitchingCamera ? true : false) })
  }


  function animateMarkerToRegion(coords) {
    const newCoordinate = coords;
    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(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);

        })
    }
  }



  function _renderMap() {
    const lat = currentLocation.lat ? currentLocation.lat : 28.579660;
    const lng = currentLocation.lng ? currentLocation.lng : 77.321110;

    // const latt=storeData.Latitude?parseFloat(storeData.Latitude):lat;
    // const long=storeData.Longitude?parseFloat(storeData.Longitude):lng;

    if (lat != null) {
      return (
        <View style={[customStyle.mapWrapCon, (Platform.OS === 'ios' ? customStyle.mapWrapConIOS : {})]}>
          <View style={[customStyle.mapWrapper, customStyle.mapWrapperSmall1]}>
            <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}
              />

            </MapView>
          </View>

        </View>
      );
    }
    else {
      return (<View>
        <Text>map not visible</Text>
      </View>)
    }
  }


  async function OpenImgModal(imgPath) {
    setSelectedImg(imgPath)
    setShowModal(true);
    if ((imgPath != '' && imgPath != null)) {
      setShowImageSaveOp(false);
    }
    else {
      setShowImageSaveOp(true);
    }


  }

  function _OpenCaptureImage_Modal(img) {
    const isImageCap = (img != '' || img != null) ? true : false;
    let camera2Label = 'test';
    return (
      <CustomModal
        style={customStyle.PromoImgModal}
        title={"Checkin Image"}
        // message={camera2Label}
        titleStyle={customStyle.PromoImgModal_title}
        messageStyle={customStyle.PromoImgModal_subtitle}
        showModal={showModal}
      >
        {
          isImageCap &&
          <View style={customStyle.PromoImgModalCon}>
            <View style={customStyle.PromoImgModal_ImgWrap}>

              <Image style={[customStyle.PromoImgModal_Img, (Platform.OS == 'ios' ? customStyle.android_flipIMageView : {})]} source={{ uri: SelectedImg }} />
            </View>
            <TouchableOpacity style={customStyle.PromoImgModal_CameraSmall} onPress={() => { openCamera() }}>
              <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
            </TouchableOpacity>

            {!showImageSaveOp &&
              <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelImage(false) }}>
                <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
              </TouchableOpacity>
            }
          </View>
        }
      </CustomModal>
    )
  }

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

    return (
      <View style={[customStyle.gtag_sImageWrap, { bottom: -40 }]}>
        <View style={customStyle.gtag_sImagelbl}>
          <TouchableOpacity style={[customStyle.gtag_sImage_View]} onPress={() => { isImageAvlbl ? OpenImgModal(StoreImgPath) : openCamera() }}>
            {!isImageAvlbl && <CameraImg width={80} height={80} />}
            {isImageAvlbl && <CameraImg3 style={{ marginLeft: 5 }} width={80} height={80}  />}
          </TouchableOpacity>
          {/* {isImageAvlbl && <Image style={[customStyle.gTag_Image,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:StoreImgPath}}/>}     */}
          <Text style={[customStyle.gtag_sImagelblText, { marginTop: 0 }]}>{'Click Selfie'}</Text>
        </View>

      </View>
    );
  }

  function DownloadErrorAlert() {

    let { ErrorMsg, ErrorSubMsg, ErrorDetail } = DErrorMsg;

    return (
      <CustomModal
        style={customStyle.dErrM_Style}
        titleStyle={customStyle.dErrMsg}
        title={(ErrorMsg || '')}
        message={(ErrorSubMsg || '')}
        messageStyle={customStyle.dErrSubMsg}
        showModal={showDErrAlert}
      >
        {ErrorDetail != null && ErrorDetail != '' && <Text style={customStyle.dErrDetail}>{ErrorDetail}</Text>}
        <View style={customStyle.storelVisitM_options}>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setshowDErrAlert(false); props.navigation.goBack(); }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{'Ok'}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }

  const [locationdata, setLocationData] = useState({})
  const [locationdata2, setLocationData2] = useState({})



  useEffect(() => {
    Get_Location_Data();
  }, [])


  // get data from Master_HomeLocation

  async function Get_Location_Data() {
    try {

      let token = await get_item('loginToken');
      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      let desg = loginDetails.Designation || '';


      await db.transaction(async function (txn) {

        let q = `SELECT * from Master_UserHomeLocation`;
        await txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            let data = txnres.rows.item(0);
            setLocationData(data);
            // let arr=[];
            // for(var i=0;i<txnres.rows.length;i++){
            //   let data =txnres.rows.item(i);
            //   arr.push(data);
            //   if(i==txnres.rows.length-1){

            //     console.log(arr, 'arrayyy')
            //     setLocationData(arr);

            //   }
            // }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);

        let q1 = `SELECT * from ${AppTables.HOME_LOCATION} WHERE VISIT_DATE='${d2}'`;
        await txn.executeSql(q1, [], async function (txn2, txnres) {
          console.log(txnres.rows.length, 'data from the table..')
          if (txnres.rows.length > 0) {
            let data = txnres.rows.item(0);
            let { LATITUDE, LONGITUDE, STATUS } = data;
            let newObj = { LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, Status: STATUS }
            setLocationData2(newObj);

            // let arr=[];
            // for(var i=0;i<txnres.rows.length;i++){               
            //   let data =txnres.rows.item(i);

            //   let {LATITUDE, LONGITUDE , STATUS}=data;
            //   let newObj= {LATITUDE:LATITUDE,LONGITUDE:LONGITUDE,Status : STATUS}
            //   console.log(data, 'data from the table..')

            //   arr.push(newObj);
            //   if(i==txnres.rows.length-1){
            //     setLocationData2(arr);
            //   }
            // }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);

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




  // on submit data (save data / upload)


  async function saveData(UploadStatus, loc) {

    console.log("UploadStatus", UploadStatus, loc)

    setShowAlert(false);
    setLoaderTitle(ST.SavingData + '...');
    setProcessing(true);


    try {
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      let now = moment(d1).format('MM/DD/YYYY HH:mm:ss');
      await db.transaction(async function (txn) {

        let { lat, lng } = currentLocation;
        let { lat1, lng1 } = loc;

        let q = `delete from ${AppTables.HOME_LOCATION}  WHERE VISIT_DATE='${d2}' `;

        let statusChage = UploadStatus;

        console.log(statusChage, "statusChage")

        let values = ` ('${d2}','${lat1 || lat}','${lng1 || lng}', '${d2}','${statusChage}')`;
        console.log('values Home Location:', values);
        let insert_q = ` insert into ${AppTables.HOME_LOCATION} (VISIT_DATE ,LATITUDE,LONGITUDE,ADDED_DATE, STATUS) values ${values}`;

        let update_q = `UPDATE  Master_UserHomeLocation SET LocationTaken='${UploadStatus}' WHERE UserName='${props.UserId}' `;
        // let update_q=`UPDATE  Master_UserHomeLocation SET LocationTaken='${UploadStatus}' WHERE UserName='${props.UserId}' `;

        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('home loaction deleted');
          await txn.executeSql(insert_q, [], async function (txn2, txnres3) {
            console.log('Insert Home location done');
            setProcessing(false);
            // notify('Insert home location Successfully.')


          }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot add home location') },);

        }, function (Etxn, txnerr) { console.log(txnerr); });

        // await txn.executeSql(update_q,[],async function (txn2, txnres3) {
        //   console.log('Insert Home location done');
        //   setProcessing(false);
        //   notify('Insert home location Succuessfully.')

        // },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add home location') },);

      });
    }
    catch (e) {
      setProcessing(false);
      notify('Cannot add home location', 'SHORT');
    }
  }
  async function upload_StatusD() {

    async function posSuccessCallback(position) {
      let loc = { lat: position.coords.latitude, lng: position.coords.longitude };
      upload_Status(loc);
    }
    await getPosition_global(posSuccessCallback);

  }

  async function upload_Status(loc) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    if (!validate()) {
      return
    }

    await saveData("I", loc);


    let arr = locationdata2;


    let { lat, lng } = currentLocation;

    let { lat1, lng1 } = loc;
    let obj = {
      "Latitude": lat || lat1,
      "Longitude": lng || lng1,
      "UserId": props.UserId,
    };


    let postData = {
      "MID": 0,
      "Keys": "User_Home_Location",
      "JsonData": JSON.stringify(obj),
      "UserId": props.UserId,
    };

    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    console.log(url, postData);

    await UploadData2(url, postData)
      .then(async (res) => {
        console.log('res:', res);
        if (res?.UploadJsonResult == "Success") {
          await saveData(0, loc);

          // Get_Location_Data()
          setProcessing(false);
          notify('Home Location data upload successfully.')
          props.navigation.goBack();
        }
        else {
          setProcessing(false);
        }
      })
      .catch((err) => {
        console.log(err); setProcessing(false);
      });
  }


  async function onSubmitData() {
    Keyboard.dismiss();
    setShowAlert(true);
  }


  function onSaveCancel() {
    setShowAlert(false);
  }


  let { Latitude, Longitude } = locationdata
  let { LATITUDE, LONGITUDE, Status } = locationdata2
  let latitude = (Number(Latitude) || Number(LATITUDE))

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? false : true)}>
      {!startDownload && processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      {(startDownload && dowloadedCount <= totalCount) && <DownloadDataModal title={ST.DownloadingData} downloadCount={dowloadedCount} totalCount={totalCount} subtitle={downloadingText} />}
      <DownloadErrorAlert />
      <CustomHeader {...props} showaddstore={true} title={'Home Location'} />

      {ConfirmSaveAlert(props, showAlert, onSaveCancel, upload_StatusD)}

      {_OpenCaptureImage_Modal()}
      {/* <CustomCamera cameraType={'front'} enableGallerForScreen={props.CheckInCameraGallery} 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]}>
          {
            <ScrollView contentContainerStyle={customStyle.geotag_scroll} style={{}}>


              {
                // isCancelled.current==false &&  
                _renderMap()
              }


              {/* locationdata?.LocationTaken == 1 && */}

              <View style={[customStyle.gTag_btnWrap, customStyle.gTag_btnWrapCI1]}>
                {
                  (Boolean(latitude) || Status == "0") ?
                    <View style={customStyle.gTag_distanceAway1}>
                      <Text style={customStyle.gTag_distanceAwayLbl1}>{`You have already marked location `}</Text>
                    </View> :
                    (Status == "I" &&
                      <View style={customStyle.gTag_distanceAway}>
                        <Text style={customStyle.gTag_distanceAwayLbl}>{`Your location is not Uploaded on sever`}</Text>
                      </View>
                    )
                }

                {locationdata?.LocationTaken == 1 && Status != "0" &&
                  <GradientButton {...props} title={'Submit'}
                    onPress={() =>
                      // submitCheckIn()
                      onSubmitData()
                    } />
                }

              </View>

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

    </Container>
  );
}



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