import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useFocusEffect, useRoute } from '@react-navigation/native';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, DeviceEventEmitter, PermissionsAndroid, 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 { clear_item, get_item } from '../components/localStorage';
import CustomHeader from '../components/customHeader';
import { Entypo, Ionicons, MaterialCommunityIcons } from '../components/icons';
import { UploadData2, checkRange, getAllFileForAFolder, restore_ImageWithMetaData, uploadContractFormFiles, validateNumber, validateNumber12, validateStoreAddStoreInfoText } from '../controller/functions';
import CustomLoader from '../components/CustomLoader';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import MapIcon from '../assets/performics/map_icon.svg';
import Geolocation from 'react-native-geolocation-service';
import { db, CoverageImagePath, AppVersion, AddStoreImagePath, URL_IMAGE } from '../constants/constants';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg from '../assets/performics/camera_front_image.svg'
import CustomModal from '../components/CustomModal';
import MapView, { AnimatedRegion, Marker, Polyline, PROVIDER_GOOGLE } from 'react-native-maps';
import reports_icon from '../assets/performics/sidemenu_icons/reports_icon.svg';

import { _checkLocationPermission } from '../components/geolocation';
import { CustomPicker } from '../components/CustomPicker';
import { ConfirmSaveAlert } from '../components/alert';
import { METHODS, getMethodName } from '../constants/methodNames';
import { UploadImagesWithoutWait } from '../constants/uploadData';

