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, resizeImage, UpdateDistributorStatus, UpdateStoreStatus, UploadData, UploadData2, UploadFormData} 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-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 { uploadDBStatus, uploadStoreStatus } from '../constants/uploadData';
import { ConfirmSaveAlert } from '../components/alert';


function DBNonWorkingReasons(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 [rerenderdata, setrerenderdata]= useState(0);
    const [location, setLocation] = useState({});
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [isAnyStoreUploaded, setIsAnyStoreUploaded] = useState(false);
    const [showAlert, setShowAlert] = useState(false);

    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});

    useEffect(() => { 
      setLoaderTitle(ST.Loading+'...')
      getNonWorkingRsns();
      getData();

      const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
      return function cleanup() {
        return unsubscribe;
      };
    }, []);

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

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



    async function getNonWorkingRsns(){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');

      // set store type: adhoc or planned
      let params=props.route.params? props.route.params:{};
     


      let token=await get_item('loginToken');
      let loginInfo=await get_item('loginInfo');
      const loginDetails=JSON.parse(loginInfo);
      let storeData1=params.storeData || {};
      setStoreData(storeData1);

      // let q=`SELECT * FROM Non_Working_ReasonDistributor WHERE EntryAllow=1`;
      let q=`SELECT * FROM Sup_Non_Working_ReasonDistributor`;

      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(Etxn,txnerr){console.log(txnerr);});
      });   
    }

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

    async function checkIfAlreadyUploaded(){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      return new Promise((resolve,reject)=>{
          db.transaction(async function (txn) { 
  
            let q=`Select t1.* from Sup_MasterDistributor t1 where 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{            
                    resolve(false);      
                }
            },function(Etxn,txnerr){console.log(txnerr);resolve(false); });
  
          }); 
  
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        return false;
      });
    }

    async function _getCurrentLocation() {  
      
      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);  
              // let EntryAllow=(selectedReason.EntryAllow=='true' || selectedReason.EntryAllow==true || selectedReason.EntryAllow==1);
              let ImageAllow=(selectedReason.ImageAllow=='true' || selectedReason.ImageAllow==true || selectedReason.ImageAllow==1);
              // checkOutAfterLoc(loc);
              let UploadStatus=ImageAllow?'L':'U';
              
              if(ImageAllow){
                await uploadNonWRsnWithImage(loc,UploadStatus);
              } 
              else{
                await uploadNonWRsn(loc,UploadStatus);
              }  
          },
          (error) => {
              notify(ST.Cannotgetuserposition);
              setProcessing(false);
          },
          { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
        );
      }
      else{        
        notify(ST.Pleaseallowlocationpermission);
      }
    }

    // async function checkOutAfterLoc(loc){
    //   setLoaderTitle(ST.UploadingData+'...');
    //   let EntryAllow=(selectedReason.EntryAllow=='true' || selectedReason.EntryAllow==true || selectedReason.EntryAllow==1);
    //   let createJourneyPlan=(isAdhocScreen==true || isBeatPlan==true || isNonMerchan==true || isNonProg==true);
    //   // createJourneyPlan? await createJCP(loc,EntryAllow): (EntryAllow?await uploadNonWRsnWithImage(loc,'L'):await uploadNonWRsn(loc,'U',storeData));
    // }

    async function uploadNonWRsn(loc,UploadStatus='L'){
      console.log('uploadNonWRsn');
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');      
      let data={
        "DistributorId":storeData.StoreId,
        "VisitDate":d2,
        "Latitude":(loc.lat || ''),
        "Longitude":(loc.lng || ''),
        "ReasonId":reasonId,
        // "Remark":"",
        // "Appversion":AppVersion,
        "UploadStatus":UploadStatus,
        "UserId":(props.UserId || ''),
        "CheckInImage":Image1,
        "CheckoutImage":"",
      }

      const url=props.baseurl+getMethodName(METHODS.DISTRIBUTOR_COVERAGE);
      console.log(url,data);
      await UploadData(url,data)
      .then(async(res)=>{  
        console.log('uploadNonWRsn res:',res);
        if(res>0){
          let isUpdated=await InsertCoverageData(loc,true,UploadStatus);
          if(isUpdated==true){
            let isupdated=await update_Store_UploadStatus(UploadStatus=='L');
            if(isupdated==true){
              notify(ST.AllDataUploaded+'!','SHORT');
              setProcessing(false);
              goBack();
            }
            else{
              notify('Cannot update distributor status!','SHORT');
              setProcessing(false);
            }
          }
          else{
            setProcessing(false);
            notify(ST.Cannotuploaddata);
          }
        }
        else{
          setProcessing(false);
          notify(ST.Cannotuploaddata,'SHORT');
        }
      })
      .catch((err)=>{
        console.log(err);
      });
    }

    async function uploadNonWRsnWithImage(loc,UploadStatus='L'){
        console.log('uploadNonWRsnWithImage');
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');    

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

        data1.append('Foldername','DBCoverageImages');
        data1.append('Path', d2);
      }

      let data={
        "DistributorId":storeData.StoreId,
        "VisitDate":d2,
        "Latitude":(loc.lat || ''),
        "Longitude":(loc.lng || ''),
        "ReasonId":reasonId,
        // "Remark":"",
        // "Appversion":AppVersion,
        "UploadStatus":UploadStatus,
        "UserId":(props.UserId || ''),
        "CheckInImage":Image1,
        "CheckoutImage":"",
      }

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

      await UploadData2(url,data)
      .then(async(res)=>{         
        console.log('res:',res);
        if(parseInt(res)>0){
          let isUpdated=await InsertCoverageData(loc,true,UploadStatus);
          if(isUpdated==true){
            // Upload Image 
            if((selectedReason.ImageAllow=='true' || selectedReason.ImageAllow==true) && Image1Path!='' && Image1Path!=null){
              await UploadFormData(url1,data1)
              .then(async(res1)=>{         
                console.log('res1:',res1);   
                // let tbname=isBeatPlan==true?'JourneyPlan_RouteWise':(isAdhocScreen==true?'Adhoc_JourneyPlan':'Mapping_JourneyPlan');
                let tbname='Sup_MasterDistributor';
                
                // let isuploaded=await uploadStoreStatus(props,storeData,'U',tbname);
                let isuploaded=await uploadDBStatus(props,storeData,'U',tbname,loc)
                if(isuploaded==true){
                  notify(ST.DataUploaded+'!');
                  setProcessing(false);
                  goBack();
                }
                else{
                  notify(ST.Cannotuploaddata);
                  setProcessing(false);
                }
                
              })
              .catch((err)=>{
                console.log(err);
              });
            }
            else{
              // let tbname=isBeatPlan==true?'JourneyPlan_RouteWise':(isAdhocScreen==true?'Adhoc_JourneyPlan':'Mapping_JourneyPlan');
              // let isuploaded=await uploadStoreStatus(props,storeData,'U',tbname);
              let tbname='Sup_MasterDistributor';
              let isuploaded=await uploadDBStatus(props,storeData,'U',tbname,loc)
              if(isuploaded==true){
                notify(ST.DataUploaded+'!');
                setProcessing(false);
                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(loc,entryAllowed=true,UploadStatus){
      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 {StoreId,MID}=storeData;
          // let {lat,lng}=location;
          let {lat,lng}=loc;
          let q=`delete from ${AppTables.DISTRIBUTOR_CHECKIN} where DISTRIBUTOR_ID='${StoreId}' and VISIT_DATE='${d2}' `; 
          let JcpType='Sup_MasterDistributor';
              
          let values=` ('${StoreId}','${d2}','${lat}','${lng}','${now}','${Image1Path}','${now}','${Image1Path}','','${d2}')`; 
          let insert_q=` insert into ${AppTables.DISTRIBUTOR_CHECKIN}(DISTRIBUTOR_ID,VISIT_DATE,LATITUDE,LONGITUDE,CHECKIN_TIME,CHECKIN_IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REMARK,ADDED_DATE) values ${values}`;
          

          console.log("InsertCoverageData-------",insert_q)
          await txn.executeSql(q,[],async function (txn2, txnres2) {
            console.log('store coverage deleted');
            await txn.executeSql(insert_q,[],async function (txn2, txnres3) {
              console.log('InsertCoverageData done');      
              
              // let isupdated=await update_Store_UploadStatus(UploadStatus=='L');
              let isupdated=await update_Store_UploadStatus(entryAllowed);
              
              resolve(isupdated);
              
            },function(Etxn,txnerr){console.log(txnerr);resolve(false);});
          },function(Etxn,txnerr){console.log(txnerr);resolve(false);});

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

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


    async function update_Store_UploadStatus(entryAllowed=true){  
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) { 
          console.log("entryAllowed-----",entryAllowed,entryAllowed==false)
          // if(entryAllowed==false){   
            let EntryAllow=(selectedReason.EntryAllow=='true' || selectedReason.EntryAllow==true || selectedReason.EntryAllow==1);         
            if(!EntryAllow){            
              // if(!entryAllowed){            
            // let q=`UPDATE Sup_MasterDistributor SET UploadStatus='U' WHERE DistributorId='${storeData.StoreId}' `;
            let q=`UPDATE Sup_MasterDistributor SET UploadStatus='U'`;
            await txn.executeSql(q,[],async function (txn2, txnres1) {           
              console.log('store status updated')
              resolve(true);
            },function(Etxn,txnerr){console.log(txnerr);resolve(false);});
          }
          else{
            let datan={StoreId:storeData.StoreId,UploadStatus:'U',tbname:'Sup_MasterDistributor'} ;            
            const isUpdated=await UpdateDistributorStatus(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);
      }     
    }

    function onSaveCancel(){
      setShowAlert(false);
    }

    async function saveData(){
      setShowAlert(false);
      setLoaderTitle(ST.UploadingData+'...');
      _getCurrentLocation();   
    }

    function validate(){
      if(reasonId=='' || reasonId==null || reason=='' || reason==null){
        notify(ST.Pleaseselectreasonfornotworking,'SHORT');
        return false;
      }
      if( selectedReason.ImageAllow=='true' && (Image1Path=='' || Image1Path==null)){
        notify('Plesae click selfie in front of warehouse','SHORT');
        return false;
      }
      return true;
    }

    async function selectReason(item){
      if(isAnyStoreUploaded==true && (item.EntryAllow=='false' || item.EntryAllow==false)){
        notify('You cannot select this reason, you have already uploaded data for a distributor!');
        return;
      }

      setSelectedReason(item);
      setReason(item.Reason);
      setReasonId(item.ReasonId);
      setrerenderdata(!rerenderdata);
      
      if(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){
        
      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.ExtendedHeight;
          let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
          let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();
          let picture_clicked_time=moment(picture_clickedd).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: DB Not Working'+' | Date:'+picture_clicked_time;
               
          let picture_clicked_date1=moment(picture_clickedd).format('YYYYMMDD');
          let picture_clicked_time1=moment(picture_clickedd).format('HHmmss');
          let filename=storeData.StoreId+'_NonworkImg-'+picture_clicked_date1+'_'+picture_clicked_time1+'.jpg';
          
          setImage1(filename);
          
          let imagePath=`${RNFS.DocumentDirectoryPath}/${filename}`;
          RNFS.copyFile(imgurl, imagePath)
          .then(async(resn) => {
            // render data with clicked image
            let uri='file://'+imagePath;
            setImage1Path(uri);  

            // 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(ST.Errorimagefilewritefailed+'!!!');
              console.log(err.message, err.code);
          });
          // resize file 
          // let resize_res=await resizeImage(imgurl,imgWidth,imgHeight)
            
          
          // if(resize_res.success){
            // file resized now rename file
               
          // }
          // else{
          //   if(resize_res.error){
          //     notify("Error in image: ",resize_res.error);
          //   }else if (resize_res.imagenotfound){
          //       notify("Cannot find image!");
          //   }else{
          //       notify("Something went wrong while capturing image!");
          //   }
          // }                  
      }        
    }

    async function openCamera(){   
      setShowCamera(true);
      // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'front'})
    }
  
    function _OpenCaptureImage_Modal(){
      const isImageCap=(Image1Path=='' || Image1Path==null)?false:true;
      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={'DB Non Working'}/>        
        {_OpenCaptureImage_Modal()}
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <CustomCamera cameraType={'front'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Not Working'} enableGallerForScreen={props.CheckInCameraGallery} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper,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}>{'Distributor Id:'}</Text>
                      <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                    </View>                    
                    <View style={[customStyle.storel_codeCon]}>
                      <Text style={customStyle.storel_codeLbl}>{'Distributor Code:'}</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}>{'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}>{'Reason for not working in warehouse'}</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=='true' && 
                          <TouchableOpacity  style={customStyle.nonWlist_camera} 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)(DBNonWorkingReasons);