import React,{useState,useEffect} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles,GetPageTheme } from "../styles/Global";
import {Image,View,Text,ScrollView,TouchableOpacity,FlatList} from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {marktext1,marktext2, UpdateStoreStatus, UploadData, UploadData2, UploadFormData,fetchProjectConfig} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {AppVersion, db, URL_IMAGE, version} 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 NoDataComponent from '../components/NoDataComponent';
import {SvgXml} from 'react-native-svg';
import CustomModal from '../components/CustomModal';
import GradientButton from '../components/gradientButton';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
// import Geolocation from '@react-native-community/geolocation';
import Geolocation from 'react-native-geolocation-service';

import {_checkLocationPermission} from '../components/geolocation';
import CustomCamera from '../components/Camera';

import cameraImg from '../assets/performics/camera_front_image.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { AppTables } from '../constants/tableConstants';
import { uploadStoreStatus } from '../constants/uploadData';
import { ConfirmSaveAlert } from '../components/alert';


function StoreNonWorkingReasons(props) { 
  console.log('StoreNonWorkingReasons props:',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((props.isDataDownloaded?true:false));
    
    const [storeData, setStoreData] = useState({});
    const [nonWorkingRsns, setNonWorkingRsns] = useState([]);
    const [selectedReason, setSelectedReason] = useState({});
    const [reason, setReason] = useState('');
    const [reasonId, setReasonId] = useState('');
    const [Image1, setImage1] = useState('');
    const [Image1Path, setImage1Path] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [showAlert, setShowAlert] = useState(false);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [location, setLocation] = useState({});
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isNPNDScreen, setisNPNDScreen] = useState(false);
    const [isAnyStoreUploaded, setIsAnyStoreUploaded] = useState(false);

    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [EmpData, setEmpData] = useState([]);
    const [IsSearchedStore, setIsSearchedStore] = useState(false);
    const [designation, setDesignation] = useState('');


    useEffect(()=>{
      (async() => {
      let params=props.route.params? props.route.params:{};
      
      let loginInfo=await get_item('loginInfo');
      const loginDetails=JSON.parse(loginInfo);

     // const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
      const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
      console.log("storewisePjp_get>>:",storeSearch, storewisePjp);
    
      setDesignation(loginDetails?.Designation)
    })()
  },[])

    useEffect(() => { 
      setLoaderTitle(ST.Loading+'...')
      let params = props.route.params ? props.route.params : {};
      let storeData1 = params.storeData || {};
      let empData1 = params.empData || {};
      let IsSearchedStore1 = params.IsSearchedStore != null && params.IsSearchedStore == 1 ? true : false;
      
      let isAdhoc = params.isAdhoc || false;
      let isNPND=params.isNPND!=null?params.isNPND:false;
      setIsAdhocScreen(isAdhoc);
      setisNPNDScreen(isNPND)
      setIsSearchedStore(IsSearchedStore1);
      setStoreData(storeData1);
      setEmpData(empData1);
      
      getNonWorkingRsns(storeData1, isAdhoc);
      getData(storeData1, isAdhoc);

      const willFocusSubscription = props.navigation.addListener('focus', onBeforeRemove);

      return function cleanup() {
        willFocusSubscription(); // Call the unsubscribe function
      };
    }, []);

    useEffect(() => {
      const beforeRemoveListener = props.navigation.addListener('beforeRemove', onBeforeRemove);
      
      return function cleanup() {
        beforeRemoveListener(); // Call the unsubscribe function
      };
    }, [showCamera]);

    function onBeforeRemove(e) {
      if (showCamera == true) {
        e.preventDefault();
        setShowCamera(false);
      }
      // No else needed - if showCamera is false, the event will proceed normally
    }


    async function getNonWorkingRsns(storeData1,isAdhoc){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      let token=await get_item('loginToken');
      let loginInfo=await get_item('loginInfo');
      const loginDetails=JSON.parse(loginInfo);

      let q=`SELECT * FROM Sup_NonWorkingReason where ShowStore='1'`;

      await db.transaction(async function (txn) {  

        await txn.executeSql(q,[],async function (txn2, txnres2) {           
          if(txnres2.rows.length>0){ 
            // show from local
            var storeArr=[];
            for(var i=0;i<txnres2.rows.length;i++){
              let sdata=txnres2.rows.item(i);            
              storeArr.push(sdata); 
            
              if(i==(txnres2.rows.length-1)){
                console.log(storeArr);
                setNonWorkingRsns(storeArr);
                setProcessing(false);
              }
            }            
          }
          else{            
            setProcessing(false); 
            notify(ST.Nodatafound);
          }
        },function(txn2,txnerr){console.log(txnerr);});
      });   
    }

    async function getData(storeData1,isAdhoc){
      let isAny=await checkIfAlreadyUploaded();
      setIsAnyStoreUploaded(isAny);
    }

    async function checkIfAlreadyUploaded(){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      let loginInfo=await get_item('loginInfo');
     // const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
      const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);

      console.log("storewisePjpcheckIfAlreadyUploaded>>:", storewisePjp);
  
      return new Promise((resolve,reject)=>{
          db.transaction(async function (txn) { 
     
            let ShowStoreSearch= storeSearch?storeSearch:false;
            console.log("designation",designation)

            let tbname1='',tbname2='',checkTbl2=true;
            if (ShowStoreSearch && designation != 'Supervisor'){
              tbname1="Sup_JourneyPlan";
              checkTbl2=false;
            }
            else if(ShowStoreSearch ? (designation == "Supervisor" && storewisePjp==true):storewisePjp==true){
              tbname1="Sup_JourneyPlanStorewiseSup";
              tbname2="Sup_JourneyPlanStorewiseSup_Adhoc";
            }
            else{
              tbname1="Sup_JourneyPlan";
              tbname2="Sup_AdhocJourneyPlan";
            }

            let q=`Select t1.* from ${tbname1} t1 where t1.VisitDate='${d2}' and t1.UploadStatus!='N' and t1.UploadStatus!='' `
            
            let q2=`Select t1.* from ${tbname2} t1 where t1.VisitDate='${d2}' and t1.UploadStatus!='N' and t1.UploadStatus!='' `
            
            await txn.executeSql(q,[],async function (txn2, txnres2) {           
                if(txnres2.rows.length>0){ 
                  // show from local
                  resolve(true);      
                }
                else if(checkTbl2){            
                  await 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 _getCurrentLocation() {  
      const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
      console.log("storewisePjp_get>>:",storeSearch, storewisePjp);
      const hasPermission=await _checkLocationPermission();
      if(hasPermission==true)
      {    
        setProcessing(true);
        Geolocation.getCurrentPosition(
          async (position) => {
              let loc={lat:position.coords.latitude,lng:position.coords.longitude}; 
              setLocation(loc);  
              if(selectedReason.EntryAllow=='true' || selectedReason.EntryAllow==true || selectedReason.EntryAllow==1){
             (storewisePjp && (isAdhocScreen || isNPNDScreen))  ? await createJCP(loc,storewisePjp,storeSearch): await uploadNonWRsnWithImage(loc,'L',storewisePjp,storeSearch);
                //await uploadNonWRsnWithImage(loc,'L');
              } 
              else{
                await uploadNonWRsn(loc,'U',storewisePjp);
              }  
          },
          (error) => {
              notify(ST.Cannotgetuserposition);
              setProcessing(false);
          },
          { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
        );
      }
      else{        
        notify(ST.Pleaseallowlocationpermission);
      }
    }

    async function uploadNonWRsn(loc,UploadStatus='U',storewisePjp){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');      
      let data={
        "Mid":storeData.MID,
        "StoreId":storeData.StoreId,
        "VisitDate":d2,
        "Latitude":(loc.lat || ''),
        "Longitude":(loc.lng || ''),
        "ReasonId":reasonId,
        "Remark":"",
        "Appversion":AppVersion,
        "UploadStatus":UploadStatus,
        "UserName":(props.UserId || ''),
      }

      const url=props.baseurl+getMethodName(METHODS.COVERAGENOTALLOW_METHOD);
      console.log('url',url);
      console.log('data',data);
      await UploadData(url,data)
      .then(async(res)=>{  
        console.log('COVERAGENOTALLOW_METHOD',res);
        if(res=='1'){
          let isupdated=await update_Store_UploadStatus(false);
          if(isupdated==true){
            notify(ST.AllDataUploaded+'!','SHORT');
            setProcessing(false);
            console.log('')
            goBack();
          }
          else{
            notify(ST.DataUploadedButcouldnotupdatestorestatus,'SHORT');
            setProcessing(false);
          }
        }
        else{
          setProcessing(false);
          notify(ST.Cannotuploaddata,'SHORT');
        }
      })
      .catch((err)=>{
        console.log(err);
      });
    }

    async function uploadNonWRsnWithImage(loc,UploadStatus='L',storewisePjp,storeSearch){
      console.log('uploadNonWRsnWithImage called');
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');  
       let Deviation=(isAdhocScreen==true)?1:isNPNDScreen?2:0;  

      var data1 = new FormData();         
      if(Image1Path!='' && Image1Path!=null){
         
        data1.append('file', {
          uri: Image1Path,
          type: 'image/jpg',
          name: Image1,
        });

        let foldername=getFolderName(Image1);
        data1.append('Foldername',foldername);
        data1.append('Path', d2);
      }
      
      // data1.append('UserName', (props.UserId || ''));
     
      
      let data={
        "StoreId": storeData.StoreId,
        "VisitDate": d2, 
        "MerchandiserId": storeData.MerchandiserId, 
        "Latitude": (loc.lat || ''), 
        "Longitude" :(loc.lng || ''), 
        "ReasonId": reasonId, 
        "Remark":"",
        "CheckInImage":"", 
        "AppVersion":AppVersion, 
        "Checkout_Image": Image1, 
        "ChainId":  storeData.ChainId, 
        "StoreTypeId": storeData.StoreTypeId,
        "ChannelId": storeData.ChannelId, 
        "UploadStatus":UploadStatus, 
        "UserId":(props.UserId || ''), 
        "Deviation": Deviation
      }

      const url=props.baseurl+getMethodName(METHODS.GETCOVERAGE_METHOD);
      const url1=(props.imageUploadUrl || URL_IMAGE)+getMethodName(METHODS.UPLOADIMAGES_METHOD);
      console.log('url',url);
      console.log('data',data);
      console.log('url1',url1);

      let ShowStoreSearch= storeSearch?storeSearch:false;
      console.log("designation",designation)

      let tbname='';
      if (ShowStoreSearch && designation != 'Supervisor'){
        tbname="Sup_JourneyPlan";
      }
      else if(ShowStoreSearch ? (designation == "Supervisor" && storewisePjp==true):storewisePjp==true){
        tbname=isAdhocScreen==true?"Sup_JourneyPlanStorewiseSup_Adhoc":"Sup_JourneyPlanStorewiseSup";
        console.log('tbnamestore',tbname)
      }
      else{
        tbname=isAdhocScreen==true?"Sup_AdhocJourneyPlan":"Sup_JourneyPlan";
        console.log('tbnameteamlist',tbname)
      }

      await UploadData2(url,data)
      .then(async(res)=>{         
        console.log('res:',res);
        if(parseInt(res)>0){
          let isUpdated=await InsertCoverageData(UploadStatus,storewisePjp,storeSearch);
          console.log('is inserted:',isUpdated);
          if(isUpdated==true){
            // Upload Image 
            if((selectedReason.ImageAllow=='true' || selectedReason.ImageAllow=='1' || selectedReason.ImageAllow==true) && Image1Path!='' && Image1Path!=null){
              console.log('upload IMage');
              await UploadFormData(url1,data1)
              .then(async(res1)=>{         
                console.log('res1:',res1);   
                

                let isuploaded=await uploadStoreStatus(props,storeData,'U',tbname);
                
                if(isuploaded==true){
                  notify(ST.DataUploaded+'!');
                  setProcessing(false);
                  console.log('222222222')
                  props.navigation.goBack();
                }
                else
                {
                  console.log('IMage not uploaded');
                  notify(ST.Cannotuploaddata);
                 
                  setProcessing(false);
                }
                
              })
              .catch((err)=>{
                console.log(err);
              });
            }
            else{
              console.log('upload status:',isuploaded);
             
              let isuploaded=await uploadStoreStatus(props,storeData,'U',tbname);
              console.log('upload status:',isuploaded);
              if(isuploaded==true){
                notify(ST.DataUploaded+'!');
                setProcessing(false);
                console.log('11111111111')
                goBack();
              }
              else{
                notify(ST.Cannotuploaddata);
                setProcessing(false);
              }
              
            }
          }
          else{
            setProcessing(false);
            notify(ST.Cannotuploaddata);
          }
        }
        else{
          setProcessing(false);
          notify(ST.Cannotuploaddata);
        }
      })
      .catch((err)=>{
        console.log(err);setProcessing(false);notify(ST.Cannotuploaddata);
      });
    }

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

      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {  
          let ShowStoreSearch=storeSearch?storeSearch:false;
          console.log("designation",designation)
    
          let {StoreId,MID}=storeData;
          let {lat,lng}=location;
          let q=`delete from ${AppTables.COVERAGE_DATA} where STORE_ID='${StoreId}' and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' `; 
          
          let JcpType="";
          if (ShowStoreSearch && designation != 'Supervisor'){
            JcpType="Sup_JourneyPlan";
          }
          else if(ShowStoreSearch ? (designation == "Supervisor" && storewisePjp==true):storewisePjp==true){
            JcpType=isAdhocScreen==true?"Sup_JourneyPlanStorewiseSup_Adhoc":"Sup_JourneyPlanStorewiseSup";
          }
          else{
            JcpType=isAdhocScreen==true?"Sup_AdhocJourneyPlan":"Sup_JourneyPlan";
          }

          let values=` ('${storeData.MerchandiserId}','${StoreId}','${d2}','${lat}','${lng}','${Image1}','${now}','${Image1Path}','${reasonId}','${reason}','','','${MID}','${JcpType}','${d2}')`; 
          let insert_q=` insert into ${AppTables.COVERAGE_DATA}(EMP_ID,STORE_ID,VISIT_DATE ,LATITUDE,LONGITUDE,IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REASON_ID,REASON,REMARK,STORE_FLAG,MID,JCP_TYPE,ADDED_DATE) values ${values}`;

          await txn.executeSql(q,[],async function (txn2, txnres2) {
            console.log('store coverage deleted');
            await txn.executeSql(insert_q,[],async function (txn2, txnres3) {
              console.log('InsertCoverageData done');         
              
            },function(txn2,txnerr){console.log(txnerr);});
          },function(txn2,txnerr){console.log(txnerr);});


          let values2=` ('${storeData.MerchandiserId}','${StoreId}','${d2}','${lat}','${lng}','${now}','${Image1Path}','${now}','${Image1Path}','','${JcpType}','${d2}')`; 
          let insert_q2=` INSERT INTO ${AppTables.CHECKIN_DATA}(EMP_ID,STORE_ID,VISIT_DATE,LATITUDE,LONGITUDE,CHECKIN_TIME,CHECKIN_IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REMARK,JCP_TYPE,ADDED_DATE) values ${values2}`;
          await txn.executeSql(`delete from ${AppTables.CHECKIN_DATA} where STORE_ID='${StoreId}' and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}'`,[],async function (txn2, txnres2) {
            console.log('store checkin deleted');
            await txn.executeSql(insert_q2,[],async function (txn2, txnres3) {

              console.log('store checkin added as leave'); 
              let issup=await update_Store_UploadStatus(true,storewisePjp,storeSearch);  
              resolve(issup);

            },function(txn2,txnerr){console.log(txnerr);resolve(false);});
          },function(txn2,txnerr){console.log(txnerr);resolve(false);});
          
        }); 
      }).then((val)=>{
        console.log('on InsertCoverageData complete:',val);
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      });
      
       
      
      
    }

    async function createJCP(loc,storewisePjp,storeSearch){
      console.log('create JCP called');
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');      
      let data={"UserId":(props.UserId || ''),"JcpType":1,"StoreId":storeData.StoreId,"VisitDate":d2}
      const url=props.baseurl+getMethodName(METHODS.CREATEJP_METHOD);
      console.log(url,data);
      await UploadData(url,data)
      .then(async(res)=>{  
        console.log(res);
        if(res!=null && res!='' && res!='0' && parseInt(res)>0){          
          updateMID(res,loc,storewisePjp,storeSearch);// update mid in db
        }
        else{
          setProcessing(false);notify(ST.OopsSomethingwentwrongcannotcreateJCP,'SHORT');
        }
        
      })
      .catch((err)=>{
        setProcessing(false);console.log(err);
      });

    }

    const goBack=()=>{
      props.navigation.goBack();
    }

    async function updateMID(MID=0,loc,storewisePjp,storeSearch){
      console.log('updateMID called',MID);
      try{
        await db.transaction(async function (txn) {   
          let q=`UPDATE  Sup_AdhocJourneyPlan 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);
            uploadNonWRsnWithImage(loc,'L',storewisePjp,storeSearch);

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

    async function update_Store_UploadStatus(entryAllowed=true,storewisePjp,storeSearch){  
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) { 
          let ShowStoreSearch=storeSearch?storeSearch:false;
          console.log("designation",designation)

          if(entryAllowed==false){  
            let tbname1='',tbname2='',checkTbl2=true;
            if (ShowStoreSearch && designation != 'Supervisor'){
              tbname1="Sup_JourneyPlan";
              checkTbl2=false;
            }
            else if(ShowStoreSearch ? (designation == "Supervisor" && storewisePjp==true):storewisePjp==true){
              tbname1="Sup_JourneyPlanStorewiseSup";
              tbname2="Sup_JourneyPlanStorewiseSup_Adhoc";
            }
            else{
              tbname1="Sup_JourneyPlan";
              tbname2="Sup_AdhocJourneyPlan";
            }
          
            let q=`UPDATE ${tbname1} SET UploadStatus='U' `;
            await txn.executeSql(q,[],async function (txn2, txnres1) {           
              console.log('store status updated')

              if(checkTbl2){
                let q2=`UPDATE ${tbname2} SET UploadStatus='U' `;
                await txn.executeSql(q2,[],async function (txn2, txnres2) {           
                  console.log('store status updated')
                  resolve(true);
                },function(txn2,txnerr){console.log(txnerr);resolve(false);});
              }
              else{
                resolve(true);
              }
            },function(txn2,txnerr){console.log(txnerr);resolve(false);});
          }
          else{
            let tbname='';
            if (ShowStoreSearch && designation != 'Supervisor'){
              tbname="Sup_JourneyPlan";
            }
            else if(ShowStoreSearch ? (designation == "Supervisor" && storewisePjp==true):storewisePjp==true){
              tbname=isAdhocScreen==true?"Sup_JourneyPlanStorewiseSup_Adhoc":"Sup_JourneyPlanStorewiseSup";
              console.log('tbnamestore',tbname)
            }
            else{
              tbname=isAdhocScreen==true?"Sup_AdhocJourneyPlan":"Sup_JourneyPlan";
              console.log('tbnameteamlist',tbname)
            }


            let datan={StoreId:storeData.StoreId,UploadStatus:'L',tbname:tbname} ;            
            const isUpdated=await UpdateStoreStatus(props,datan);
            resolve(isUpdated);
            
          }
        }); 
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      })
    }

    async function submitNonWorkingRsns(){
      let isvalid=await validate();
      if(isvalid){
        setShowAlert(true);
      }   
    }

    async function validate(){
      if(reasonId=='' || reasonId==null || reason=='' || reason==null){
        notify(ST.Pleaseselectreasonfornotworking,'SHORT');
        return false;
      }
      if( (selectedReason.ImageAllow=='true' || selectedReason.ImageAllow=='1' || selectedReason.ImageAllow==true) && (Image1Path=='' || Image1Path==null)){
        notify(ST.Pleaseclickselfieinfrontofstore,'SHORT');
        return false;
      }
      return true;
    }

    async function selectReason(item){
      if(isAnyStoreUploaded==true && (item.EntryAllow=='false' || item.EntryAllow==false)){
        notify(ST.Youcannotselectthisreasonasthereisalreadyastore);
        return;
      }

      setSelectedReason(item);
      setReason(item.Reason);
      setReasonId(item.ReasonId);
      setrerenderdata(!rerenderdata);
      
      if(item.ImageAllow=='1' || item.ImageAllow=='true' || item.ImageAllow==true){
        if((Image1Path!='' && Image1Path!=null)){
          setShowImageSaveOp(false);
        }
        else{
          setShowImageSaveOp(true);
        }
        openImageModal();
      }
    }

    function openImageModal(){
      setShowModal(true);    
    }

    function closeImageModal(){
      setShowModal(false);
    }

    function cancelImage(){
      setImage1('');
      setImage1Path('');
      closeImageModal();
    }

    async function getImage(imgdata){

      console.log('imgdata',imgdata);
        
      if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
        notify(ST.Cameraunavailable);
      }
      else if(typeof imgdata =='object' && imgdata.uri!=null){
        const img=imgdata;
          const imgurl=img.uri, imgWidth=img.width, imgHeight=img.height;
         
          
          let picture_clicked_time=new Date();
          picture_clicked_time=moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')
          
          
          const mark_text1=picture_clicked_time;
          const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Not Working'+' | Date:'+picture_clicked_time;
         console.log('mark_text1',mark_text1,imgurl);
          await marktext1(mark_text1,imgurl)
          .then((res)=>{
            console.log("res.success",res.success)
              if(res.success){
                  let uri=res.uri;
                  marktext2(mark_text2,uri,imgWidth,imgHeight)
                  .then((res)=>{
                      if(res.success){
                          let picture_clickedd=new Date();
                          let picture_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                          let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                          let filename=storeData.StoreId+'_NonworkImg-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                          
                          setImage1(filename);
                          // renamefile
                          let imagePath=`${RNFS.DocumentDirectoryPath}/${filename}`;
                          RNFS.copyFile(res.uri, imagePath)
                          .then(resn => {
                              let uri='file://'+imagePath;
                              console.log('image marker',uri);
                              setImage1Path(uri);  
                          })
                          .catch(err => {
                              console.log(ST.Errorimagefilewritefailed+'!!!');
                              console.log(err.message, err.code);
                          });                           
                                   
                      }
                      else{
                          if(res.imagenotfound){
                              notify(ST.Pleasecaptureaimage);
                          }
                          else{
                              notify(res.error);
                          }
                      }
                  });
              }
              else{
                  if(res.imagenotfound){
                      notify(ST.Pleasecaptureaimage);
                  }
                  else{
                      notify(res.error);
                  }
              }
          }).catch((err)=>{
            console.log("error--",err)
          });            
      }        
    }

    async function openCamera(){   
      setShowCamera(true);
      setShowModal(false);
      // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'front'})
    }

    function onSaveCancel(){
      setShowAlert(false);
    }

    async function saveData(){
      setShowAlert(false);
      setLoaderTitle(ST.UploadingData+'...');
      _getCurrentLocation();   
    }
  
    function _OpenCaptureImage_Modal(){
      const isImageCap=(Image1Path=='' || Image1Path==null)?false:true;

      console.log('isImageCap',isImageCap);
      return (
        <CustomModal 
          style={customStyle.nonWCapImgModal}
          title={ST.NonWorkingReason}
          message={ST.Pleaseclickselfieinfrontofstore}
          titleStyle={customStyle.nonWCapImgModal_title}
          messageStyle={customStyle.nonWCapImgModal_subtitle}
          showModal={showModal}
        >
          {
            !isImageCap && 
            <View style={customStyle.nonWCapImgModalCon}>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Camera} onPress={()=>{openCamera()}}>
                <SvgXml width={100} height={100} xml={CameraImg2}/>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{closeImageModal()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
              </TouchableOpacity>
            </View>
          }
          { 
          isImageCap && 
          <View style={customStyle.nonWCapImgModalCon}>
            <View style={customStyle.nonWCapImgModal_ImgWrap}>
              <Image  style={[customStyle.nonWCapImgModal_Img,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:Image1Path}} />
            </View>
            <TouchableOpacity style={customStyle.nonWCapImgModal_CameraSmall} onPress={()=>{openCamera()}}>
              <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color}/>
            </TouchableOpacity>
            { showImageSaveOp &&
            <View style={customStyle.nonWCapImgModal_btng}>              
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{cancelImage()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Save_btn} onPress={()=>{closeImageModal()}}>
                <Text style={customStyle.nonWCapImgModal_Save_btnText}>{ST.Save}</Text>
              </TouchableOpacity>
            </View>}
            {!showImageSaveOp &&
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{closeImageModal()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Close}</Text>
              </TouchableOpacity>
            }
            
          </View>

          }
        </CustomModal>
      )
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={ST.NotWorking}/>        
        {_OpenCaptureImage_Modal()}
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <CustomCamera cameraType={'front'} onImageCaptured={(imgData)=>{setShowModal(true);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,customStyle.pageContentWrapper_bgLight]}>
          { !props.isDataDownloaded && <NoDataComponent {...props}/>}
          {props.isDataDownloaded && Object.keys(storeData).length>0 &&
            <View style={customStyle.storeD_Main}>
              <View style={[customStyle.storeD_storelMain]}>
              <View style={[customStyle.storel,customStyle.storeInfo_wrap]}>

              <View style={customStyle.storel_card_outer}> 
                <View style={customStyle.storel_card}>
                  <View style={customStyle.storel_card_content}>
                    <Text style={customStyle.storel_card_title}>{storeData.StoreName}</Text>
                  </View>                  
                </View>
                <View style={customStyle.storel_details}>
                  <View style={customStyle.storel_code}>
                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
                      <Text style={customStyle.storel_codeLbl}>{ST.StoreId+':'}</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                    </View>                    
                    <View style={[customStyle.storel_codeCon]}>
                      <Text style={customStyle.storel_codeLbl}>{ST.StoreCode+':'}</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreCode}</Text>
                    </View>
                  </View>
                  <View style={customStyle.storel_code}>                    
                    <View style={[customStyle.storel_codeCon]}>
                      <Text style={customStyle.storel_codeLbl}>{ST.Address+':'}</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.Address}</Text>
                    </View>
                  </View>                                 
                </View>                
              </View> 

              </View>
              </View>

              <View style={customStyle.nonWorking_con}>
                <View style={customStyle.nonWorking_form}> 
                  <Text style={customStyle.nonWform_hd}>{ST.Reasonfornotworkinginstore}</Text>                          
                  <FlatList 
                  contentContainerStyle={customStyle.storeD_scroll}
                  extraData={rerenderdata}
                  style={customStyle.storeD_scrollCon}
                  data={nonWorkingRsns}
                  renderItem={({item,index})=>{

                    const nWselStyle=reasonId==item.ReasonId?customStyle.nWselStyle:{};
                    const nWselStyleText=reasonId==item.ReasonId?customStyle.nWselStyleText:{};
                    const CapImageShow=(Image1Path!='' && Image1Path!=null) && reasonId==item.ReasonId?true:false;
                    let isDisabled=(isAnyStoreUploaded==true && (item.EntryAllow=='false' || item.EntryAllow==false));
                    return (
                      <TouchableOpacity key={index} style={[customStyle.nonWlist,nWselStyle,isDisabled==true?{backgroundColor:'#cdcdcd'}:{}]} disabled={isDisabled} onPress={()=>{selectReason(item)}}>
                        <Text style={[customStyle.nonWlist_Text,nWselStyleText]}>{item.Reason}</Text>
                        { (item.ImageAllow=='1' || item.ImageAllow=='true' || item.ImageAllow==true) && 
                            <TouchableOpacity  style={customStyle.nonWlist_camera} disabled={isDisabled} onPress={()=>{selectReason(item)}}>
                                {!CapImageShow && <SvgXml width={30} height={30} xml={CameraImg2} />}
                                {CapImageShow && <SvgXml width={30} height={30} xml={CameraImg3} />}
                            </TouchableOpacity>
                            }
                      </TouchableOpacity>
                    );
                  }}
                  />
                </View>                
              </View>
              
              <View style={customStyle.nonW_btnWrap}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{submitNonWorkingRsns();}}/> 
              </View>    

            </View>   
            
          }          
         </View>      
       </LinearGradient>       
        
      </Container>   
    ); 
  }
  


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