import React,{useState,useEffect, useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles,GetPageTheme } from "../styles/Global";
import {TextInput,View,Text,TouchableOpacity,Platform,FlatList, Alert, KeyboardAvoidingView, Keyboard, AppState} from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import { restore_ImageWithMetaData} from '../controller/functions';
import {set_item,clear_item} from '../components/localStorage';
import {db, ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { FontAwesome, Ionicons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import { ConfirmSaveAlert} from '../components/alert';
import CustomCamera from '../components/Camera';
import QRCodeScannerKit from '../components/QRCodeScannerKit';


function StockUniqueQRCode(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(false);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [globalBrandData, setGlobalBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    
    const [catImages, setCatImages] = useState([]);
    const [SKUStockData, setSKUStockData] = useState([]);

    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);
    const [showAlert, setShowAlert] = useState(false);
    const [toRemoveId, setToRemoveId] = useState('');
    const [toRemoveItem,setToRemoveItem]= useState({});
    const [showRemoveConfirm_M,setshowRemoveConfirm_M]= useState(false);


    const [AddVisFormData, setAddVisFormData] = useState({});
    const [QREnable, setQREnable] = useState(false);
    const [QRqtnData, setQRqtnData] = useState({});
    const [showQRCamera, setShowQRCamera] = useState(false);
     const [products, setProducts] = useState([]);
    
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [ShowCatWise,setShowCatWise]= useState(false);
    const [CatData,setCatData]= useState(false);

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(SKUStockData);
    const WindowDataImgRef = React.useRef(catImages);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = useState(false);
    const PSGroupData=React.useRef(''); // Grouping data (Category/ SubCategory/ Brand ) for BG save fuunctionality with Partial Save Scenario
    const BGPSAllow=React.useRef(false);

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

    const [productList, setProductList] = useState([]); 


  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let ShowCatWise1=params.ShowCatWise!=null?params.ShowCatWise:false;
        let CatData1=params.CatData!=null?params.CatData:{};
        let isAdhoc=params.isAdhoc || false;

        console.log('params.ShowCatWise',params.ShowCatWise);

        setIsAdhocScreen(isAdhoc);
        setShowCatWise(ShowCatWise1);
        setCatData(CatData1);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        setStoreCameraAllow(cameraAllow);
            
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName
         getData(storeData1,menu1,ShowCatWise1,CatData1);

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

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

           let newDataForSubCateory ={
            storeBGDataHdr:WindowDataImgRef.current,
            menuName:ScreenNameRef.current,
            StoreId1:StoreIdRef.current,
            visiteDate:d2,
            BGPSAllow:BGPSAllow.current,
            PSGroupData:PSGroupData.current,
           }
           let WindowsStr2= JSON.stringify(newDataForSubCateory)
           console.log("checkwindatahdr:",WindowsStr2)
           await set_item('storeDataHdr',WindowsStr2); 
       }
     }

    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(() => {
        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 BgWindowDataHdr(val){
        WindowDataImgRef.current=val
        setCatImages(val);
    }


    
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
              {
                text: ST.Cancel,
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: async () => {
                // setHasUnsavedChanges(false);
                BgUnsavedChanges(false)
                await clear_item('storeData')
                props.navigation.dispatch(e.data.action);} }
            ]
          );
    }

