import React,{useState,useEffect, useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, KeyboardAvoidingView, BackHandler, AppState, Keyboard} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2, validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath,ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, MaterialCommunityIcons} from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import cameraImg from '../assets/performics/camera_front_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { ExitScreenAlert } from '../components/alert';
import CustomCamera from '../components/Camera';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg4 from '../assets/performics/camera_asterisk.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';

function Sampling_Stock(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(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);
    
    const [catImages, setCatImages] = useState([]);
    const [SKUStockData, setSKUStockData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [disableEdit, setDisableEdit] = useState(false);
    const [SaleFlag, setSaleFlag] = useState(false);
    const [SamplingData, setSamplingData] = useState({});

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(SKUStockData);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');
    const catImagesRef=React.useRef(catImages);

    const inputRefs = useRef({});

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let SamplingData1=params.SamplingData || {};
        
        let isAdhoc=params.isAdhoc || false;
        let SamplingSaleFlag=params.SamplingSaleFlag || false;

        setSaleFlag(SamplingSaleFlag)
        setSamplingData(SamplingData1);
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName
        getData(storeData1,menu1,SamplingData1,SamplingSaleFlag);

        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
        return function cleanup() {
            AppStateSubscription.remove();   
            return unsubscribe;
        };
       
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        if(nextAppState =='background' && hasUnsavedChangesRef.current==true){
           let newData = {
               storeBGData:WindowDataRef.current,
               menuName:ScreenNameRef.current,
               StoreId1:StoreIdRef.current,
               BgCatImage:catImagesRef.current,
               visiteDate:d2
           }
           let WindowsStr= JSON.stringify(newData)
           await set_item('storeData',WindowsStr); 
       }
     }

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
        // AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
        // AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
    }, [hasUnsavedChanges]);   
    
    // useEffect(() => {
    //     AppState.removeEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
    //     AppState.addEventListener('change',(pro)=>{ _handleAppStateChange(SKUStockData,pro)});
    // }, [SKUStockData]); 

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }
    
    function BgUnsavedChanges(val){
        hasUnsavedChangesRef.current=val
        setHasUnsavedChanges(val);
    }

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

    function BgCatImages(val){
        catImagesRef.current=val
        setCatImages(val);
    }
    
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
              {
                text: "Cancel",
                onPress: () => {},
                style: "cancel"
              },
              { text: "OK", onPress: async () => {
                // setHasUnsavedChanges(false);
                BgUnsavedChanges(false)
                await clear_item('storeData')
                props.navigation.dispatch(e.data.action);} }
            ]
          );
    }

    async function getData(storeData1,menu1,SamplingData1,SamplingSaleFlag){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId,StoreClassId,StoreCategoryId}=storeData1;
          let {SamplingDefinitionId}=SamplingData1;
          let allCats=[];

          let AllKPIFields=await getKPIFields(menu1);
          setKPIFields(AllKPIFields);

          // set switch camera flag as defined in mapping menu flag (if exists)
          let SwitchingCameraI=AllKPIFields.findIndex(i=>i.KPIFieldName=='SwitchingCamera');
          let SwitchingCameraObj=SwitchingCameraI>=0?AllKPIFields[SwitchingCameraI]:{};
          let SwitchingCamera=SwitchingCameraI>=0?SwitchingCameraObj['KPIFieldEnable']:false;
          setShowSwitchCamera(SwitchingCamera);
        
          await db.transaction(async function (txn) {        
            
            
            let q=`SELECT DISTINCT c.SamplingStockValue as SamplingStockId,c.ProductName as ProductName,'' as MSL, c.SamplingStockDefinitionId, c.SamplingDefinitionId, c.SamplingStockTable, c.SamplingStockField, c.SamplingStockMBQ from Master_SamplingStockDefinition c where c.SamplingDefinitionId='${SamplingDefinitionId}' `;           
            
            let q2="";
            if( SamplingSaleFlag==true){
                // SELECT c.STOCK, c.SAMPLING_STOCK_VALUE as SamplingStockId, c.PRODUCT_NAME as ProductName,'' as MSL, c.SAMPLING_STOCK_DEFINITION_ID as SamplingStockDefinitionId, c.SAMPLING_DEFINITION_ID as SamplingDefinitionId, c.SAMPLING_STOCK_TABLE as SamplingStockTable, c.SAMPLING_STOCK_FIELD as SamplingStockField, c.SAMPLING_STOCK_MBQ as SamplingStockMBQ from SAMPLING_STOCK_DATA c LEFT OUTER JOIN SAMPLING_SALE_DATA s on c.SAMPLING_DEFINITION_ID=s.SAMPLING_DEFINITION_ID   where  c.STORE_ID='1' AND c.VISIT_DATE='08/21/2023'
                
                // let join=` INNER JOIN ${AppTables.SAMPLING_SALE_DATA} s on c.SAMPLING_DEFINITION_ID=s.SAMPLING_DEFINITION_ID  `;
                // q2=`SELECT c.STOCK, c.SAMPLING_STOCK_VALUE as SamplingStockId, c.PRODUCT_NAME as ProductName,'' as MSL, c.SAMPLING_STOCK_DEFINITION_ID as SamplingStockDefinitionId, c.SAMPLING_DEFINITION_ID as SamplingDefinitionId, c.SAMPLING_STOCK_TABLE as SamplingStockTable, c.SAMPLING_STOCK_FIELD as SamplingStockField, c.SAMPLING_STOCK_MBQ as SamplingStockMBQ, s.SALE from ${AppTables.SAMPLING_STOCK_DATA } c ${join} where c.SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' AND c.STORE_ID='${StoreId}' AND c.VISIT_DATE='${d2}' `; 
                
                let join=` LEFT OUTER JOIN ${AppTables.SAMPLING_SALE_DATA} s on c.SAMPLING_STOCK_DEFINITION_ID=s.SAMPLING_STOCK_DEFINITION_ID AND c.SAMPLING_DEFINITION_ID=s.SAMPLING_DEFINITION_ID `;
                q2=`SELECT c.STOCK, c.SAMPLING_STOCK_VALUE as SamplingStockId, c.PRODUCT_NAME as ProductName,'' as MSL, c.SAMPLING_STOCK_DEFINITION_ID as SamplingStockDefinitionId, c.SAMPLING_DEFINITION_ID as SamplingDefinitionId, c.SAMPLING_STOCK_TABLE as SamplingStockTable, c.SAMPLING_STOCK_FIELD as SamplingStockField, c.SAMPLING_STOCK_MBQ as SamplingStockMBQ, s.SALE from ${AppTables.SAMPLING_STOCK_DATA } c ${join} where c.SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' AND c.STORE_ID='${StoreId}' AND c.VISIT_DATE='${d2}' `;           
            }else{

                q2=`SELECT c.SAMPLING_STOCK_VALUE as SamplingStockId, c.PRODUCT_NAME as ProductName,'' as MSL, c.SAMPLING_STOCK_DEFINITION_ID as SamplingStockDefinitionId, c.SAMPLING_DEFINITION_ID as SamplingDefinitionId, c.SAMPLING_STOCK_TABLE as SamplingStockTable, c.SAMPLING_STOCK_FIELD as SamplingStockField, c.SAMPLING_STOCK_MBQ as SamplingStockMBQ , STOCK from ${AppTables.SAMPLING_STOCK_DATA} c where c.SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' AND c.STORE_ID='${StoreId}' AND c.VISIT_DATE='${d2}' `;          
            }

            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                if(txnres2.rows.length>0){
                    let arr=[],storeBGData1=[],bgStoreJson={};
                   
                    for(var i=0;i<txnres2.rows.length;i++){
                        let data =txnres2.rows.item(i);
                        inputRefs.current['input1_'+data.SamplingStockId+'_'+data.SamplingStockDefinitionId]='';
                        arr.push(data);
                        if(i==txnres2.rows.length-1){
                            setBrandData(arr);
                        }                                
                    }
                    
                }
            },function (txnE,txnerr) { console.log(txnerr); },);
            
            
            await txn.executeSql(q2,[],async function (txn2, txnres) { 
                console.log("data.STOCK----",txnres.rows.length,q2)
                if(txnres.rows.length>0){
                    let arr=[],storeBGData1=[],bgStoreJson={};
                    let windData = await get_item('storeData')
                    if(windData!=null && windData!=''){
                        let StoreJson = JSON.parse(windData)
                        let { storeBGData,menuName,StoreId1,BgCatImage,visiteDate }= StoreJson
                        // if( menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                        //     storeBGData1=storeBGData;
                        //     bgStoreJson=StoreJson
                        //     // setSKUStockData(storeBGData);
                        //     if(BgCatImage.length>0){
                        //         // BgCatImages(BgCatImage)
                        //     }
                        //     if(storeBGData.length>0){
                        //         // BgWindowData(storeBGData);
                        //     }
                        //     BgUnsavedChanges(true)
                            
                        // }
                    }
                    
                    for(var i=0;i<txnres.rows.length;i++){
                        let data =txnres.rows.item(i);
                        console.log("sampling stock data:",data);
                        arr.push(data);
                        inputRefs.current['input1_'+data.SamplingStockId+'_'+data.SamplingStockDefinitionId]='';
                        let defData={'SamplingStockId':data.SamplingStockId,'SamplingStockDefinitionId':data.SamplingStockDefinitionId,'Stock':data.STOCK, 'Sale':(data.SALE!="null" && data.SALE!=null ? data.SALE:"")};
                        // console.log("data.STOCK----1",defData)
                        allCats.push(defData);
                        if(i==txnres.rows.length-1){
                            setSKUStockData(allCats);
                            // setBrandData(arr);
                        }
                    }
                }
                else{
                    // await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    //     if(txnres2.rows.length>0){
                    //         let arr=[],storeBGData1=[],bgStoreJson={};
                           
                    //         for(var i=0;i<txnres2.rows.length;i++){
                    //             let data =txnres2.rows.item(i);
                    //             // console.log("data.STOCK----2",data)
                    //             inputRefs.current['input1_'+data.SamplingStockId+'_'+data.SamplingStockDefinitionId]='';
                    //             arr.push(data);
                    //             if(i==txnres2.rows.length-1){
                    //                 setBrandData(arr);
                    //             }                                
                    //         }
                            
                    //     }
                    // },function (txnE,txnerr) { console.log(txnerr); },);
                }
            },function (txnE,txnerr) { console.log(txnerr); },);
            setProcessing(false);
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

   

    async function focusToNext(cat,type='1'){

        let activeKey='';
        let arr=Object.keys(inputRefs.current);
        if(type=="1"){
            activeKey='input1_'+cat.SamplingStockId+'_'+cat.SamplingStockDefinitionId;
        }

        let activeIndex=arr.indexOf(activeKey);
        if(activeIndex<arr.length-1){
            let nextKey = arr[++activeIndex] 
            let nextRef= inputRefs.current[nextKey];
            nextRef.focus();    
        }
        else{
            return
        }
    }

    async function openCamera(option){ 
        setGetImageProps({'option':option}); 
        console.log('openCamera');
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'});
        setShowCamera(true);
    }

    async function submitOpeningStock(){
        let isvalid=await validate();
        if(isvalid){
            Keyboard.dismiss();
            setShowAlert(true);
        }
    }

    async function saveData(){
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            let {SamplingDefinitionId}=SamplingData;
            await db.transaction(async function (txn) { 

                //  remove old data
                let q=`DELETE FROM ${SaleFlag==true? AppTables.SAMPLING_SALE_DATA:AppTables.SAMPLING_STOCK_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' `;
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    console.log('stock data deleted');
                },function (txnE,txnerr) { console.log(txnerr); },);
               
                
                var values='',add_Stock='';
                for(var i=0;i<brandData.length;i++){
                    let catIndex=i;
                    let item=brandData[catIndex];
                    let skuData=SKUStockData.find(i=>i.SamplingStockId==item.SamplingStockId && i.SamplingStockDefinitionId==item.SamplingStockDefinitionId) || {};
                    values+=values!=''?' , ':'';
                    //   SaleFlag==true? AppTables.SAMPLING_STOCK_DATA:AppTables.SAMPLING_SALE_DATA
                    if(SaleFlag==true){
                        values+=` ('${StoreId}','${d2}','${item.SamplingStockDefinitionId}','${SamplingDefinitionId}','${item.SamplingStockTable}', '${item.SamplingStockField}','${item.SamplingStockId}', '${item.SamplingStockMBQ}','${item.ProductName}','${skuData.Sale || '0'}','${d2}') `;
                    }else{
                        values+=` ('${StoreId}','${d2}','${item.SamplingStockDefinitionId}','${SamplingDefinitionId}','${item.SamplingStockTable}', '${item.SamplingStockField}','${item.SamplingStockId}', '${item.SamplingStockMBQ}','${item.ProductName}','${skuData.Stock}','${d2}') `; 
                    }
                }

                if(SaleFlag==true){
                    add_Stock=`INSERT INTO ${AppTables.SAMPLING_SALE_DATA} (STORE_ID,VISIT_DATE, SAMPLING_STOCK_DEFINITION_ID, SAMPLING_DEFINITION_ID, SAMPLING_STOCK_TABLE, SAMPLING_STOCK_FIELD, SAMPLING_STOCK_VALUE, SAMPLING_STOCK_MBQ, PRODUCT_NAME, SALE, ADDED_DATE) VALUES ${values} `;
                }else{
                    add_Stock=`INSERT INTO ${AppTables.SAMPLING_STOCK_DATA} (STORE_ID,VISIT_DATE, SAMPLING_STOCK_DEFINITION_ID, SAMPLING_DEFINITION_ID, SAMPLING_STOCK_TABLE, SAMPLING_STOCK_FIELD, SAMPLING_STOCK_VALUE, SAMPLING_STOCK_MBQ, PRODUCT_NAME, STOCK, ADDED_DATE) VALUES ${values} `;
                }

                await txn.executeSql(add_Stock,[],async function (txn2, txnres) { 
                    console.log('stock added');
                    notify('Stock updated successfully');
                    setProcessing(false);
                    // clear store data in local storage to avoiding re-set data for the store  
                    clear_item('storeData')
                    props.navigation.goBack();
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock') },);
             
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }


    // async function onChangeValidate(cat,CategoryIndex,skus,ProductIndex){
    //     let isValid=true;
        
    //     let skuData=SKUStockData.find(ci=>ci.CategoryId==item.CategoryId && ci.ProductId==skuItem.ProductId ) || {};
    //     if(skuData.ExpiryStock!=null  && skuData.ExpiryStock!="" && skuData.Stock!=null && skuData.Stock!="" ){
    //         let isExpStockIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ExpiredStock')
    //         let isExpStockPIObj=isExpStockIndex>=0?KPIFields[isExpStockIndex]:{};
    //         let isExpStockEnable=isExpStockIndex>=0?isExpStockPIObj['KPIFieldEnable']:true;

                                        
    //         if(isExpStockEnable==true &&(parseInt(skuData.ExpiryStock)>parseInt(skuData.Stock))){
    //             notify('Expiry Stock value should be less than or equal to Stock for '+skuItem.ProductName,'SHORT');
    //             isValid=false;
    //         }else{

    //         }
    //     }
        
    // }

    async function validate(){
        let isValid=true;
        let dataCheckKey=SaleFlag==true ? 'Sale' :'Stock';
        let isAnyFilled=false;
        
        let isSaleDependIndex=KPIFields.findIndex(i=>i.KPIFieldName=='SaleDependOnStock')
        let isSaleDependPIObj=isSaleDependIndex>=0?KPIFields[isSaleDependIndex]:{};
        let isSaleDependEnable=isSaleDependIndex>=0?isSaleDependPIObj['KPIFieldEnable']:true;

        
        await Promise.all(
            brandData.map(async (item,index) => {
                
                if((isValid  && !SaleFlag) || SaleFlag){
                    let skuData=SKUStockData.find(i=>i.SamplingStockId==item.SamplingStockId && i.SamplingStockDefinitionId==item.SamplingStockDefinitionId) || {};
                  
                    if(skuData[dataCheckKey]!==0 && ( skuData[dataCheckKey]==null || skuData[dataCheckKey]=='')){
                       
                        if(!SaleFlag){ // pop up alert for stock 
                            notify('Please enter '+dataCheckKey+' for '+item.ProductName,'SHORT');
                            isValid=false;
                        }
                    }else{
                        if(SaleFlag && isSaleDependEnable && ((skuData["Sale"]>skuData["Stock"])  )){
                            //data does not exists for sale
                            notify('Sale should not be greater than stock for '+item.ProductName,'SHORT');
                            isValid=false;
                        }
                        
                         //data exists for sale
                        isAnyFilled=true;
                    }

                    //check if any filled for sales at last index
                    console.log("isAnyFilled:",isAnyFilled);
                    if(SaleFlag && index==brandData.length-1 && !isAnyFilled){
                        isValid=false;
                        notify('Please enter sale for atleast one product!');
                    }
                    
                }
            })
        );

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

    function onStockValChange(item,val,key,type=''){
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }
        
        let allSKUData=SKUStockData;
        let defData={'SamplingStockId':item.SamplingStockId,'SamplingStockDefinitionId':item.SamplingStockDefinitionId};
        const skud_index=allSKUData.findIndex(i=>i.SamplingStockId==item.SamplingStockId && i.SamplingStockDefinitionId==item.SamplingStockDefinitionId);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        skud[key]=val;

        skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
        BgWindowData(allSKUData)
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function _render_Alert(){
        return (
          <CustomModal 
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={'Do you really want to save data?'}
            showModal={showAlert}
          >
            <View style={customStyle.storelVisitM_options}>
             <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setShowAlert(false)}}>
                <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{saveData()}}>
                <Text style={customStyle.storelVisitM_op_btnText}>Yes</Text>
              </TouchableOpacity>
            </View>
          </CustomModal>
        )
      }

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

      function _OpenCaptureImage_Modal(img){
       
        const isImageCap=(img!='' || img!=null)?true:false;
        // console.log("imag pop is trigger",isImageCap,showModal,img)
        let {item}=reCapImgModalObj
        let camera2Label=(window && window.PromoImage2Lable) || '';
        return (
          <CustomModal 
            style={customStyle.PromoImgModal}
            title={currentMenu.MenuName+" Image"}
            message={camera2Label}
            titleStyle={customStyle.PromoImgModal_title}
            messageStyle={customStyle.PromoImgModal_subtitle}
            showModal={showModal}
          >
            { 
            isImageCap && 
            <View style={customStyle.PromoImgModalCon}>
              <View style={customStyle.PromoImgModal_ImgWrap}>
                <Image  style={[customStyle.PromoImgModal_Img,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:SelectedImg}} />
              </View>
              <TouchableOpacity style={customStyle.PromoImgModal_CameraSmall} onPress={()=>{openCamera(item)}}>
                <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color}/>
              </TouchableOpacity>
              
              {!showImageSaveOp &&
                <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={()=>{cancelImage()}}>
                  <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                </TouchableOpacity>
              }
            </View>
            }
          </CustomModal>
        )
      }
  

    function _renderStocks(){

        return (
        <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={(Platform.OS=='ios'?10:-100)} >  
            <FlatList 
            data={brandData}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.opening_Stock_scroll} 
            style={customStyle.opening_Stock_scrollOuter}
            nestedScrollEnabled={true}
            scrollToOverflowEnabled={true}
            renderItem={({item,index})=>{

                const cat=item;
                const catIndex=index;
                let keyname= SaleFlag==true ? 'Sale' :'Stock';
                const cindex=SKUStockData.findIndex(i=>i.SamplingStockId==item.SamplingStockId && i.SamplingStockDefinitionId==item.SamplingStockDefinitionId);
                let stockData=cindex>=0?SKUStockData[cindex]:{};
                const Stock=stockData[keyname]!=null?stockData[keyname]:'';
    
                return(
                    <View style={customStyle.Sampling_OStock_wrap} key={catIndex}>
                        {/* <View style={customStyle.opening_Stock_cat}>                            
                            <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                <Text style={customStyle.opening_Stock_catText}>{item.ProductName}</Text>
                            </LinearGradient>
                        </View> */}
                        <View style={customStyle.Sampling_OStock_prds}>
                            <View style={customStyle.openStk_prd_Con} >
                                <Text style={customStyle.openStk_prd_name}>{item.ProductName}</Text>
                                {SaleFlag && <Text style={[customStyle.openStk_prdd_flabel,customStyle.openStk_prd_borderB]}>{"Stock: "+stockData.Stock}</Text>}
                                <View style={customStyle.openStk_prd_form}>
                                    <View style={customStyle.openStk_prd_row}>
                                            <View style={[customStyle.openStk_prd_colflex]}>
                                            <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ SaleFlag==true ? 'Sale' :'Stock'}</Text>
                                            <TextInput 
                                                ref={(reff)=>{inputRefs.current['input1_'+item.SamplingStockId+'_'+item.SamplingStockDefinitionId]=reff;}}
                                                style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle]}              
                                                placeholder=""   
                                                autoComplete='off'   
                                                editable={!disableEdit}      
                                                placeholderTextColor={PageTheme.$placeholder_color} 
                                                value={(Stock+'' || '')}
                                                returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                keyboardType='number-pad'
                                                blurOnSubmit={false}
                                                onChangeText={(val)=>{ 
                                                    onStockValChange(cat,val,keyname,'numeric')}}
                                                onSubmitEditing={()=>{focusToNext(cat,'1')}}
                                            />
                                        </View>
                                    </View>
                                </View>
                            </View>
                        </View>
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView> 
        );
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={SaleFlag?"S-Sale":"S-Stock"} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {_OpenCaptureImage_Modal()}
        {_render_Alert()}
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName+' Stock'} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper]}>
          { Object.keys(storeData).length>0 &&     
            _renderStocks()
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
               {!disableEdit &&  <GradientButton {...props} title={'Save'} onPress={()=>{submitOpeningStock()}}/> }
               {disableEdit &&  <GradientButton {...props} title={'Save'} onPress={()=>{submitOpeningStock()}} disabled={true} colors={[PageTheme.$text_color_light,PageTheme.$text_color_light]} /> }
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
  }
  
  

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