function AddStoreInfo(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 globalStyle = globalStyles(props.DarkMode, route.name);

  const [processing, setProcessing] = useState(false);
  const [loaderTitle, setLoaderTitle] = useState();
  const [designation, setDesignation] = useState('');
  // setSelectedDistributorId
  const [distributorname, setDistributorName] = useState([]);
  const [cityname, setCityName] = useState([]);
  const [storetype, setStoreType] = useState([]);

  const [distributornameid, setSelectedDistributorNameId] = useState([]);
  const [citynameid, setSelectedCityNameId] = useState([]);
  const [storetypeid, setSelectedStoreTypeId] = useState([]);


  const [addstoreinfo, setAddStoreInfo] = useState([]);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [AddStoreinfoFormData, setAddStoreInfoFormData] = useState({});
  const [isAddVisPresent, setIsAddVisPresent] = useState(0);


  const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
  const WindowDataRef = React.useRef(addstoreinfo);
  const VisFormDataRef = React.useRef(AddStoreinfoFormData);
  const isAddVisPresentRef = React.useRef(isAddVisPresent);


  const [rerenderdata, setrerenderdata] = useState(0);
  const [rerenderdata2, setrerenderdata2] = useState(0);

  const [showCamera, setShowCamera] = useState(false);
  const [selectedValue, setSelectedValue] = useState(null);
  const [selectedCityValue, setSelectedCityValue] = useState(null);
  const [selectedStoretypeValue, setSelectedStoretypeValue] = useState(null);
  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 [storeData, setStoreData] = useState({});
  const [StoreImgPath, setStoreImgPath] = useState('');
  const [SelectedStoreImg, setSelectedStoreImg] = useState('');
  const [showStoreModal, setShowStoreModal] = useState(false);
  const [StoreImage, setStoreImage] = useState('');
  const [SelectedImg, setSelectedImg] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [showImgModal, setShowImgModal] = useState(false);
  const [showImageSaveOp, setShowImageSaveOp] = useState(true);
  const [storeDistanceText, setStoreDistanceText] = useState('0 m');
  const [storeDistance, setStoreDistance] = useState(0);
  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 + '...')
    const onImageCapturedSubs = DeviceEventEmitter.addListener('onImageCaptured', (imgData) => { getImage(imgData) });

    Get_Master_DistributorFilter();

    calLocatDistance();

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

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

  }, []);

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

  useFocusEffect(
    React.useCallback(() => {
      Get_Master_DistributorFilter();
    }, [])
  );

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

  async function Get_Master_DistributorFilter() {
    try {

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

      await db.transaction(async function (txn) {

        let q = `SELECT * from Master_DistributorFilter`;
        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);
              arr.push(data);
              if (i == txnres.rows.length - 1) {
                setDistributorName(arr);
                setrerenderdata(!rerenderdata);
              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);

        let q1 = `SELECT * from Master_CityFilter`;
        await txn.executeSql(q1, [], 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);
              arr.push(data);
              if (i == txnres.rows.length - 1) {
                setCityName(arr);
                setrerenderdata(!rerenderdata);
              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);

        let q2 = `SELECT * from Master_StoreTypeFilter`;
        await txn.executeSql(q2, [], 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);
              arr.push(data);
              if (i == txnres.rows.length - 1) {
                setStoreType(arr);
                setProcessing(false);
                setrerenderdata(!rerenderdata);
              }
            }
          }
          else {
            setProcessing(false);
          }
        }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); },);

        let q3 = `SELECT * from ${AppTables.ADD_STORE_INFO} WHERE VISIT_DATE='${d2}'`;
        await txn.executeSql(q3, [], async function (txn2, txnres) {
          console.log(txnres.rows.length, 'data from the table..')
          if (txnres.rows.length > 0) {
            let arr = [];
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);

              let { DISTRIBUTOR_NAME, DISTRIBUTOR_ID, STORE_NAME, STORE_ADDRESS, CITY_NAME, CITY_ID, STORETYPE_NAME, STORETYPE_ID, IMAGE, IMAGEPATH, LAT, LNG, STATUS } = data;
              let newObj = { DistributorName: DISTRIBUTOR_NAME, DistributorId: DISTRIBUTOR_ID, StoreName: STORE_NAME, StoreAddress: STORE_ADDRESS, CityName: CITY_NAME, CityId: CITY_ID, StoreType: STORETYPE_NAME, StoreTypeId: STORETYPE_ID, ImageName: IMAGE, ImagePath: IMAGEPATH, Longitude: LAT, Latitude: LNG, Status: STATUS }
              console.log(data, 'data from the table..')

              arr.push(newObj);
              if (i == txnres.rows.length - 1) {
                setAddStoreInfo(arr);
                setrerenderdata(!rerenderdata);
              }
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);

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


  function BgAddVisFormData(val) {
    console.log(val, "valval")
    VisFormDataRef.current = val
    setAddStoreInfoFormData(val);
  }

  function BgIsAddVisPresent(val) {
    isAddVisPresentRef.current = val
    setIsAddVisPresent(val);
  }

  function CleanSelector(option, keyLbl = '', data = {}) {

    if (keyLbl == 'CategoryName') {
      Get_Master_DistributorFilter(option.value, 'SubCategories');

      // clear subcategory and brand
      data['SubCategoryId'] = '';
      data['SubCategoryName'] = '';
      data['BrandId'] = '';
      data['BrandName'] = '';


      data['DisplayId'] = ''
      data['DisplayName'] = ''
      data['Remark'] = ''
      data['Image1Path'] = ''

    }
    else if (keyLbl == 'SubCategoryName') {
      Get_Master_DistributorFilter(option.value, 'Brands');

      // clear brand
      data['BrandId'] = '';
      data['BrandName'] = '';

      data['DisplayId'] = ''
      data['DisplayName'] = ''

      data['Image1Path'] = ''

      data['Remark'] = ''

    } else if (keyLbl == 'BrandName') {

      // clear brand

      data['DisplayId'] = ''
      data['DisplayName'] = ''

      data['Image1Path'] = ''

      data['Remark'] = ''

    } else if (keyLbl == 'DisplayName') {

      // clear brand

      data['Image1Path'] = ''

      data['Remark'] = ''

    }

  }


  function onselectionChange(option, keyLbl, keyVal) {
    let data = AddStoreinfoFormData;
    data[keyVal] = option.value;
    data[keyLbl] = option.label;

    CleanSelector(option, keyLbl, data)

    BgAddVisFormData(data)
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true)
    setrerenderdata(!rerenderdata);

  }


  function _render_Distributor_Option(props) {
    return (

      <View style={[{ paddingHorizontal: 10, width: '100%' }]}>
        <Text style={[customStyle.sform_label3, { marginTop: 10 }]}>Select Distributor Name :</Text>

        {CustomPicker(props, distributorname, 'DistributorName', 'DistributorId', 'DistributorName', 'DistributorId', onselectionChange, { value: AddStoreinfoFormData.DistributorName })}

      </View>
    )
  }

  function _render_City_Option() {
    return (

      <View style={[{ paddingHorizontal: 10, width: '100%' }]}>
        <Text style={[customStyle.sform_label3, { marginTop: 0 }]}>Select City Name :</Text>

        {CustomPicker(props, cityname, 'CityName', 'CityId', 'CityName', 'CityId', onselectionChange, { value: AddStoreinfoFormData.CityName })}

      </View>
    )
  }

  function _render_Storetype_Option() {
    return (
      <View style={[{ paddingHorizontal: 10, width: '100%' }]}>
        <Text style={[customStyle.sform_label3, { marginTop: 10 }]}>Select Store Type :</Text>
        {CustomPicker(props, storetype, 'StoreType', 'StoreTypeId', 'StoreType', 'StoreTypeId', onselectionChange, { value: AddStoreinfoFormData.StoreType })}
      </View>
    )
  }

  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 getLocationUpdates() {
    Geolocation.watchPosition(
      async (position) => {
        OnLocation(position);
      },
      (error) => {
        notify(ST.Cannotgetuserposition);
      },
      { enableHighAccuracy: true, distanceFilter: 1, interval: 10000, fastestInterval: 5000, maximumAge: 0 }
    )
  }

  async function OnLocation(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 };

    setMarkerCoordinate(new AnimatedRegion({ latitude: latitude, longitude: longitude }));
    setMarkerInfo({ latitude: latitude, longitude: longitude });
    setAddStoreInfoFormData(prevState => ({
      ...prevState,
      Latitude: latitude,
      Longitude: longitude
    }));
    setCurrentLocation(loc);
  }

  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....')

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


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


  function BgWindowData(val) {
    WindowDataRef.current = val
    setAddStoreInfo(val);
  }

  function BgUnsavedChanges(val) {
    hasUnsavedChangesRef.current = val
    setHasUnsavedChanges(val);
  }


  async function validateForm() {

    let isValid = true;

    let { DistributorName, DistributorId, CityName, CityId, StoreType, StoreTypeId, StoreName, StoreAddress, Remark, Image1, Image1Path, FromDate, ToDate, showFromDateFlag } = AddStoreinfoFormData;

    if ((DistributorName == '' || DistributorName == null) || (DistributorId == '' || DistributorId == null)) {
      isValid = false;
      notify(ST.Pleaseselectdistributorname, 'SHORT');
    }

    else if ((StoreName == '' || StoreName == null)) {
      isValid = false;
      notify(ST.Pleasefillthestorename, 'SHORT');
    }
    else if ((StoreAddress == '' || StoreAddress == null)) {
      isValid = false;
      notify(ST.Pleasefillthestoreaddress, 'SHORT');
    }
    else if ((CityName == '' || CityName == null) || (CityId == '' || CityId == null)) {
      isValid = false;
      notify(ST.Pleaseselectcityname, 'SHORT');
    }
    else if ((StoreType == '' || StoreType == null) || (StoreTypeId == '' || StoreTypeId == null)) {
      isValid = false;
      notify(ST.Pleaseselectstoretype, 'SHORT');
    }
    else if (StoreImage == '' || StoreImage == null) {
      isValid = false;
      notify(ST.Pleaseclickselfieinfrontofstore, 'SHORT');

    }

    console.log('isValid:', isValid);
    return isValid;
  }


  async function Add_StoreInfo() {

    let isValid = await validateForm();
    console.log('isValid add:', isValid);
    if (isValid) {
      let arr = addstoreinfo;
      let StoreinfoObj = AddStoreinfoFormData;
      StoreinfoObj["UserId"] = props.UserId;

      arr.push(StoreinfoObj);
      BgWindowData(arr);
      BgUnsavedChanges(true);
      notify(ST.AddStoreInfoaddedsuccessfully, 'LONG');
      setrerenderdata(!rerenderdata);
      BgAddVisFormData({});
      setStoreImage('');
      setStoreImgPath('')

    }
  }

  function onFormDataChange(val, key, type = '') {
    if (val != '') {
      let isValid = validateNumber12(val, type);
      if (!isValid) {
        return;
      }
    }

    let data = AddStoreinfoFormData;
    data[key] = val;
    // setAddVisFormData(data);
    // setHasUnsavedChanges(true);
    BgAddVisFormData(data);
    BgUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }

  async function validateAndAddStoreInfo() {
    let isValid = await validateForm();
    console.log('isValid:', isValid);
    if (isValid) {
      Add_StoreInfo();
    }
  }

  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();
      ////change by jeevanp
      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);
      ////change by jeevanp
      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 || '') + '_AddStoreInfoImg-' + calculate_tym_date_for_filename + '.jpg';
      console.log(filename, "file_name");

      const mark_text1 = calculate_tym_date_over_img;
      const mark_text2 = 'User Id:' + props.UserId + ' | Image Type: Add Store Info' + ' | Date:' + calculate_tym_date_over_img;
      console.log(mark_text1 + "\n" + mark_text2, "mark_text2");

      setStoreImage(filename);

      setAddStoreInfoFormData(prevState => ({
        ...prevState,
        ['ImageName']: filename
      }));

      let imagePath = `${AddStoreImagePath}${filename}`;
      console.log("checkin imgurl:", imagePath, imgurl);
      RNFS.copyFile(imgurl, imagePath)
        .then(async (resn) => {
          // render data with clicked image
          let uri = 'file://' + imagePath;
          setStoreImgPath(uri);
          setSelectedImg(uri)
          // Update AddStoreinfoFormData object
          setAddStoreInfoFormData(prevState => ({
            ...prevState,
            ['ImagePath']: uri // Use filename as key and image data as value
          }));

          // BgAddVisFormData(addstoreinfo)
          BgUnsavedChanges(true)
          setrerenderdata2(!rerenderdata2);
          // 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);
        });
    }
  }


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

  function cancelStoreImage() {

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

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

  }

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

    return (
      <View style={[
        customStyle.mapWrapCon,
        (Platform.OS === 'ios' ? customStyle.mapWrapConIOS : {}), { marginHorizontal: 25 }]}>
        <View style={[
          customStyle.mapWrapperStoreInfo,
          customStyle.mapWrapperStoreInfoSmall,
        ]}>
          <MapView
            ref={MyMap}
            provider={PROVIDER_GOOGLE}
            style={customStyle.mapStyleStorInfo}
            showsUserLocation={true}
            zoomEnabled={true}
            initialCamera={{
              center: {
                latitude: lat,
                longitude: lng,
              },
              pitch: 7,
              heading: 7,
              altitude: 100,
              zoom: 19,
            }}
          >
            <Marker.Animated
              ref={MyMarker}
              // coordinate={{ latitude: lat, longitude: lng }} 
              coordinate={markerCoordinate}
              pinColor={'#ff78b6'}
              title={markerTitle}
              description={markerPlaceText}
            />

          </MapView>
        </View>
        {_render_captureImage()}
      </View>
    );

  }

  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) ? await createJCP(loc) : await uploadCheckIn(loc);
      }

      await getPosition_global(posSuccessCallback);
    }
  }


  function _OpenCaptureImage_Modal(img) {
    const isImageCap = (img != '' || img != null) ? true : false;
    let camera2Label = 'test';
    return (
      <CustomModal
        style={customStyle.PromoImgModal}
        title={ST.CheckinImage}
        // 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 }]}>{ST.ClickStoreFrontImage}</Text>
        </View>

      </View>
    );
  }

  useEffect(() => {

  }, [])

  async function OpenStoreImgModal(imgPath) {

    setSelectedStoreImg(imgPath);
    setShowStoreModal(true);
    console.log("imgPath------", imgPath)
    if ((imgPath != '' && imgPath != null)) {
      setShowImageSaveOp(false);
    }
    else {
      setShowImageSaveOp(true);
    }

  }

  function _Open_Image_Modal(img) {
    const isImageCap = (img != '' || img != null) ? true : false;

    return (
      <CustomModal
        style={customStyle.PromoImgModal}
        title={ST.CheckinImage}
        // message={camera2Label}
        titleStyle={customStyle.PromoImgModal_title}
        messageStyle={customStyle.PromoImgModal_subtitle}
        showModal={showImgModal}
      >
        {
          isImageCap &&
          <View style={customStyle.PromoImgModalCon}>
            <View style={customStyle.PromoImgModal_ImgWrap}>
              <Image style={[customStyle.PromoImgModal_Img, (Platform.OS == 'ios' ? customStyle.android_flipIMageView : {})]} source={{ uri: SelectedStoreImg }} />
            </View>


            <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelStoreImage(false) }}>
              <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
            </TouchableOpacity>

          </View>
        }
      </CustomModal>
    )
  }

  function onSaveCancel() {
    setShowAlert(false);
  }

  async function onSubmitData() {
    const hasUStatus = addstoreinfo?.some(item => item?.Status !== "U");

    console.log(hasUStatus, 'hasUStatus');  // gives us true if any of Status is not equal to "U" from the array of object.

    if (addstoreinfo.length === 0) {
      notify(ST.Pleaseclickaddfirst);
    }
    else if (!hasUStatus) {
      notify(ST.Pleaseclickaddfirst);
    }
    else {

      Keyboard.dismiss();
      setShowAlert(true);
    }
  }

  async function saveData(UploadStatus) {

    console.log(UploadStatus, "UploadStatus")
    // setHasUnsavedChanges(false);
    BgUnsavedChanges(false)
    setShowAlert(false);
    setLoaderTitle(ST.SavingData + '...');
    setProcessing(true);
    try {

      await db.transaction(async function (txn) {

        let q = `DELETE FROM ${AppTables.ADD_STORE_INFO} WHERE VISIT_DATE ='${d2}' `;

        //  remove old data
        await txn.executeSql(q, [], async function (txn2, txnres) {
          console.log('av data deleted');
        }, function (txnE, txnerr) { console.log(txnerr); },);

        var values = '';

        if (addstoreinfo.length > 0) {
          for (var i = 0; i < addstoreinfo.length; i++) {
            let catIndex = i;
            let item = addstoreinfo[catIndex];
            let statusChage = item.Status == "U" ? "U" : UploadStatus;
            let { DistributorName, DistributorId, StoreName, StoreAddress, CityName, CityId, StoreType, StoreTypeId, Latitude, ImageName, ImagePath, Longitude } = item;
            values += values != '' ? ' , ' : '';
            values += ` ('${d2}','${DistributorName}','${DistributorId}','${StoreName}','${StoreAddress}','${CityName}','${CityId}','${StoreType}','${StoreTypeId}','${Latitude}','${Longitude}','${ImageName}','${ImagePath}','${d2}','${statusChage}') `;
            // VISIT_DATE , DISTRIBUTOR_NAME , DISTRIBUTOR_ID , STORE_NAME , STORE_ADDRESS ,CITY_NAME ,CITY_ID ,STORETYPE_NAME ,STORETYPE_ID  ,IMAGE ,LAT ,LNG , ADDED_DATE 
          }
        }

        console.log('values ADD_STORE_INFO:', values);
        let add_data = `INSERT INTO ${AppTables.ADD_STORE_INFO} (VISIT_DATE, DISTRIBUTOR_NAME, DISTRIBUTOR_ID , STORE_NAME , STORE_ADDRESS ,CITY_NAME ,CITY_ID ,STORETYPE_NAME ,STORETYPE_ID ,LAT,LNG,IMAGE,IMAGEPATH,ADDED_DATE, STATUS) VALUES ${values} `;

        await txn.executeSql(add_data, [], async function (txn2, txnres) {
          console.log('av added');
          notify(ST.AddStoreInfoaddedsuccessfully, 'SHORT');
          // setProcessing(false);
          // clear store data in local storage to avoiding re-set data for the store  
          clear_item('storeData')
        }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify(ST.Cannotaddaddstoreinfo) },);


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

  async function upload_Status() {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let fpath = Platform.OS == 'ios' ? StoreImgPath.replace('file://', '') : StoreImgPath;
    console.log(fpath, 'path of imaggege');
    await saveData("I");

    // {"CityId": 8, "CityName": "EAST", "DistributorId": 44, "DistributorName": "A.D.M.Distributors", "Image": "file:///data/user/0/com.performics/files/PerformicsAllImages/CoverageImages/undefined_testmer_StoreImg-20240403_095006.jpg", "Latitude": 28.5274669, "Longitude": 77.277973, "StoreAddress": "Hchccj", "StoreName": "Cyuff", "StoreType": "KEELLS SUPER", "StoreTypeId": 14}

    setLoaderTitle('Uploading Data...');

    let storeInfo = addstoreinfo
    let arr = []

    storeInfo?.map((item, i) => {
      let itemObj = item;
      if (item.Status != "U") {
        delete itemObj.ImagePath;
        arr.push(itemObj);
        return itemObj
      }
    })


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

    console.log("addstoreinfo-------------ad", addstoreinfo)

    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    -
      console.log(url, postData, 'url and postDaata...');
    let allFilesToUpload = await getAllFileForAFolder(AddStoreImagePath, "AddNewStoreImages");

    console.log('allFilesToUpload--------allFilesToUpload', allFilesToUpload);
    await uploadContractFormFiles12(allFilesToUpload)

    await UploadData2(url, postData)
      .then(async (res) => {
        console.log('res: 12', res);
        if (res?.UploadJsonResult == "Success") {
          await saveData("U");
          Get_Master_DistributorFilter()
          setProcessing(false);
        }
        else {
          setProcessing(false);
        }
      })
      .catch((err) => {
        console.log(err); setProcessing(false);
      });

  }

  async function uploadContractFormFiles12(allfiles = []) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let uploadCount = 0;
    const url = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);


    var isAllUploaded = false;
    return await Promise.all(
      allfiles.map(async (file, i) => {
        let index = i;
        let actualfilepath = 'file://' + file.uri;
        let isExists = await RNFS.exists(actualfilepath).then((res) => { return res; });
        console.log('isExists file', isExists, file.uri, file);
        let isImageUploaded = false;
        // isExists==false
        if (isExists) {
          let postData = new FormData();
          postData.append('file', {
            uri: actualfilepath,
            // type: mime.getType(actualfilepath),
            type: file.type,
            name: file.name,
          });

          postData.append('Foldername', "AddNewStoreImages");
          postData.append('Path', d2);

          isImageUploaded = await UploadImagesWithoutWait(postData, url);
          if (isImageUploaded == true) {
            console.log('isExists file uploaded', isExists, uploadCount, index, allfiles.length - 1);
            await RNFS.unlink(actualfilepath);
            uploadCount++;
            // UpdateUploadCountLocal(uploadCount+1)
            if (uploadCount == allfiles.length) {
              isAllUploaded = true;
            }

          } else {
            console.log('file not uploaded:', isExists, actualfilepath);
          }

        }
        else {//file does not exists 
          uploadCount++;
          // UpdateUploadCountLocal(uploadCount+1)
          if (uploadCount == allfiles.length) {
            isAllUploaded = true;
          }
        }

        return isImageUploaded;
      })
    ).then((val) => {
      console.log(val);
      return isAllUploaded;
    })
      .catch((err) => {
        console.log(err);
        return false;
      })
  }



  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader title={loaderTitle} />}
      <CustomHeader {...props} showaddstore={true} title={ST.AddStoreInfo} screen={"AddStoreInfo"} />

      { /*<TouchableOpacity style={{alignItems:'flex-end', alignSelf:'flex-end', justifyContent:'flex-end', alignContent:'flex-end', paddingHorizontal:10, marginTop:5}} onPress={() => props.navigation.navigate('StoreInfoList')}>
        <View >
          <Entypo name='dots-three-vertical' size={30} color={PageTheme.$primary_color}/>
        </View> 
      </TouchableOpacity> */}

      {ConfirmSaveAlert(props, showAlert, onSaveCancel, upload_Status)}
      {_OpenCaptureImage_Modal()}
      {_Open_Image_Modal()}


      <ScrollView style={{ flex: 1, width: '100%', paddingRight: 20, paddingLeft: 10 }}>

        {_render_Distributor_Option(props)}
        <View style={[customStyle.AddStockM_row, { marginTop: 10 }]} >
          <Text style={customStyle.AddStockM_label}>{ST.StoreName + ':'}</Text>
          <View style={customStyle.AddStockM_col} >
            <TextInput
              style={[customStyle.AddStockM_InputStyle, { height: 40 }]}
              placeholder=""
              autoComplete='off'
              placeholderTextColor={PageTheme.$placeholder_color}
              // keyboardType={'number-pad'}
              value={(AddStoreinfoFormData.StoreName || '')}
              onChangeText={(val) => { onFormDataChange(val, 'StoreName', 'text') }}
            />
          </View>
        </View>

        <View style={[customStyle.AddStockM_row, { marginTop: 0 }]}>
          <Text style={customStyle.AddStockM_label}>{ST.StoreAddress + ':'}</Text>
          <View style={customStyle.AddStockM_col} >
            <TextInput
              style={[customStyle.AddStockM_InputStyle, { height: 40 }]}
              placeholder=""
              autoComplete='off'
              placeholderTextColor={PageTheme.$placeholder_color}
              // keyboardType={'number-pad'}
              value={(AddStoreinfoFormData.StoreAddress || '')}
              onChangeText={(val) => { onFormDataChange(val, 'StoreAddress', 'text') }}

            />
          </View>
        </View>
        {_render_City_Option()}
        {_render_Storetype_Option()}

        <View style={{ marginVertical: 30 }}>
          {_renderMap()}
        </View>

        <View style={[customStyle.addVis_btnWrap, { marginTop: 10 }]}>
          <TouchableOpacity style={customStyle.addVis_btn}
            onPress={() => { validateAndAddStoreInfo() }}
          >
            <Text style={customStyle.addVisBtnText}>{ST.Add}</Text>
          </TouchableOpacity>
        </View>

        <View style={customStyle.addVis_list}>
          {addstoreinfo.length > 0 && <Text style={customStyle.addVis_listhdrText}>{ST.AddedStores}</Text>}
          <View style={customStyle.addVis_listInner}>
            {
              addstoreinfo.length > 0 &&
              addstoreinfo.map((item, index) => {
                return (
                  <View key={index} style={customStyle.addVis_listItem}>
                    <View style={customStyle.addVis_listI_row2}>
                      <View style={[customStyle.addVis_listIcol1, customStyle.addVis_listIcol100]}>
                        <View style={customStyle.addVis_listI_row}>
                          <Text style={customStyle.addVis_listI_Label}>{ST.DistributorName + ' :'}</Text>
                          <Text style={customStyle.addVis_listI_Val}>{item.DistributorName}</Text>
                        </View>
                        <View style={customStyle.addVis_listI_row}>
                          <Text style={customStyle.addVis_listI_Label}>{ST.StoreName + ' :'}</Text>
                          <Text style={customStyle.addVis_listI_Val}>{item.StoreName}</Text>
                        </View>
                        <View style={customStyle.addVis_listI_row}>
                          <Text style={customStyle.addVis_listI_Label}>{ST.StoreAddress + ' :'}</Text>
                          <Text style={customStyle.addVis_listI_Val}>{item.StoreAddress}</Text>
                        </View>
                        <View style={customStyle.addVis_listI_row}>
                          <Text style={customStyle.addVis_listI_Label}>{ST.CityName + ' :'}</Text>
                          <Text style={customStyle.addVis_listI_Val}>{item.CityName}</Text>
                        </View>
                        <View style={[customStyle.addVis_listI_row]}>
                          <Text style={customStyle.addVis_listI_Label}>{ST.StoreType + ' :'}</Text>
                          <Text style={customStyle.addVis_listI_Val}>{item.StoreType}</Text>
                        </View>
                        { /*<View style={[customStyle.addVis_listI_row]}>
                                  <Text style={customStyle.addVis_listI_Label}>{ST.Latitude+' :'}</Text>
                                  <Text style={customStyle.addVis_listI_Val}>{item.Latitude}</Text>
                                  </View>

                                  <View style={[customStyle.addVis_listI_row]}>
                                  <Text style={customStyle.addVis_listI_Label}>{ST.Longitude+' :'}</Text>
                                  <Text style={customStyle.addVis_listI_Val}>{item.Longitude}</Text>
                                  </View> */}

                        <View style={[customStyle.addVis_listI_row, { alignItems: 'center' }]}>
                          <Text style={customStyle.addVis_listI_Label}>{ST.StoreImage + ' :'}</Text>

                          <TouchableOpacity onPress={() => { setShowImgModal(true); setSelectedStoreImg(item?.ImagePath) }} >
                            <CameraImg3 style={{ marginLeft: 5 }} width={40} height={40} />
                          </TouchableOpacity>

                          {item.Status == "I" &&
                            <View style={[customStyle.storel_usCon]}>
                              <Text style={[customStyle.storel_usText, { color: 'red' }]}>{"Upload Pending"}</Text>
                            </View>
                          }

                          {item.Status == "U" &&
                            <View style={[customStyle.storel_usCon]}>
                              <Ionicons name='checkmark-done-sharp' color='green' size={20} />
                              <Text style={[customStyle.storel_usText, { color: 'green' }]}>{ST.Uploaded}</Text>
                            </View>
                          }
                        </View>


                      </View>

                      <View style={{ alignItems: 'flex-end', marginLeft: 15, marginTop: -15 }}>
                        <TouchableOpacity
                          activeOpacity={0.5}
                          style={customStyle.storel_geotag_btn}
                          onPress={() => {
                            props.navigation.navigate('ShowMap', { storeData: item });
                          }}>
                          <MapIcon width={30} height={30} />
                        </TouchableOpacity>
                      </View>
                    </View>
                  </View>
                );
              })
            }
          </View>

          <View style={{ alignItems: 'center', paddingBottom: 20, paddingTop: -20 }} >
            <GradientButton {...props} title={'Save'} onPress={() => { onSubmitData() }} />
          </View>

        </View>
      </ScrollView>

    </Container>
  );
}

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