async function getData(storeData1, menu1, ShowCatWise1, CatData1 = {}, QRcode = null) {
    try {
        let { StoreId } = storeData1;

        db.transaction((txn) => {

            // ✅ Step 1: Load existing data if no QR code is scanned
            if (!QRcode) {
                setLoaderTitle(ST.Loading + '...');
                setProcessing(true);

                let loadQuery = `SELECT * FROM ${AppTables.QRCODE_SCANNER} WHERE STORE_ID = ? AND VISIT_DATE = ?`;
                txn.executeSql(loadQuery, [StoreId, d2], (txn2, txnres) => {
                    console.log('Existing products:', txnres.rows.length);

                    let existingProducts = [];
                    for (let i = 0; i < txnres.rows.length; i++) {
                        existingProducts.push({ 
                            // id: i + 1,  
                            // code: txnres.rows.item(i).UNIQUE_QRCODE,  
                            // productName: txnres.rows.item(i).PRODUCT_NAME || 'Unknown Product',
                            // qrCodeId: txnres.rows.item(i).QRCODE_ID
                            id: i + 1, ...txnres.rows.item(i) 

                        });
                    }

                    console.log("Loaded existing products:", existingProducts);
                    setProducts(existingProducts);
                    setProcessing(false);

                }, (txnE, txnerr) => {
                    console.log('Error loading existing data:', txnerr);
                });
            }

            // ✅ Step 2: Handle new QR code scan
            if (QRcode) {
                // Check for duplicates
                const exists = products.some((item) => item.code === QRcode);
                if (exists) {
                    Alert.alert('Duplicate', 'This item is already added to the list.');
                    return;
                }

                // ✅ Improved QR extraction with validation
                let extractedCode = 'N/A';  // Default if extraction fails

                console.log("qrcode---",QRcode)

                const qrParts = QRcode.split('-');
                if (qrParts.length >= 2) {
                    extractedCode = qrParts[qrParts.length - 2];  // Second-last part
                }

                console.log('Extracted Product Code:', extractedCode);

                // ✅ Query `Product_Master` for product name
                txn.executeSql(
                    `SELECT ProductName,ProductId FROM Product_Master WHERE ProductCode = ?`, 
                    [extractedCode], 
                    (txn2, res) => {
                        let productName = 'Unknown Product';
                        let productId =''
                        if (res.rows.length > 0) {
                            productName = res.rows.item(0).ProductName;
                            productId = res.rows.item(0).ProductId;
                        }

                        console.log('Matched Product Name:', productName);

                        // ✅ Add new product with name to the list and re-index IDs
                        setProducts((prev) => {
                            // const newProduct = { 
                            //     id: prev.length + 1, 
                            //     code: QRcode, 
                            //     productName: productName
                            // };

                            const newProduct = { id: prev.length + 1, code: QRcode, productName: productName,productId:productId };
                            
                           // const updatedList = [...prev, newProduct];
                            const updatedList = [newProduct, ...prev];
                            return updatedList.map((item, index) => ({
                                ...item,
                                id: index + 1  // ✅ Re-index IDs
                            }));
                        });
                    },
                    (txn2, err) => {
                        console.error('Error querying Product_Master:', err);
                    }
                );
            }
        });

    } catch (err) {
        console.error('Error in getData:', err);
    }
}




    async function getImage(imgdata){
        let cat=getImageProps.option || '';
        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: '+currentMenu.MenuName+' | 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+'_'+(props.UserId || '')+'_Stock-'+picture_clicked_date1+'_'+picture_clicked_time1+'.jpg';
            
            let allIMgs=catImages;
            let defData={'SubCategoryId':cat.SubCategoryId};
            const cindex=allIMgs.findIndex(i=>i.SubCategoryId==cat.SubCategoryId);
            const imgData=cindex>=0?(allIMgs[cindex] || defData):defData;
            imgData.ImageName=filename;

            let imagePath='file://'+ImageFolderPath+currentMenu.ScreenName+"/"+filename;
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri=imagePath;
                console.log('image marker',uri);
                imgData.ImagePath=uri; 
                cindex>=0?allIMgs[cindex]=imgData:allIMgs.push(imgData);
                setCatImages(allIMgs);
                console.log("catimages--",catImages)
                // setHasUnsavedChanges(true);
                BgWindowDataHdr(allIMgs)
               
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);

                // 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);
            });                      
        }        
    }
  

    async function submitQRData(){
       let isvalid=await validate();
       console.log("isvalidd--",isvalid);
        if(isvalid){
            Keyboard.dismiss();
           setShowAlert(true);
        }
    }

    async function saveData(){
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        try {   
            let {StoreId}=storeData;
            db.transaction(async function (txn) {

                let q = `DELETE FROM ${AppTables.QRCODE_SCANNER} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;

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

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

    

    async function insertData(seq = 0) {
        try {
            let {StoreId}=storeData;
            console.log('scannedProducts before insertion:', products,StoreId);  // ✅ Verify the data
          
            if (products.length === 0) {
                console.log('No products to insert.');
                notify('No products to insert!');
                return;
            }
    
            db.transaction(async (txn) => {
                let scanValues = products.map((product, index) => {
                    seq++;
                    console.log('scannedProducts for insertion:', products); 
                    const {code,id,productName,productId} = product;
                    console.log("checkproducts:",product)
    
                  //  let SKU_UID = `SKU${seq}${Math.floor(Math.random() * 1000)}`;
    
                    return `('${id || product.QRCODE_ID}', '${StoreId}','${d2}','${code || product.UNIQUE_QRCODE}','${productName || product.PRODUCT_NAME}','${productId || product.PRODUCT_ID}','${d2}')`;
                }).join(", ");   // ✅ Combine all values into a single query
    
                let addScanQuery=`INSERT INTO ${AppTables.QRCODE_SCANNER} (QRCODE_ID,STORE_ID,VISIT_DATE,UNIQUE_QRCODE,PRODUCT_NAME,PRODUCT_ID,ADDED_DATE) VALUES ${scanValues} `;
    
                console.log('Insert query:', addScanQuery);
    
                txn.executeSql(
                    addScanQuery,
                    [],
                    (txn2, res) => {
                        console.log('Data inserted successfully');
                        notify('Stock inserted successfully!');
                        setProcessing(false);
                        setProductList([]);  // ✅ Clear the list after insertion
                    },
                    (error) => {
                        console.error('Insert Error:', error);
                        notify('Failed to insert data!');
                    }
                );
            });
    
        } catch (err) {
            console.error('Insertion Error:', err);
            notify('An error occurred while inserting data!');
        }
    }
    


    async function validate(){
        let isValid=true;

        if(products.length === 0){
            notify("Please Scan  QR Code");
            isValid=false;
        }
        console.log('isValid:',isValid);
        return isValid;
    }


    function onSaveCancel(){
        setShowAlert(false)
    }

    function showRemoveConfirm(item,index){
        console.log("checking-------",item)

        if(item.QRCODE_ID>0){
            console.log("checking--id-----",item.QRCODE_ID)
            setToRemoveId(item.QRCODE_ID);
            setToRemoveItem(item);
            setshowRemoveConfirm_M(true);
        }
        else{
            setToRemoveId(index);
            setToRemoveItem(item);
            setshowRemoveConfirm_M(true);
        }
      
    }

    //===============neww deletion
    async function Remove_QRdata() {
        let { StoreId } = storeData;  
        let index = toRemoveId;  
        let item = toRemoveItem; 
        console.log("Deleting frommmm-----"); 
    
        db.transaction(async (txn) => {
            // ✅ If item exists in the database
            console.log("Deleting from -----",item);
            if (item.QRCODE_ID && item.QRCODE_ID !== 'undefined' && index >= 0) {
                console.log("Deleting from DB, ID:", item.qrCodeId);
    
                let deleteQuery = `DELETE FROM ${AppTables.QRCODE_SCANNER} WHERE STORE_ID = '${StoreId}'AND VISIT_DATE = '${d2}'AND QRCODE_ID = '${item.QRCODE_ID}' `;
                console.log("deleteQuery:", deleteQuery);
    
                txn.executeSql(deleteQuery, [], (txn3, txnres) => {
                    console.log('QR-Code data deleted:', item.QRCODE_ID);
    
                    // ✅ Remove from the local products list
                    const updatedProducts = products
                        .filter((p) => p.QRCODE_ID !== item.QRCODE_ID)
                        .map((p, idx) => ({ ...p, id: idx + 1 }));  // ✅ Reassign IDs
    
                    setProducts([...updatedProducts]);  // Ensure a fresh reference for re-render
                    setHasUnsavedChanges(true);
                    notify('QR-Code removed successfully', 'LONG');
                    setAddVisFormData({});
                    setrerenderdata((prev) => !prev);  // Trigger re-render
                    setToRemoveId('');
                    setToRemoveItem({});
                    setshowRemoveConfirm_M(false);
    
                }, (txnE, txnerr) => {
                    console.log('Error deleting QR-Code:', txnerr);
                });
    
            } else {
                // ✅ Handle local deletion (not in DB)
                if (index >= 0 && index < products.length) {
                    console.log('Deleting locally, index:', index);
    
                    const updatedProducts = products
                        .filter((_, i) => i !== index)   // Remove item by index
                        .map((item, idx) => ({ ...item, id: idx + 1 }));  // ✅ Reassign IDs
    
                    setProducts([...updatedProducts]);  // Ensure fresh reference for re-render
                    setHasUnsavedChanges(true);
                    notify('QR-Code removed successfully', 'LONG');
                    setAddVisFormData({});
                    setrerenderdata((prev) => !prev);  // Trigger re-render
                } else {
                    notify('Cannot remove! QR-Code not found', 'LONG');
                }
    
                setToRemoveId('');
                setToRemoveItem({});
                setshowRemoveConfirm_M(false);
            }
        });
    }
    


    async function onQRScanned(imgdata){

        let QR_withValidChars=imgdata!=null && imgdata!=''?imgdata.replace(/["']/g,''):'';
        let value=QR_withValidChars;
        console.log("value------",value)
        onFormDataChange(value,'QRCode','qrtext')
        getData(storeData,currentMenu,"","",value);
    }


    function onFormDataChange(val,key,type="text"){

           
        let data=AddVisFormData;
        data[key]=val;
        setAddVisFormData(data);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);

        console.log("addvisbiltydtaa--",AddVisFormData)
    }

   

    function FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        console.log('searchedQry',searchedQry);
        let arr=[];
        var arr2={};
        var newBrand={};
        if(searchedQry!=null && searchedQry!=''){
            // globalBrandData.map((item,index)=>{
            for(let i=0;i<globalBrandData.length;i++){
                let item=globalBrandData[i];
                let brandList=item.brandList || [];
                arr2=Object.assign({'test':'1'} , item);
                
                let newBrandList=[];
                for(let j=0;j<brandList.length;j++){
                    let brand=brandList[j];
                    let skulist=brand.skulist || [];
                    newBrand=Object.assign({'test2':'2'} , brand);
                    
                    let newSkulist=[];
                    for(let k=0;k<skulist.length;k++){
                        let sku=skulist[k];
                        let {ProductName}=sku;
                        if(ProductName.toLowerCase().includes(searchedQry)){
                            newSkulist.push(sku);
                        }

                        if(k==skulist.length-1){
                            newBrand.skulist=newSkulist;
                            
                            if(newBrand.skulist.length>0){
                                newBrandList.push(newBrand);
                                if(j==brandList.length-1){
                                    arr2.brandList=newBrandList;
                                    arr.push(arr2);
                                }
                            }

                        }
                    }
                }

                
            }
        }
        else{
          arr=globalBrandData;
        }

        console.log('globalBrandData:',globalBrandData)
        setBrandData(arr);
        setrerenderdata(!rerenderdata)
        setrerenderdata2(!rerenderdata2)
    }


    function _renderStocks(){
        //{console.log("productList----", productList )}
        let isHdrImgIndex=KPIFields.findIndex(i=>i.KPIFieldName=='HeaderImageAllow')
        let isHdrImgKPIObj=isHdrImgIndex>=0?KPIFields[isHdrImgIndex]:{};

        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view_qr,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={-150} >                                                       
                                            <FlatList 
                                            data={products}
                                            extraData={rerenderdata2}
                                            listKey={(i,skuIndex)=>{ return skuIndex;}}
                                            renderItem={({item,index})=>{
                                                
                                            const skus=item;
                                            console.log("checkskudata:",skus)
                                        
                                            const sku_index=index;
    
                                            let card_bg = skus.code ? { backgroundColor: PageTheme.$fifth_color } : {};
                                               // get error field product id
                                            let EF_product= errorfield.EF_product!=null? errorfield.EF_product:{};
                                            let error_pid = EF_product.ProductId || '';
                                            let EF_InputKey=errorfield.EF_InputKey;
                                            // let show_errorhere =errorcatid==cat.SubCategoryId && error_bid==brand.BrandId && error_pid==skus.ProductId;
                                            
                                            let errorStyle_ST=( error && show_errorhere && EF_InputKey=='input1_'? customStyle.stk_inptSTyle_error :{});

                                            return(
                                                <View key={sku_index}
                                                    style={{
                                                        flexDirection: 'row',
                                                        justifyContent: 'flex-start',
                                                        alignItems: 'center',
                                                        marginLeft: 20,
                                                        flex: 1,
                                                    }}
                                                >
                                                    <Text style={{ fontWeight: 800, marginRight: 15,color:'gray' }}>{skus.id || skus.QRCODE_ID}</Text>
                                                    <View style={customStyle.qrCodeScanner}>
                                                    <Text style={customStyle.qrCodeInputStyle}> {skus.code || skus.UNIQUE_QRCODE}</Text>
                                                    <Text style={{marginTop:5}} >{skus.productName||skus.PRODUCT_NAME}</Text>
                                                    </View>
                                            
                                                    <TouchableOpacity style={{ marginLeft: 20 }} onPress={() => { showRemoveConfirm(item, index); } }>
                                                        <FontAwesome name='trash' size={20} color={'red'} />
                                                    </TouchableOpacity>
                                                </View>
                                            )
                                            }}
                                            contentContainerStyle={{ paddingBottom: 120 }}
                                            />                                     
                         </KeyboardAvoidingView>   
        )
    }
    
    
   
    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <View style={{zIndex: 10}}>
          <CustomHeader {...props} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        </View>
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {ConfirmSaveAlert(props,showRemoveConfirm_M,()=>{setshowRemoveConfirm_M(false)},Remove_QRdata,"Do you want to remove this item")}
        {/* <CustomCamera cameraType={'back'} QRCodeEnable={QREnable} onImageCaptured={(imgData)=>{setShowQRCamera(false);onQRScanned(imgData)}} showCamera={showQRCamera} onHideCamera={()=>{setShowQRCamera(false);}}/>    */}
       <QRCodeScannerKit visible={showQRCamera} onClose={() => { setShowQRCamera(false); setQREnable(false);}}
     onQRScanned={(value) => {
    setShowQRCamera(false);
    setQREnable(false);
    onQRScanned(value);  // तुम्हारा existing function
  }}
/>

        
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName} 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]}>

          <View style={customStyle.addVisForm}>
                    <View style={customStyle.addVisRow}>                        
                        <View style={[customStyle.addVisCol100]}>
                            <View style={customStyle.addVisFormGrp}>
                                <Text style={customStyle.addVisLabel}>{"QR Code"}</Text>
                                <View>
                                    <TextInput  
                                        style={customStyle.addVisInputStyle} 
                                        value={(AddVisFormData.QRCode || '')}
                                        onChangeText={(val)=>{onFormDataChange(val,'QRCode',"qrtext");}}
                                        autoComplete='off'
                                    />
                                    <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={()=>{setQREnable(true);setQRqtnData({});setShowQRCamera(true);}}>
                                        <Ionicons name="camera" color={PageTheme.$accent_color} size={24}/>
                                    </TouchableOpacity> 
                                </View>
                            </View>
                        </View>
     
                    </View>
                </View>

          {   
              _renderStocks()
          }
        
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{submitQRData()}}/> 
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
  }
  
  

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