import React, { useState, useEffect, useRef, memo } from "react";
import { Text, TouchableOpacity, View, Image, StatusBar } from "react-native";
import { GetPageTheme, customStyles, globalStyles } from "../styles/Global";
import { useRoute } from '@react-navigation/native';
import { AntDesign, Entypo, FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons } from "./icons";
import { notify } from "./notify";
import moment from "moment";
import { AppTables } from "../constants/tableConstants";
import { db } from "../constants/constants";
import { SvgXml } from "react-native-svg";
import * as RNFS from 'react-native-fs';

import MapIcon from '../assets/performics/map_icon.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CustomCamera from '../components/Camera';
import { get_item } from "./localStorage";
import { getMethodName, METHODS } from "../constants/methodNames";
import { getDownloadJson1, fetchProjectConfig } from "../controller/functions";


const StoreItem = memo((props) => {
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  const route = useRoute();
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const item = props.item;
  //console.log("sdata.CheckInTime", item.CheckInTime)
  // console.log("itemitem====",item)
  const isAlreadyCheckedIn = props?.isAlreadyCheckedIn;

  // console.log("store detail data--",item?.CheckInTime != "" && item?.CheckInTime != null ? item.StoreId : "anita")

  const ST = props.StaticText || {};
  const IsSearchedStore = props.IsSearchedStore != null && props.IsSearchedStore == true ? true : false;
  // console.log("IsSearchedStore",IsSearchedStore)
  const isNPNDScreen = props.isNPNDScreen != null && props.isNPNDScreen == true ? true : false;

  const CheckInStoreIds = props.CheckInStoreIds != null && typeof props.CheckInStoreIds == "object" ? props.CheckInStoreIds : [];


  // add posSale (download Sup_Mapping_StorePosSaleDefinition when user click on checkin .)
  async function DownloadDataPosSaleDefination(data1) {
    props.setLoaderTitle("Downloading " + "Store PosSale defination Data...");
    props.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: item?.StoreId,
      Param2: '',

    }

    console.log(url, data);
    return await getDownloadJson1(url, data)
      .then(async (res) => {
        console.log("DownloadDataPosSaleDefination res:", res);
        if (res.Sup_Mapping_StorePosSaleDefinition != null || res.Sup_Mapping_StorePosSaleDefinition != '') {
          props.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.navigate('StoreDailyMenu', { storeData: data1, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore, isNPND: isNPNDScreen });
          }
          else {
            props.setProcessing(false);
            // notify("No data found for possale defination list.");
            props.navigation.navigate('StoreDailyMenu', { storeData: data1, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore, isNPND: isNPNDScreen });
            return [];
          }
        }
        else {
          // notify('No data found!');
          props.setProcessing(false);
          props.navigation.navigate('StoreDailyMenu', { storeData: data1, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore, isNPND: isNPNDScreen });
          return [];
        }

      })
      .catch((err) => {
        console.log('onPage Team error', err);
        props.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 = item.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(data1) {
    props.setProcessing(true);
    try {
      await db.transaction(async (txn) => {
        let query = `
            SELECT DISTINCT * FROM Sup_Mapping_StorePosSaleDefinition Where StoreId = '${item?.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.navigate('StoreDailyMenu', { storeData: data1, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore, isNPND: isNPNDScreen });

          }
          else {
            console.log('Table is empty. Triggering data download.');
            DownloadDataPosSaleDefination(data1);
            // setProcessing(false);
          }
        }, (error) => {
          props.setProcessing(false);
          console.log("Error while executing getposSaledefinationdata SQL: ", error);
        });
      });
    } catch (err) {
      console.log("Error in get pos Saledefinationdata function: ", err);
      props.setProcessing(false);
    }
  }
  // end download

  async function get_posSaleStoredefinationdata(data1) {
    try {
      await db.transaction(async function (txn) {
        let q = `select count() as count from Sup_Mapping_StorePosSaleDefinition where StoreId= '${item.StoreId}' `;
        await txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length >= 0) {
            let data = txnres.rows.item(0);
            console.log(data, "data--->");
            if (data?.count > 0) {
              props.navigation.navigate('StoreDailyMenu', { storeData: data1, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore, isNPND: isNPNDScreen });
              console.log("no need to download the data.")
            } else {
              getposSaledefinationdata(data1);
            }
          }
        }, function (txnE, txnerr) { console.log(txnerr); },);
      });
    } catch (err) {
      console.log(err);
      props.setProcessing(false);
    }
  }


  async function get_to_store_details(data) {
    console.log("===IsSearchedStore===", IsSearchedStore, "called ===", data);
    const { StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
    // const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);

    if (data.UploadStatus == 'U') {
      notify(ST.AllDataalreadyuploadedforthisstore);
      // props.navigation.navigate('StoreDailyMenu',{storeData:data,'isAdhoc':props.isAdhocScreen,'IsSearchedStore':IsSearchedStore});
    }
    else if (data.UploadStatus == 'L') {
      notify(ST.Alreadymarkedasnotworkingstatusforthisstore);
    }
    else if (data.UploadStatus == 'I') {

      let isChcekedIn = await checkIfCheckInAvlbl(storewisePjp, storeSearch);
      console.log('isChcekedIn==storewisePjp', isChcekedIn, storewisePjp);
      console.log("data=======", data)
      let menuList = data.MenuList;
      console.log('menuList length:', menuList?.length);
      if (storewisePjp == true) {

        if (isChcekedIn == true) {
          if (menuList?.length > 0) {
            props.set_autoback({ 'AutoGoToPrev': false });

            let isPosSale = menuList?.some(item => item.ScreenName == 'POSSALE');
            if (isPosSale) {
              get_posSaleStoredefinationdata(data);
            }
            else {
              props.navigation.navigate('StoreDailyMenu', { storeData: data, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore, isNPND: isNPNDScreen });
            }

          }
        }
        else {
          console.log("restore checkin called ======")
          let isrestored = await restoreCheckIn(data, storewisePjp, storeSearch);

          props.setProcessing(false);
          console.log('isrestored:', isrestored);
          if (isrestored == true) {
            if (menuList?.length > 0) {
              props.set_autoback({ 'AutoGoToPrev': false });

              let isPosSale = menuList?.some(item => item.ScreenName == 'POSSALE');
              if (isPosSale) {
                get_posSaleStoredefinationdata(data);
              }
              else {
                props.navigation.navigate('StoreDailyMenu', { storeData: data, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore, isNPND: isNPNDScreen });
              }
            }
          }
          else {
            notify(ST.CheckIndatanotavailable);
          }

        }

      }
      else {
        if (isChcekedIn == true) {

          console.log("menuList--->", menuList)
          console.log("menuList---ccc>", isChcekedIn)

          if (menuList?.length > 0) {
            props.set_autoback({ 'AutoGoToPrev': false });

            let isPosSale = menuList?.some(item => item.ScreenName == 'POSSALE');
            if (isPosSale) {
              get_posSaleStoredefinationdata(data);
            }
            else {
              props.navigation.navigate('StoreDailyMenu', { storeData: data, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore, isNPND: isNPNDScreen });
            }
          }
        }
        else {
          console.log("helllllooooo--->")
          let isrestored = await restoreCheckIn(data, storewisePjp, storeSearch);
          props.setProcessing(false);
          console.log('isrestored:', isrestored);
          if (isrestored == true) {
            if (menuList?.length > 0) {
              props.set_autoback({ 'AutoGoToPrev': false });

              let isPosSale = menuList?.some(item => item.ScreenName == 'POSSALE');
              if (isPosSale) {
                get_posSaleStoredefinationdata(data);
              }
              else {
                props.navigation.navigate('StoreDailyMenu', { storeData: data, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore, isNPND: isNPNDScreen });
              }
            }
          }
          else {
            notify(ST.CheckIndatanotavailable);
          }

        }

      }
    }
    else if (data.UploadStatus == 'C') {
      notify(ST.Alreadycheckedout);
    }
    else if (data.UploadStatus == 'D') {
      notify(ST.Dataalreadyuploaded);
    }
    else if (data.UploadStatus == 'P') {
      notify(ST.Datapartiallyuploaded);
    }
    else if (data.UploadStatus == 'N' || data.UploadStatus == '') {
      console.log('isChcekedIn');
      let isChcekedIn = await checkIfAlreadyCheckdIn(storewisePjp, storeSearch);
      console.log('isChcekedIn', isChcekedIn);
      if (isChcekedIn == true) {
        notify(ST.Youarealreadycheckedintotheotherstore, 'LONG');
      }
      else if (IsSearchedStore && CheckInStoreIds.indexOf(item.StoreId) >= 0) {
        // this store is already checked in
        notify("This store is already Checked-In");
      }
      else if (isAlreadyCheckedIn) {
        notify(ST.Youarealreadycheckedintotheotherstore, 'LONG');
      }
      else {
        if (IsSearchedStore && props.InsertPJP != null) {
          console.log("insert pjp is called ======")
          let isInserted = await props.InsertPJP(item);
          console.log("isPJPInserted:", isInserted);
        }
        console.log("go to checkin screen ======")
        props.setShowStoreVisitModal(true);
        props.setCurrentStore(data);
      }
    }

  }



  async function checkIfCheckInAvlbl(storewisePjp, storeSearch) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let join, join2, q, q2;
    let execQ2 = true;
    let ShowStoreSearch = storeSearch ? storeSearch : false;
    console.log("storewisePjp:", storewisePjp);


    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {

        if (storewisePjp) {
          join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_JourneyPlanStorewiseSup' `;
          q = `Select t1.* from Sup_JourneyPlanStorewiseSup t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`

          join2 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_JourneyPlanStorewiseSup_Adhoc' `;
          q2 = `Select t1.* from Sup_JourneyPlanStorewiseSup_Adhoc t1 ${join2} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
        } else if (isNPNDScreen) {
          join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_NPNDStore' `;
          q = `Select t1.* from Sup_NPNDStore t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`

          join2 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_AdhocJourneyPlan' `;
          q2 = `Select t1.* from Sup_AdhocJourneyPlan t1 ${join2} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
        }
        else {
          join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_JourneyPlan' `;
          q = `Select t1.* from Sup_JourneyPlan t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`

          join2 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_AdhocJourneyPlan' `;
          q2 = `Select t1.* from Sup_AdhocJourneyPlan t1 ${join2} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
        }


        console.log('checkIfCheckInAvlbl q:', q)
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('checkIfCheckInAvlbl q count:', txnres2.rows.length)
          if (txnres2.rows.length > 0) {
            // show from local
            resolve(true);
          }
          else if (execQ2) {
            txn.executeSql(q2, [], async function (txn2, txnres3) {
              if (txnres3.rows.length > 0) {
                // show from local
                resolve(true);
              }
              else {
                resolve(false);
              }
            }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });
          }
          else {
            resolve(false);
          }
        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });

      });

    }).then((val) => {
      return val;
    }).catch((err) => {
      return false;
    });
  }


  async function AskForCancelCheckin(data) {
    props.setCancelCheckOutStore(data);
    props.setShowCancelCIModal(true);
  }


  async function restoreCheckIn(item, storewisePjp, storeSearch) {
    try {
      props.setLoaderTitle(ST.YouhaveclearedtheAppDataRestoringCheckinInfo + '...');
      props.setProcessing(true);

      const d2 = moment(new Date()).format('MM/DD/YYYY');

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

        const { StoreId, VisitDate, MID, Latitude, Longitude, InTime, OutTime, MerchandiserId, UploadStatus } = item;

        console.log("restoreCheckIn item:", item);

        let JcpType = storewisePjp
          ? (props.isAdhocScreen ? "Sup_JourneyPlanStorewiseSup_Adhoc" : (props.isNPNDScreen ? "Sup_NPNDStore" : "Sup_JourneyPlanStorewiseSup"))
          : (props.isAdhocScreen ? "Sup_AdhocJourneyPlan" : (props.isNPNDScreen ? "Sup_NPNDStore" : "Sup_JourneyPlan"));

        let In_Time = InTime
          ? moment(InTime, InTime.includes('/')
            ? "MM/DD/YYYY HH:mm:ss"
            : "HH:mm:ss"
          ).format("HH:mm:ss")
          : '';

        let Out_Time = ""
        if (UploadStatus !== 'I') {
          Out_Time = OutTime
            ? moment(OutTime, OutTime.includes('/')
              ? "MM/DD/YYYY HH:mm:ss"
              : "HH:mm:ss"
            ).format("HH:mm:ss")
            : '';
        }



        //let In_Time = InTime ? moment(d2 + ' ' + InTime).format('MM/DD/YYYY HH:mm:ss') : '';
        //let Out_Time = OutTime ? moment(d2 + ' ' + OutTime).format('MM/DD/YYYY HH:mm:ss') : '';
        let CHECKOUT_TIME = Out_Time || '';

        db.transaction((txn) => {

          txn.executeSql(
            `DELETE FROM ${AppTables.COVERAGE_DATA}`,
            [],
            () => {
              txn.executeSql(
                `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)
              VALUES (?, ?, ?, ?, ?, '', ?, '', '0', '', '', '', ?, ?, ?)`,
                [MerchandiserId, StoreId, VisitDate, Latitude, Longitude, CHECKOUT_TIME, MID, JcpType, d2],
                () => {
                  txn.executeSql(
                    `DELETE FROM ${AppTables.CHECKIN_DATA}`,
                    [],
                    () => {
                      txn.executeSql(
                        `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 (?, ?, ?, ?, ?, ?, '', ?, '', '', ?, ?)`,
                        [MerchandiserId, StoreId, VisitDate, Latitude, Longitude, In_Time, Out_Time, JcpType, d2],
                        () => {
                          console.log('CHECKIN INSERT SUCCESS');
                          resolve(true);
                        },
                        (e) => { console.log(e); resolve(false); }
                      );
                    },
                    (e) => { console.log(e); resolve(false); }
                  );
                },
                (e) => { console.log(e); resolve(false); }
              );
            },
            (e) => { console.log(e); resolve(false); }
          );

        });

      });

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


  async function checkIfAlreadyCheckdIn(storewisePjp, storeSearch) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let join, join2, q, q2;
        let execQ2 = true;
        let ShowStoreSearch = storeSearch ? storeSearch : false;


        if (storewisePjp) {
          join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_JourneyPlanStorewiseSup' `;
          q = `Select t1.* from Sup_JourneyPlanStorewiseSup t1 where t1.VisitDate='${d2}' and t1.UploadStatus='I'`

          join2 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_JourneyPlanStorewiseSup_Adhoc' `;
          q2 = `Select t1.* from Sup_JourneyPlanStorewiseSup_Adhoc t1 where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
        } else if (isNPNDScreen) {
          join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_NPNDStore' `;
          q = `Select t1.* from Sup_NPNDStore t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`

          join2 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_AdhocJourneyPlan' `;
          q2 = `Select t1.* from Sup_AdhocJourneyPlan t1 ${join2} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
        }
        else {
          join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_JourneyPlan' `;
          q = `Select t1.* from Sup_JourneyPlan t1 where t1.VisitDate='${d2}' and t1.UploadStatus='I'`

          join2 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_AdhocJourneyPlan' `;
          q2 = `Select t1.* from Sup_AdhocJourneyPlan t1 where t1.VisitDate='${d2}' and t1.UploadStatus='I'`

        }

        console.log("query-------1-21", q);
        console.log("query-------2", q2);

        txn.executeSql(q, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            console.log("query-------1--", txnres2.rows.length);
            // show from local
            resolve(true);
          }
          else if (execQ2) {
            console.log("query-------2--");
            txn.executeSql(q2, [], async function (txn2, txnres3) {
              if (txnres3.rows.length > 0) {
                // show from local
                resolve(true);
              }
              else {
                resolve(false);
              }
            }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });
          }
          else {
            resolve(false);
          }
        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });

      });

    }).then((val) => {
      return val;
    }).catch((err) => {
      return false;
    });
  }

  return (
    <TouchableOpacity
      style={customStyle.storel}
      key={props.index}
      onPress={() => { get_to_store_details(item) }}>
      <View style={customStyle.storel_card_outer}>
        <View style={customStyle.storel_card}>
          <View style={customStyle.storel_card_content}>
            <Text style={customStyle.storel_card_title}>{item?.StoreName}</Text>
          </View>
        </View>
        <View style={customStyle.storel_details}>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeBorder, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.StoreId + ':'}</Text>
              <Text style={customStyle.storel_codeText}>{item?.StoreId}</Text>
            </View>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.StoreType + ':'}</Text>
              <Text style={[customStyle.storel_codeText, { width: '50%' }]}>{item?.StoreType}</Text>
            </View>
          </View>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.StoreCode + ':'}</Text>
              <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item?.StoreCode}</Text>
            </View>
          </View>
          <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.Address + ':'}</Text>
              <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item?.Address}</Text>
            </View>
          </View>
          {/* {console.log("CheckInTime====", item?.CheckInTime)} */}
          {
            (item?.CheckInTime != null && item?.CheckInTime != '') &&
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
              <Fontisto style={customStyle.storel_codeIcon} color={PageTheme.$secondary_color_dark} name='clock' />
              <View style={[customStyle.storel_codeCon, customStyle.storel_codeBorder]}>
                <Text style={customStyle.storel_codeText}>{ST.CheckIn + ':'}</Text>

                <Text style={customStyle.storel_codeText}>{item?.CheckInTime}</Text>
              </View>
              {(item?.CheckOutTime != null && item?.CheckOutTime != '') &&
                <View style={[customStyle.storel_codeCon]}>
                  <Text style={customStyle.storel_codeText}>{ST.CheckOut + ':'}</Text>
                  <Text style={customStyle.storel_codeText}>{item?.CheckOutTime}</Text>
                </View>
              }
            </View>
          }
          {(item?.UploadStatus != null && item?.UploadStatus != '' && item?.UploadStatus != 'N') &&
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
              <View style={[customStyle.storel_usWrap]}>

                {item?.UploadStatus != null && (item?.UploadStatus == 'I' || item?.UploadStatus == 'L') &&
                  <TouchableOpacity style={[customStyle.storel_usCon, customStyle.storel_usConBtn, customStyle.storel_usConBtn2]} onPress={() => { AskForCancelCheckin(item) }}>
                    {item?.UploadStatus == 'L' ? <MaterialCommunityIcons name='exclamation' color='red' size={20} /> : <MaterialCommunityIcons name='login' color='#1f7dbc' size={20} />}
                    {item?.UploadStatus == 'L' ? <Text style={[customStyle.storel_usText, { color: 'red' }, customStyle.storel_usBtnText]}>{ST.NotWorking}</Text> : <Text style={[customStyle.storel_usText, { color: '#1f7dbc' }, customStyle.storel_usBtnText]}>{ST.CheckedIn}</Text>}

                    <View style={[customStyle.storel_usBtnRemoveIcon]}>
                      <FontAwesome name='trash' size={20} color={'red'} />
                    </View>
                  </TouchableOpacity>}
                {/* {item.UploadStatus!=null && item.UploadStatus=='I' &&
                        <View style={[customStyle.storel_usCon]}>
                          <MaterialCommunityIcons name='login' color='#1f7dbc' size={20}/>
                          <Text style={[customStyle.storel_usText,{color:'#1f7dbc'}]}>Checked In</Text>
                        </View>}  */}
                {item?.UploadStatus != null && item.UploadStatus == 'C' &&
                  <View style={[customStyle.storel_usCon]}>
                    <MaterialCommunityIcons name='logout' color='#ffd667' size={20} />
                    <Text style={[customStyle.storel_usText, { color: '#ffd667' }]}>{ST.CheckedOut}</Text>
                  </View>}
                {item?.UploadStatus != null && item?.UploadStatus == 'P' &&
                  <View style={[customStyle.storel_usCon]}>
                    <AntDesign name='cloudupload' color='red' size={20} />
                    <Text style={[customStyle.storel_usText, { color: 'red' }]}>{ST.PartiallyUploaded}</Text>
                  </View>}
                {item?.UploadStatus != null && item?.UploadStatus == 'D' &&
                  <View style={[customStyle.storel_usCon]}>
                    <Ionicons name='checkmark-sharp' color='green' size={20} />
                    <Text style={[customStyle.storel_usText, { color: 'green' }]}>{ST.DataUploaded}</Text>
                  </View>}
                {item?.UploadStatus != null && item?.UploadStatus == '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>}
                {/* {item.UploadStatus!=null && item.UploadStatus=='L' &&
                        <View style={[customStyle.storel_usCon]}>
                          <MaterialCommunityIcons name='exclamation' color='red' size={20}/>
                          <Text style={[customStyle.storel_usText,{color:'red'}]}>{ST.NotWorking}</Text>
                        </View> }   */}

                {console.log("allDone===", item)}

                {item.allDone == true && (item.UploadStatus == 'I') &&
                  <TouchableOpacity style={customStyle.storel_CheckOutBtn} onPress={() => { props.onCheckOut ? props.onCheckOut(item) : ''; }}>
                    <Text style={customStyle.storel_CheckOutBtnText}>{ST.CheckOut}</Text>
                  </TouchableOpacity>
                }
              </View>
            </View>}
          {
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10, customStyle.storel_usOp]}>
              <TouchableOpacity style={[customStyle.storel_usOpBtn]} onPress={() => { props.navigation.navigate('Album', { storeData: item, 'empData': props.EmpData, 'isAdhoc': props.isAdhocScreen, 'IsSearchedStore': IsSearchedStore }); }}>
                <Ionicons name='albums' color={PageTheme.$accent_color} size={20} />
                <Text style={customStyle.storel_usOpBtnText}>{'Album'}</Text>
              </TouchableOpacity>
            </View>
          }
        </View>
        {item?.GeoTag == 'Y' &&
          <TouchableOpacity activeOpacity={0.5} style={customStyle.storel_geotag_btn} onPress={() => { props.navigation.navigate('ShowMap', { storeData: item }) }} >
            <SvgXml width={30} height={30} xml={MapIcon} />
          </TouchableOpacity>
        }
        {item?.GeoTag == 'N' &&
          <TouchableOpacity activeOpacity={1} style={customStyle.storel_geotag_btn} onPress={() => { }} >
            <Entypo name='location-pin' size={30} color={'#b4b4b4'} />
          </TouchableOpacity>
        }
      </View>
    </TouchableOpacity>
  );
});

export default StoreItem;

