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 } 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, resizeImage, restore_ImageWithMetaData, UpdateStoreStatus, UploadData, UploadData2, UploadFormData, getKPIFieldsForKyc } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { AppVersion, common_ImagePath, ImageFolderPath, db, gMap_key, URL_IMAGE, CoverageImagePath, DevType } 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 { 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-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 { NativeModules } from 'react-native';
const { CameraaiModule } = NativeModules;


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 [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 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);
    getData();

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

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

    };

  }, []);

  useEffect(() => {
    console.log('show camera changes:', showCamera);
    console.log('NoCheckIn_Photo:', props.NoCheckIn_Photo);

    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(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 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: 1, interval: 10000, fastestInterval: 5000, maximumAge: 0 }
    )
  }

  async function OnLocation(position, storeData1) {
    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 };
    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 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 };
        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 || isStoreSearch == 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}
    let data = { "UserId": props.UserId || '', "JcpType": isStoreSearch == true ? 6 : (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' : (isStoreSearch == true ? 'StoreSearch_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 uploadCheckIn(loc) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let fpath = Platform.OS == 'ios' ? StoreImgPath.replace('file://', '') : StoreImgPath;
    console.log("fpath", fpath);
    var data1 = new FormData();          
    data1.append('file', {
      uri: fpath ,
      type: 'image/jpg',
      name: StoreImage,
    });

    let foldername=getFolderName(StoreImage);
    console.log('foldername:',foldername);
    data1.append('Foldername',foldername);
    data1.append('Path', d2);
    let data = {
      "Mid": storeData.MID,
      "StoreId": storeData.StoreId,
      "VisitDate": d2,
      "Latitude": (loc.lat || ''),
      "Longitude": (loc.lng || ''),
      "ReasonId": 0,
      "Remark": "",
      "Appversion": DevType == "Prod" ? AppVersion : AppVersion + " Dev",
      // "Appversion":AppVersion+"V1",
      "UploadStatus": "I",
      "UserName": (props.UserId || ''),
      "ImageName": StoreImage,
      "CheckoutImage": "",
    }

    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:', res);
        if (parseInt(res) > 0) {
          InsertCoverageData();
          // Upload Image 
          await UploadFormData(url1,data1)
          .then(async(res1)=>{         
            console.log('res1 image upload:',res1);            
          })
          .catch((err)=>{
            console.log(err);
          });
        }
        else {
          setProcessing(false);
        }
      })
      .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('storecheclistupdate', props.StoreChecklistOnce)
    let AllKPIFields = await getKPIFieldsForKyc();
    console.log("AllKPIFields", AllKPIFields);

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

    let designation = loginDetails.Designation || '';

    // Compute isCompactStoreData
    let ShowCompactStoreProfileRestrict = AllKPIFields?.findIndex((i) => i.KPIFieldName == "CompactStoreProfileRestrict");
    let ShowCompactStoreProfileRestrictObj = ShowCompactStoreProfileRestrict >= 0 ? AllKPIFields[ShowCompactStoreProfileRestrict] : {};
    let ShowCompactStoreSplitArr = ShowCompactStoreProfileRestrictObj?.KPIFieldDisplayName?.split(",") || [];
    const isCompactStoreData = ShowCompactStoreSplitArr;
    console.log('iscompetitorValues-----',storeData.Deviation);
    setProcessing(false);
    if (props.ShowCompactStoreProfile == true) {
      if (!isCompactStoreData.includes(designation)) {
        props.navigation.replace('StoreProfileKyc', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg, isStoreSearch: isStoreSearch, '_fromStoreWise': true });
      }else {
        props.navigation.replace('StoreDailyMenu', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg, isStoreSearch: isStoreSearch, '_fromStoreWise': true });
      }
    } else if (props.ShowStoreProfile == true && storeData.Deviation != 6) {
      props.navigation.replace('StoreProfile', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg, isStoreSearch: isStoreSearch, '_fromStoreWise': true });
    } else if (props.ShowStoreChecklist == true || props.StoreChecklistOnce == true) {
      props.navigation.replace('StoreChecklist', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg, isStoreSearch: isStoreSearch, '_fromStoreWise': true });
    } else if (props.ShowReportAfterCheckIn == true) {
      props.navigation.replace('ReportsMenu', {
        storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan,
        'isNonMerchans': isNonMerchan, isNonProgs: isNonProg, isStoreSearch: isStoreSearch, '_fromStoreWise': true
      });
    } else {
      let allMenuList = await getMenuList();
      if (allMenuList.length > 0) {
        props.navigation.replace('StoreDailyMenu', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg, isStoreSearch: isStoreSearch, '_fromStoreWise': true });
      }
      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 || isStoreSearch == 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 []
    })
  }

  async function InsertCoverageData() {
    try {
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      let now = moment(d1).format('MM/DD/YYYY HH:mm:ss');
      let intime = moment(d1).format('HH:mm:ss');
      let serverDateTime1 = now

      await db.transaction(async function (txn) {

        let { StoreId, MID, ChannelId, StoreCode, EmpId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, ExpiryStock, InTime, OutTime, CameraAllow, AddVisiAllow, LastVisitDate, Score, MinTimeTaken, StoreCategoryId, StoreCategory, StoreClassId, StoreClass, TaxType, GSTno, GSTImage, MTDMerchandised, DistributorId } = storeData;
        let { lat, lng } = currentLocation;
        let q = `delete from ${AppTables.COVERAGE_DATA} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
        console.log("storeId.....", q);
        let storeSearchDlt = `delete from ${AppTables.STORE_SEARCHJCP} where StoreId='${StoreId}' and VisitDate='${d2}' `;
        // let JcpType=isBeatPlan==true?'JourneyPlan_RouteWise':(isAdhocScreen==true?'Adhoc_JourneyPlan':(isNonMerchan==true?'NonMerchandising_JourneyPlan':(isNonProg==true? 'NonProgram_JourneyPlan':'Mapping_JourneyPlan')));
        let JcpType = isStoreSearch == true ? 'StoreSearch_JourneyPlan' :
          (isBeatPlan == true ? 'JourneyPlan_RouteWise' :
            (isAdhocScreen == true ? 'Adhoc_JourneyPlan' :
              (isNonMerchan == true ? 'NonMerchandising_JourneyPlan' :
                (isNonProg == true ? 'NonProgram_JourneyPlan' : 'Mapping_JourneyPlan'))));


        let values = ` ('${StoreId}','${d2}','${lat}','${lng}','${StoreImage}','${serverDateTime1}','${StoreImgPath}','0','','','','${MID}','${JcpType}','${d2}')`;

        // let storeSearchValues = ` ('${MID}','${ChannelId}','${StoreId}','${StoreCode}','${EmpId}','${VisitDate}','${ChainId}','${ChainName}','${StoreName}','${Address}','${Location}','${Landmark}','${CityId}','${CityName}','${StateId}','${StateName}','${RegionId}','${StoreTypeId}','${StoreType}','${StoreCategoryId}','${StoreCategory}','${StoreClassId}','${StoreClass}','${Pincode}','${Latitude}','${Longitude}','${Phone}','${Mobile}','${ContactPerson}','${Email}','${TaxType}','${GSTno}','${GSTImage}',"I",'${GeoTag}','${GeoFenceRadius}','${ExpiryStock}','${InTime}','${OutTime}','${CameraAllow}','${AddVisiAllow}','${LastVisitDate}','${Score},'${MinTimeTaken},,'${MTDMerchandised},,'${DistributorId})`; 
        let storeSearchValues = `('${MID}', '${ChannelId}', '${StoreId}', '${StoreCode}', '${EmpId}', '${VisitDate}', '${ChainId}', '${ChainName}', '${StoreName}', '${Address}', '${Location}', '${Landmark}', '${CityId}', '${CityName}', '${StateId}', '${StateName}', '${RegionId}', '${StoreTypeId}', '${StoreType}', '${StoreCategoryId}', '${StoreCategory}', '${StoreClassId}', '${StoreClass}', '${Pincode}', '${Latitude}', '${Longitude}', '${Phone}', '${Mobile}', '${ContactPerson}', '${Email}', '${TaxType}', '${GSTno}', '${GSTImage}', 'I', '${GeoTag}', '${GeoFenceRadius}', '${ExpiryStock}', '${InTime}', '${OutTime}', '${CameraAllow}', '${AddVisiAllow}', '${LastVisitDate}', '${Score}', '${MinTimeTaken}', '${MTDMerchandised}', '${DistributorId}')`;

        // let values=` ('${StoreId}','${d2}','${lat}','${lng}','${StoreImage}','${now}','${StoreImgPath}','0','','','','${MID}','${JcpType}','${d2}')`; 
        let insert_q = ` insert into ${AppTables.COVERAGE_DATA}(STORE_ID,VISIT_DATE ,LATITUDE,LONGITUDE,IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REASON_ID,REASON,REMARK,STORE_FLAG,MID,JCP_TYPE,ADDED_DATE) values ${values}`;
        let insert_sjp = ` insert into ${AppTables.STORE_SEARCHJCP}(MID, ChannelId, StoreId, StoreCode, EmpId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, StoreCategoryId, StoreCategory,StoreClassId,StoreClass,Pincode,Latitude,Longitude, Phone, Mobile, ContactPerson, Email,TaxType,GSTno,GSTImage,UploadStatus,GeoTag, GeoFenceRadius, ExpiryStock,InTime,OutTime,CameraAllow, AddVisiAllow,LastVisitDate,Score,MinTimeTaken,MTDMerchandised,DistributorId) values ${storeSearchValues}`;
        console.log("storeId.....", insert_q);
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('store coverage deleted');
          // await txn.executeSql(storeSearchDlt,[],async function (txn2, txnres2) {    
          console.log('store search data deleted');
          if (isStoreSearch == true) {
            await txn.executeSql(storeSearchDlt, [], async function (txn2, txnres2) {
              console.log('Store search data deleted');
              await txn.executeSql(insert_sjp, [], async function (txn2, txnres3) {
                console.log('Insert StoreSearchJCP done');
              }, function (Etxn, txnerr) { console.log(txnerr); });
            }, function (Etxn, txnerr) { console.log(txnerr); });
          }
          await txn.executeSql(insert_q, [], async function (txn2, txnres3) {
            console.log('InsertCoverageData done');
          }, function (Etxn, txnerr) { console.log(txnerr); })
        }, function (Etxn, txnerr) { console.log(txnerr); });

        let q2 = `delete from ${AppTables.CHECKIN_DATA} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
        let values2 = ` ('${StoreId}','${d2}','${lat}','${lng}','${serverDateTime1}','${StoreImgPath}','','','','${JcpType}','${d2}')`;
        let insert_q2 = ` INSERT INTO ${AppTables.CHECKIN_DATA}(STORE_ID,VISIT_DATE,LATITUDE,LONGITUDE,CHECKIN_TIME,CHECKIN_IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REMARK,JCP_TYPE,ADDED_DATE) values ${values2}`;
        let udata = { StoreId: StoreId, MID: MID, UploadStatus: 'I', tbname: JcpType };
        console.log("values2", values2);
        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');
            // Adding extra fields dynamically
            udata.InTime = intime;
            udata.outtime = "00:00:00";
            console.log("values2", udata);
            UpdateStoreStatus(props, udata, startRedownload1)// update uploadstatus
          }, function (Etxn, txnerr) { console.log(txnerr); });

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

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

  function validate() {
    if ((!props.NoCheckIn_Photo && StoreImage == '') || (!props.NoCheckIn_Photo && StoreImage == null)) {
      notify(ST.Pleaseclickselfieinfrontofstore, 'SHORT');
      return false;
    }

    return true;
  }


  const getImageSize = (imgurl) => {
    return new Promise((resolve, reject) => {
      Image.getSize(
        'file://' + imgurl,
        (width, height) => {
          resolve({ width, height });
        },
        (error) => {
          console.error('Failed to get image dimensions:', error, 'file://' + imgurl);
          reject(error);
        }
      );
    });
  };

  async function getImage(imgdata) {
    console.log('inside store check-in')
    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();
      ///nishant 
      const { width, height } = await getImageSize(imgurl);
      // let picture_clicked_time=moment(picture_clickedd).format('DD-MM-YYYY HH:mm:ss')
      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 = storeDataDetail.StoreId + '_' + (props.UserId || '') + '_StoreImg-' + calculate_tym_date_for_filename + '.jpg';
      console.log(filename, "file_name");
      setStoreImage(filename);
      const mark_text1 = calculate_tym_date_over_img;
      const mark_text2 = 'Store Name:' + storeDataDetail.StoreName + ' | Store Id:' + storeDataDetail.StoreId + ' | User Id:' + storeDataDetail.EmpId + ' | Image Type: Check In' + ' | Date:' + calculate_tym_date_over_img;

      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: width || imgWidth, imgHeight: height || 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);
        });
    }
  }

  async function openCamera() {
    // console.log("platform------",Platform.OS);
    if (props.FaceRecognition && Platform.OS == 'android') {
      let imagePath = `${common_ImagePath}Test.jpg`;
      // console.log("imagePath------",imagePath);
      let res = await CameraaiModule?.initializeSDK({ "filePath": imagePath })
      // console.log("imagePath------2",res);
      await getImage({ uri: res, storeData: storeData })

    } else {
      props.navigation.navigate('CameraScreen', { 'getImage': getImage, 'cameraType': (props.CheckinOpenBackCamera ? 'back' : 'front'), 'CheckInCameraGallery': props.CheckInCameraGallery, storeData: storeData, enableCameraFlip: (props.CheckInSwitchingCamera ? true : false) })
    }
  }


  function moveMarkerToPos(e) {
    let coords = e.nativeEvent.coordinate;
    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 });
    }
  }


  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}
              provider={PROVIDER_GOOGLE}
              style={customStyle.mapStyle}
              showsUserLocation={true}
              zoomEnabled={true}

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


  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 (
      <>
        {!props?.NoCheckIn_Photo && (
                  <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>
        
                      <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); props.navigation.goBack(); }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{'Ok'}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {!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={ST.StoreCheckIn} />
      {_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]}>
          {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, customStyle.storel_codeTextAddr]}>{storeData.Address}</Text>
                      </View>
                    </View>
                  </View>
                </View>

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


              <View style={[customStyle.gTag_btnWrap, customStyle.gTag_btnWrapCI]}>
                {
                  storeDistance > props.GeoFenceRadius && props.GeoFenceEnable == true &&
                  <View style={customStyle.gTag_distanceAway}>
                    <Text style={customStyle.gTag_distanceAwayLbl}>{`${ST.Youare} ${storeDistanceText} ${ST.Awayfromthestore}`}</Text>
                  </View>
                }

                <GradientButton {...props} title={ST.CheckIn} disabled={props.GeoFenceEnable == true ? (storeDistance > props.GeoFenceRadius ? true : false) : false}
                  colors={props.GeoFenceEnable == true ? (storeDistance > props.GeoFenceRadius ? [PageTheme.$text_color_light, PageTheme.$text_color_light] : null) : null}
                  onPress={() => {
                    props.GeoFenceEnable == true ? (storeDistance > props.GeoFenceRadius ? true : submitCheckIn()) : submitCheckIn()
                  }} />
              </View>

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

    </Container>
  );
}



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