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, getDownloadJson1, marktext1, marktext2, UpdateStoreStatus, UploadData, UploadData2, UploadFormData, fetchProjectConfig } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { AppVersion, common_ImagePath, db, gMap_key, URL_IMAGE } 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';
import CustomCamera from '../components/Camera';
import { getAvailblQuery, getIfAvlbl, Q_MenuList } from '../constants/ConstantQueries';
import { executeTasks, getReDownloadTasks1, startRedownload } from '../components/downloadTasks';
import CustomModal from '../components/CustomModal';
import DownloadDataModal from '../components/downloadDataModal';


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();
  const [markerPos, setMarkerPos] = useState({});
  const [markerTitle, setMarkerTitle] = useState('');
  const [markerPlaceText, setMarkerPlaceText] = useState('');
  const [loaderTitle, setLoaderTitle] = useState();
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [storeDistanceText, setStoreDistanceText] = useState('0 m');
  const [storeDistance, setStoreDistance] = useState(0);
  const [showCamera, setShowCamera] = useState(false);
  const [getImageProps, setGetImageProps] = useState({});
  const [EmpData, setEmpData] = useState([]);
  const [IsSearchedStore, setIsSearchedStore] = 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 [isNPNDScreen, setisNPNDScreen] = useState(false);
  const [designation, setDesignation] = useState('');

  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(() => {
    (async () => {
      setLoaderTitle(ST.Loading + '...')
      let params = props.route.params ? props.route.params : {};
      let storeData1 = params.storeData || {};

      console.log(storeData1, "storeData1---->>>>>>")

      let empData1 = params.empData || {};
      let IsSearchedStore1 = params.IsSearchedStore != null && params.IsSearchedStore == 1 ? true : false;

      console.log("IsSearchedStore1", IsSearchedStore1)

      let isAdhoc = params.isAdhoc || false;
      let isNPND = params.isNPND != null ? params.isNPND : false;

      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);

      setDesignation(loginDetails?.Designation)

      setisNPNDScreen(isNPND)
      setIsAdhocScreen(isAdhoc);
      setIsSearchedStore(IsSearchedStore1);
      setEmpData(empData1);
      setStoreData(storeData1);
      calLocatDistance(storeData1);


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

      return function cleanup() {
        isCancelled.current = true;
        Geolocation.clearWatch()
        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]);

  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 calLocatDistance(storeData1) {
  //   console.log('calLocatDistance storeData1:', storeData1);
  //   if (storeData1.Latitude != '' && storeData1.Latitude != null) {
  //     const hasPermission = await _checkLocationPermission();
  //     if (hasPermission == true) {
  //       getCurrentPosition(storeData1);
  //       getLocationUpdates(storeData1);
  //     }
  //     else {
  //       notify(ST.Pleaseallowlocationpermission);
  //     }
  //   }
  //   else {
  //     notify(ST.Storelocationnotavailable);
  //   }
  // }

  async function calLocatDistance(storeData1) {
  console.log('calLocatDistance storeData1:', storeData1);

  let lat = parseFloat(storeData1?.Latitude);
  let lng = parseFloat(storeData1?.Longitude);

  const hasStoreLatLng =
    !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0;

  const hasPermission = await _checkLocationPermission();
  if (!hasPermission) {
    notify(ST.Pleaseallowlocationpermission);
    return;
  }

  if (hasStoreLatLng) {
    // ✅ StoreList case
    getCurrentPosition(storeData1);
    getLocationUpdates(storeData1);
  } else {
    // ✅ GeoTag case → use current device location
    console.log('Store lat/lng missing, using current location');

    Geolocation.getCurrentPosition(
      (position) => {
        const currentLoc = {
          ...storeData1,
          Latitude: position.coords.latitude,
          Longitude: position.coords.longitude,
          __fromGeoTag: true, // debug flag
        };

        getCurrentPosition(currentLoc);
        getLocationUpdates(currentLoc);
      },
      () => {
        notify(ST.Storelocationnotavailable);
      },
      { enableHighAccuracy: true }
    );
  }
}


  async function getCurrentPosition(storeData1) {
    Geolocation.getCurrentPosition(
      async (position) => {
        OnLocation(position, storeData1);
      },
      (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: 20, 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 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 loc = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        //const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
        const { StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
        console.log("storewisePjp_get_chekin::", storeSearch, storewisePjp);


        // --- final condition ---
        (storewisePjp && (isAdhocScreen || isNPNDScreen))
          ? await createJCP(loc, storewisePjp, storeSearch)
          : await uploadCheckIn(loc, storewisePjp, storeSearch);
      }

      await getPosition_global(posSuccessCallback);
    }
  }

  console.log("isAdhocScreen", isAdhocScreen);

  async function createJCP(loc, storewisePjp, storeSearch) {
    console.log("create JCP called")
    console.log('createJCP', designation == "Supervisor");
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let data = { "UserId": (props.UserId || ''), "JcpType": isAdhocScreen ? 1 : (IsSearchedStore ? 0 : 1), "StoreId": storeData.StoreId, "VisitDate": d2, "EmpId": storeData.MerchandiserId }
    const url = props.baseurl + getMethodName(METHODS.CREATEJP_METHOD_SUPWISE);
    console.log(url, data);
    await UploadData2(url, data)
      .then(async (res) => {
        console.log("create JCP res:", res);
        if (res != null && res != '' && res != '0' && parseInt(res) > 0) {
          let isupdated = await updateMID(res, storewisePjp, storeSearch);// update mid in db
          if (isupdated) {
            // if MID updated call checkin function 
            await uploadCheckIn(loc, storewisePjp, storeSearch);
            // setProcessing(false);notify("PJP created"+res,'SHORT');
            // console.log("hold upload check in")
          }
          else {
            setProcessing(false); notify("Something went wrong! Cannot update MID:" + res, 'SHORT');
          }
        }
        else {
          setProcessing(false); notify(ST.OopsSomethingwentwrongcannotcreateJCP, 'SHORT');
        }

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

  }
  async function updateMID(MID = 0, storewisePjp, storeSearch) {
    console.log("updateMID:", MID)
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let tbname = '';
        console.log("IsSearchedStore===", IsSearchedStore)
        let ShowStoreSearch = storeSearch ? storeSearch : false;

        // ShowStoreSearch = true ; // add naita static 

        console.log("designation", designation, "props.SUP_StorewisePJP", storewisePjp, ShowStoreSearch)


        //  if (ShowStoreSearch && storewisePjp === true) 
        if (ShowStoreSearch ? (designation == "Supervisor" && storewisePjp == true) : storewisePjp == true) {
          tbname = isAdhocScreen == true ? "Sup_JourneyPlanStorewiseSup_Adhoc" : isNPNDScreen ? "Sup_NPNDStore" : "Sup_JourneyPlanStorewiseSup";
          console.log('tbnamestore', tbname)
        }

        else {
          tbname = isAdhocScreen == true ? "Sup_AdhocJourneyPlan" : isNPNDScreen ? "Sup_NPNDStore" : "Sup_JourneyPlan";
          console.log('tbnameteamlist', tbname)
        }



        let q = `UPDATE  ${tbname} SET MID='${MID}' WHERE StoreId='${storeData.StoreId}' and MerchandiserId='${storeData.MerchandiserId}'  `;

        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);
          resolve(true);
        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });
      });
    }).catch((err) => {
      console.log(err);
      return false;
    })

  }
  async function uploadCheckIn(loc, storewisePjp, storeSearch) {

    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let fpath = Platform.OS == 'ios' ? StoreImgPath.replace('file://', '') : StoreImgPath;
    console.log(fpath);
    let Deviation = (isAdhocScreen == true) ? 1 : isNPNDScreen ? 2 : 0;
    var data1 = new FormData();

    data1.append('file', {
      uri: fpath,
      type: 'image/jpg',
      name: StoreImage,
    });

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

    data = {
      "StoreId": storeData.StoreId,
      "VisitDate": d2,
      "MerchandiserId": storeData.MerchandiserId,
      "Latitude": (loc.lat || ''),
      "Longitude": (loc.lng || ''),
      "ReasonId": 0,
      "Remark": "",
      "CheckInImage": StoreImage,
      "AppVersion": AppVersion,
      "Checkout_Image": "",
      "ChainId": "",
      "StoreTypeId": "",
      "ChannelId": "",
      "UploadStatus": "I",
      "UserId": (props.UserId || ''),
      "Deviation": Deviation,
    }


    const url = props.baseurl + getMethodName(METHODS.GETCOVERAGE_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 uploadCheckIn:', res);
        let Store_MID = res;
        if (parseInt(res) > 0) {

          let data2 = {
            "UserId": (props.UserId || ''),
            "StoreId": storeData.StoreId,
            "MerchandiserId": storeData.MerchandiserId,
            "VisitDate": d2,
            "Status": "I",
          }


          const url2 = props.baseurl + getMethodName(METHODS.STORECOVERAGE_STATUS_METHOD);
          console.log(url2, data2);

          await UploadData2(url2, data2)
            .then(async (res) => {
              // MID need to updated here only when Create JCP method called in Search Wise store case
              let isMIDUpdated = await updateMID(Store_MID, storewisePjp, storeSearch);
              console.log('coverage status res:', res, isMIDUpdated, storewisePjp);
              if (parseInt(res) > 0) {
                InsertCoverageData(storewisePjp, storeSearch);
              }
              else if (res == 1) {
                notify('Cannot update CheckIn Status! ' + res.error, 'SHORT');
                setProcessing(false);
              }
            })
            .catch((err) => {
              console.log('onPage Team error/', err);
              setProcessing(false);
            });

          console.log('checkindata', JSON.stringify(data1))
          // Upload Image 
          await UploadFormData(url1, data1)

            .then(async (res1) => {
              console.log('res1 image upload:', res1);
            })
            .catch((err) => {
              console.log(err);
            });

        }
        else {
          setProcessing(false);
          notify('Something went wrong! Not able to do checkin', 'SHORT');
        }
      })
      .catch((err) => {
        console.log(err); setProcessing(false);
      });
  }
  function exit() {
    setTimeout(() => {
      notify(ST.CheckinSuccessful, 'LONG');
      setProcessing(false);
      setTimeout(() => { props.navigation.goBack(); }, 100);
    }, 1000)
  }

  async function onStoreStatusUpdate(txnres2) {
    console.log('onStoreStatusUpdate')
    setProcessing(false);
    notify(ST.CheckInDataUploadedsuccessfully, 'SHORT');

    // props.navigation.navigate('StoreDailyMenu',{storeData:storeData,'isAdhoc':isAdhocScreen});
    let allMenuList = await getMenuList(isAdhocScreen, isNPNDScreen, true);

    console.log(allMenuList, "allMenuList--->>")
    if (allMenuList.length > 0) {

      let isPosSale = allMenuList?.some(item => item.ScreenName === 'POSSALE');

      console.log(isPosSale, "isPosSale before")


      // isPosSale = true ; 

      console.log(isPosSale, "isPosSale after");

      if (isPosSale) {
        getposSaledefinationdata();
      }
      else {
        props.navigation.replace('StoreDailyMenu', { storeData: storeData, empData: (EmpData || ''), 'isAdhoc': isAdhocScreen, isNPND: isNPNDScreen });
      }
    }
    else {
      props.navigation.goBack();
    }
  }

  async function checkAvailability(storeData1, data, checkPosale = false) {

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q2 = getAvailblQuery(data.ScreenName, storeData1, data, checkPosale);
        // console.log('Executing query check availability:', q2);
        if (q2 != '' && q2 != null) {

          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            let isAvlbl = getIfAvlbl(data.ScreenName, txnres2, storeData1);
            console.log(data.ScreenName, "isAvlbl:", isAvlbl); // for check the avaliable screen
            resolve(isAvlbl);
          }, function (txn2, 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(isAdhoc, isNPND, checkPosale = false) {
    let { StoreId, ChannelId, RegionId, StoreTypeId } = storeData;
    return new Promise((resolve, reject) => {

      db.transaction(async function (txn) {
        let q = Q_MenuList(storeData, isAdhoc, isNPND);

        await txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            let arr = [];
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);

              console.log(data, "data of menu'ss")

              let isAvlbl = await checkAvailability(storeData, data, checkPosale);

              if (isAvlbl) {
                arr.push(data);
              }

              if (i == (txnres.rows.length - 1)) {
                resolve(arr);
              }
            }
          }
          else {
            resolve([])
          }
        }, function (txn2, txnerr) { console.log(txnerr); resolve([]); },);
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log('')
      return []
    })
  }

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

        let { StoreId, MID } = storeData;
        let storeStr = JSON.stringify(storeData)
        let { lat, lng } = currentLocation;
        let JcpType = '';

        console.log(isNPNDScreen, "IsSearchedStore===", IsSearchedStore, storeData)
        let ShowStoreSearch = storeSearch ? storeSearch : false;

        // console.log("designation",designation, "props.SUP_StorewisePJP",props.SUP_StorewisePJP)

        // ShowStoreSearch = true ; // change 18 april (night)
        console.log("ShowStoreSearch", ShowStoreSearch)
        if (ShowStoreSearch && designation != "Supervisor") {
          JcpType = "Sup_JourneyPlan"
          InsertPJP(storeData);
          console.log('jcpstore', JcpType)
        }

        else if
          //  (ShowStoreSearch && storewisePjp === true)
          (ShowStoreSearch ? (designation == "Supervisor" && storewisePjp == true) : storewisePjp == true) {
          JcpType = isAdhocScreen == true ? "Sup_JourneyPlanStorewiseSup_Adhoc" : isNPNDScreen ? "Sup_NPNDStore" : "Sup_JourneyPlanStorewiseSup";
          console.log('jcpstore', JcpType)
        }
        else {
          JcpType = isAdhocScreen == true ? "Sup_AdhocJourneyPlan" : isNPNDScreen ? "Sup_NPNDStore" : "Sup_JourneyPlan";
          console.log('jcpeteamlist', JcpType)
        }

        //  Delete old data and insert new checkin data in COVERAGE_DATA table

        let q = `delete from ${AppTables.COVERAGE_DATA} where EMP_ID='${storeData.MerchandiserId}}' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;

        let values = ` ('${storeData.MerchandiserId}','${StoreId}','${d2}','${lat}','${lng}','${StoreImage}','${now}','${StoreImgPath}','0','','','','${MID}','${JcpType}','${d2}','${storeStr}','I')`;
        let insert_q = ` insert into ${AppTables.COVERAGE_DATA}(EMP_ID,STORE_ID,VISIT_DATE ,LATITUDE,LONGITUDE,IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REASON_ID,REASON,REMARK,STORE_FLAG,MID,JCP_TYPE,ADDED_DATE,STORE_OBJ,STATUS) values ${values}`;
        console.log('insert_q', insert_q)
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('store coverage deleted');
          await txn.executeSql(insert_q, [], async function (txn2, txnres3) {
            console.log('InsertCoverageData done');
          }, function (txn2, txnerr) { console.log(txnerr); });
        }, function (txn2, txnerr) { console.log(txnerr); });


        //  Delete old data and insert new checkin data in CHECKIN_DATA table
        let q2 = `delete from ${AppTables.CHECKIN_DATA} where EMP_ID='${storeData.MerchandiserId}' and STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;

        let values2 = ` ('${storeData.MerchandiserId}','${StoreId}','${d2}','${lat}','${lng}','${now}','${StoreImgPath}','','','','${JcpType}','${d2}')`;
        let insert_q2 = `INSERT INTO ${AppTables.CHECKIN_DATA}(EMP_ID,STORE_ID,VISIT_DATE,LATITUDE,LONGITUDE,CHECKIN_TIME,CHECKIN_IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REMARK,JCP_TYPE,ADDED_DATE) values ${values2}`;
        console.warn("values2----", insert_q2)
        await txn.executeSql(q2, [], async function (txn2, txnres2) {
          console.log('removed');
          await txn.executeSql(insert_q2, [], async function (txn2, txnres3) {
            console.log('checkin data added');
            let udata = { StoreId: StoreId, MID: MID, UploadStatus: 'I', tbname: JcpType, EmpId: storeData.MerchandiserId };
            UpdateStoreStatus(props, udata, startRedownload1)// update uploadstatus
          }, function (txn2, txnerr) { console.log(txnerr); });

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




        // only if its comes from showscreen
        // let values3=` ('${storeData.MerchandiserId}','${StoreId}','${d2}','${lat}','${lng}','${StoreImage}','${now}','${StoreImgPath}','0','','','','${MID}','${JcpType}','${d2}','${storeStr}','I')`; 
        // let insert_q3=` insert into ${JcpType}(EMP_ID,STORE_ID,VISIT_DATE ,LATITUDE,LONGITUDE,IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REASON_ID,REASON,REMARK,STORE_FLAG,MID,JCP_TYPE,ADDED_DATE,STORE_OBJ,STATUS) values ${values3}`;
        // console.log('insert_q',insert_q)
        // await txn.executeSql(q,[],async function (txn2, txnres2) {
        //   console.log('store coverage deleted'); 
        //   await txn.executeSql(insert_q,[],async function (txn2, txnres3) {
        //     console.log('Insert        ===  Data done');
        //   },function(txn2,txnerr){console.log(txnerr);});
        // },function(txn2,txnerr){console.log(txnerr);});


      });
    }
    catch (e) {
      setProcessing(false);
      notify(ST.CouldnotaddCheckIndata, 'SHORT');
    }
  }

  // when store search 

  // Insert PJP before check in 

  async function InsertPJP(storeData1) {

    console.log("Insert PJP store data=======>", storeData1)

    return new Promise((resolve, reject) => {

      var values = [], sql_stmnt = '', all_vals = '';
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      let tbname = 'Sup_JourneyPlan';

      let { MID, ChannelId, StoreId, StoreCode, EmpId, MerchandiserId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, InTime, OutTime, CameraAllow } = storeData1;
      values.push(` ('${MID}', '${ChannelId}', '${StoreId}', '${StoreCode}', '${EmpId}', '${MerchandiserId}', '${VisitDate}', '${ChainId}', '${ChainName}', '${StoreName}', '${Address}', '${Location}', '${Landmark}', '${CityId}', '${CityName}', '${StateId}', '${StateName}', '${RegionId}', '${StoreTypeId}', '${StoreType}', '${Pincode}', '${Latitude}', '${Longitude}', '${Phone}', '${Mobile}', '${ContactPerson}', '${Email}', '${UploadStatus}', '${GeoTag}', '${GeoFenceRadius}', '${InTime}', '${OutTime}','${CameraAllow}')`);
      all_vals = values.join(',');
      sql_stmnt = `INSERT INTO ${tbname}(MID,ChannelId,StoreId,StoreCode,EmpId,MerchandiserId,VisitDate,ChainId,ChainName,StoreName,Address,Location,Landmark,CityId,CityName,StateId,StateName,RegionId,StoreTypeId,StoreType,Pincode,Latitude,Longitude,Phone,Mobile,ContactPerson,Email,UploadStatus,GeoTag,GeoFenceRadius,InTime,OutTime,CameraAllow) 
                values ${all_vals}`;

      let q = `select * from ${tbname} where VisitDate='${d2}' and StoreId='${StoreId}' and  MerchandiserId='${MerchandiserId}' `;

      db.transaction(async function (txn) {
        await txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            // This store has already been added in storelistPJP!!
            console.log("This store has already been added in storelistPJP!!");
            // notify("This store has already been visited!")
            resolve(false);
          }
          else {
            // This store is not added in storelistPJP yet!! then add store
            await txn.executeSql(sql_stmnt, [], async function (txn2, txnres2) {
              resolve(true);
            }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });
          }

        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });
      })
    }).catch((err) => {
      console.log(err);
      return false;
    })

  }


  function validate() {
    console.log('validate checkin:', StoreImage, storeDistance, props.GeoFenceEnable, props.GeoFenceRadiu);
    if (StoreImage == '' || StoreImage == null) {
      notify(ST.Pleaseclickselfieinfrontofstore, 'SHORT');
      return false;
    }
    else if (props.GeoFenceEnable == true && storeDistance > props.GeoFenceRadius) {
      notify(`You are outside the geofenceradius ${storeDistance} m`, '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;
      const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: Geo Tag' + ' | Date:' + picture_clicked_time;

      console.log('imgurl marktext1:', imgurl);
      await marktext1(mark_text1, imgurl)
        .then((res) => {
          if (res.success) {

            let uri = res.uri;
            console.log("uri--------", uri, imgWidth, imgHeight)
            marktext2(mark_text2, uri, imgWidth, imgHeight)
              .then((res) => {
                console.log("test---", 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 = storeData.StoreId + '_' + (props.UserId || '') + '_StoreImg-' + picture_clicked_date + '_' + picture_clicked_time + '.jpg';

                  setStoreImage(filename);
                  // renamefile
                  let imagePath = 'file://' + `${common_ImagePath}${filename}`;
                  RNFS.moveFile(res.uri, imagePath)
                    .then(resn => {
                      let uri = imagePath;
                      console.log('image marker', uri);
                      setStoreImgPath(uri);
                    })
                    .catch(err => {
                      console.log('ERROR: image file write failed!!!');
                      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() {
    console.log("camer----open")
    setShowCamera(true);
    // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'front'})
  }


  function moveMarkerToPos(e) {
    let coords = e.nativeEvent.coordinate;

    // 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;
    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);

        })
    }
  }

  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 });
    }
  }

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

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

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




  async function onDownloadComplete() {
    // Data downloaded
    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
  }


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

  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={() => { openCamera() }}>
            {!isImageAvlbl && <SvgXml width={80} height={80} xml={cameraImg} />}
            {isImageAvlbl && <Image style={[customStyle.gTag_Image, (Platform.OS == 'ios' ? customStyle.android_flipIMageView : {})]} source={{ uri: StoreImgPath }} />}
          </TouchableOpacity>
          <Text style={[customStyle.gtag_sImagelblText, { marginTop: 0 }]}>{ST.ClickSelfieinfrontofStore}</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) }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{'Ok'}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }


  // console.log(storeData, "storeData--->>>>")


  // add posSale (download Sup_Mapping_StorePosSaleDefinition when user click on checkin .)
  async function DownloadDataPosSaleDefination() {
    setLoaderTitle("Downloading " + "Store PosSale defination Data...");
    setProcessing(true);
    let downloadKey = "Sup_Mapping_StorePosSaleDefinition";


    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);

    let data = '';

    data = {
      Downloadtype: downloadKey,
      Username: loginDetails.UserId,
      Param1: storeData?.StoreId,
      Param2: '',

    }

    console.log(url, data);
    return await getDownloadJson1(url, data)
      .then(async (res) => {
        console.log("DownloadDataPosSaleDefinationn res:", res);

        // Check if the response contains "No Data" result
        //  if (res?.[0]?.Result == "No Data" || res.Sup_Mapping_StorePosSaleDefinition == null || res.Sup_Mapping_StorePosSaleDefinition === '') {
        //   setProcessing(false);
        //   notify("No data found for possale defination list.");
        //   props.navigation.replace('StoreDailyMenu',{storeData:storeData,empData:(EmpData||''),'isAdhoc':isAdhocScreen,isNPND:isNPNDScreen});
        //   return [];
        //  }

        if (res.Sup_Mapping_StorePosSaleDefinition != null || res.Sup_Mapping_StorePosSaleDefinition != '') {
          setProcessing(false);
          let posSaleArr = res.Sup_Mapping_StorePosSaleDefinition;
          let isInserted = await InsertDownloadedPosSale(posSaleArr);

          console.log('Inserted data:', posSaleArr);
          console.log('isInserted:', isInserted)
          if (isInserted) {
            // notify("possale defination list downloaded successfully.");
            props.navigation.replace('StoreDailyMenu', { storeData: storeData, empData: (EmpData || ''), 'isAdhoc': isAdhocScreen, isNPND: isNPNDScreen });

          }
          else {
            setProcessing(false);
            // notify("No data found for possale defination list.");
            props.navigation.replace('StoreDailyMenu', { storeData: storeData, empData: (EmpData || ''), 'isAdhoc': isAdhocScreen, isNPND: isNPNDScreen });
            return [];
          }
        }
        else {
          // notify('No data found!');
          props.navigation.replace('StoreDailyMenu', { storeData: storeData, empData: (EmpData || ''), 'isAdhoc': isAdhocScreen, isNPND: isNPNDScreen });
          setProcessing(false);
          return [];
        }

      })
      .catch((err) => {
        console.log('onPage Team error', err);
        setProcessing(false);
        // notify("Cannot download store posSale defination data!")
        return [];
      });
  }


  async function InsertDownloadedPosSale(posSaleArr) {
    console.log("insert download posSale called");
    return new Promise((resolve, reject) => {

      var values = [], sql_stmnt = '', all_vals = '';
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      let tbname = 'Sup_Mapping_StorePosSaleDefinition';
      let storeId = storeData.StoreId;
      let q = `Delete from ${tbname} where VisitDate='${d2}' AND StoreId='${storeId}' `;

      posSaleArr.map((data_obj) => {
        let { PosDefinitionId, StoreId, VisitDate } = data_obj;
        values.push(` ('${PosDefinitionId}', '${StoreId}', '${VisitDate}')`);
      });
      all_vals = values.join(',');
      sql_stmnt = `INSERT INTO ${tbname}(PosDefinitionId,StoreId,VisitDate) 
        values ${all_vals}`;

      db.transaction(async function (txn) {
        await txn.executeSql(q, [], async function (txn2, txnres4) {
          console.log('removeddata');
          await txn.executeSql(sql_stmnt, [], async function (txn2, txnres2) {
            resolve(true);
          }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });
        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });
      })
    }).catch((err) => {
      console.log(err);
      return false;
    })

  }

  async function getposSaledefinationdata() {
    setProcessing(true);
    try {
      await db.transaction(async (txn) => {
        let query = `
            SELECT DISTINCT * FROM Sup_Mapping_StorePosSaleDefinition Where StoreId = '${storeData?.StoreId}' AND VisitDate = '${d2}';`;

        console.log(query, "query");

        txn.executeSql(query, [], (txn, result) => {
          if (result.rows.length > 0) {
            console.log(result.rows.length, "result.rows.length")
            props.navigation.replace('StoreDailyMenu', { storeData: storeData, empData: (EmpData || ''), 'isAdhoc': isAdhocScreen, isNPND: isNPNDScreen });
            console.log(arr, "get posSale defination data list ........");
          }
          else {
            console.log('Table is empty. Triggering data download.');
            DownloadDataPosSaleDefination();
            // setProcessing(false);
          }
        }, (error) => {
          setProcessing(false);
          console.log("Error while executing getposSaledefinationdata SQL: ", error);
        });
      });
    } catch (err) {
      console.log("Error in get pos Saledefinationdata function: ", err);
      setProcessing(false);
    }
  }
  // end download

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      {(startDownload && dowloadedCount <= totalCount) && <DownloadDataModal title={ST.DownloadingData} downloadCount={dowloadedCount} totalCount={totalCount} subtitle={downloadingText} />}
      <DownloadErrorAlert />
      <CustomHeader {...props} title={ST.StoreCheckIn} />
      <CustomCamera cameraType={'front'} 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, customStyle.gTag_btnWrapCI]}>
                {
                  storeDistance > props.GeoFenceRadius &&
                  <View style={customStyle.gTag_distanceAway}>
                    <Text style={customStyle.gTag_distanceAwayLbl}>{`${ST.Youare} ${storeDistanceText} ${ST.Awayfromthestore}`}</Text>
                  </View>
                }
                <GradientButton {...props} title={ST.CheckIn} onPress={() => { submitCheckIn() }} />
              </View>

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

    </Container>
  );
}



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