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, Keyboard, Animated, AppState} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2, resizeImage, restore_ImageWithMetaData, 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, HierarchyTbls} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome, Ionicons, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';

import GradientButton from '../components/gradientButton';
import { ConfirmSaveAlert} from '../components/alert';
import QRCodeScannerKit from '../components/QRCodeScannerKit';


function SaleQRCode(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 [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 [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;
    }, [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 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);} }
            ]
          );
    }

//chngesss new restricate dublicate when same product exist in db also

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_SALE} 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, ...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 in current products list
                const existsInList = products.some((item) => item.code === QRcode);
                if (existsInList) {
                    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
                const qrParts = QRcode.split('-');
                if (qrParts.length >= 2) {
                    extractedCode = qrParts[qrParts.length - 2];  // Second-last part
                }

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

                // ✅ Check if product already exists in QRCODE_SALE table
                txn.executeSql(
                    `SELECT COUNT(*) as count FROM ${AppTables.QRCODE_SALE} WHERE STORE_ID = ? AND VISIT_DATE = ? AND UNIQUE_QRCODE = ?`,
                    [StoreId, d2, QRcode], // Use full QRcode instead of extractedCode
                    (txn2, checkRes) => {
                        // Log the raw result for debugging
                        console.log("checkRes:", JSON.stringify(checkRes));
                        // Access the count correctly
                        const count = checkRes.rows.item(0).count; // Should work for most SQLite libraries
                        const existsInTable = count > 0;

                        console.log("Exists in table:", existsInTable, "Count:", count);

                        if (existsInTable) {
                            Alert.alert('Duplicate', 'This item already exists in the sales record for today.');
                            return;
                        }

                        // ✅ Query Product_Master for product name if no duplicate found
                        txn.executeSql(
                            `SELECT ProductName, ProductId FROM Product_Master WHERE ProductCode = ?`, 
                            [extractedCode], 
                            (txn3, 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,
                                        productId: productId,
                                        ProductCode: extractedCode // Add ProductCode for consistency
                                    };                           
                                    const updatedList = [newProduct, ...prev];
                                    return updatedList.map((item, index) => ({
                                        ...item,
                                        id: index + 1  // Re-index IDs
                                    }));
                                });
                            },
                            (txn3, err) => {
                                console.error('Error querying Product_Master:', err);
                            }
                        );
                    },
                    (txn2, err) => {
                        console.error('Error checking QRCODE_SALE:', err);
                    }
                );
            }
        });

    } catch (err) {
        console.error('Error in getData:', err);
    }
}
    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_SALE} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;

                //  remove old data
                txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('QRCODE_SALE 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_SALE} (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('Sale QR Data 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);
        }
      
    }

    //   async function Remove_QRdata() {
    //         let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
    //         let { MenuId } = currentMenu;
          
    //         db.transaction(async function (txn) {          
    //                 let index = toRemoveId;
    //                 console.log("indexxx----",index)
    //                 let item = toRemoveItem;
    //                 let arr = products;
    //                 if (item.QRCODE_ID!=null && item.QRCODE_ID!='undefined'&& index>0) {
    //                         console.log("check-keyId-",index)      
                               
    //                         let deleteQuery=`DELETE FROM ${AppTables.QRCODE_SCANNER} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' AND QRCODE_ID='${index}' `;
    //                         console.log("dlete-query",deleteQuery)
    
    //                             txn.executeSql(deleteQuery, [], function (txn3, txnres) {
    //                                 console.log('QR-Code data deleted', item.QRCODE_ID,+""+index);
    //                                 let updatedProduct = products.filter(item => item.QRCODE_ID !== index);
    //                                 setProducts(updatedProduct);
    //                                 setHasUnsavedChanges(true);  
    //                                 notify('QR-Code  removed successfully', 'LONG'); 
    //                                 setrerenderdata(!rerenderdata);
    //                                 setToRemoveId('');
    //                                 setToRemoveItem({});
    //                                 setshowRemoveConfirm_M(false);
                                                              
    //                             }, function (txnE, txnerr) {
    //                                 console.log('Error deleting QR-Code :', txnerr);
    //                             });                        
                                                                   
    //                 } 
    //                 else {
    //                     let index=toRemoveId
    //                     let item=toRemoveItem;
    //                     let arr=products;
    //                     console.log('toRemoveId:',"helllo");
    //                     console.log('toRemoveId:',index);
    //                     if(index>=0 && index<arr.length){
    //                         arr.splice(index,1);
    //                         setProducts(arr);
    //                         setHasUnsavedChanges(true);
    //                         notify('QR-Code removed successfully','LONG')
    //                         setrerenderdata(!rerenderdata);
    //                     }
    //                     else{
    //                         notify('Cannot remove! QR-Code not found','LONG')
    //                     }
    //                     setToRemoveId('');
    //                     setToRemoveItem({});
    //                     setshowRemoveConfirm_M(false);
    //                 }
               
    //         });
    //     }

    //===============neww deletion
    async function Remove_QRdata() {
        let { StoreId } = storeData;  
        let index = toRemoveId;  
        let item = toRemoveItem;  
    
        db.transaction(async (txn) => {
            // ✅ If item exists in the database
            if (item.QRCODE_ID && item.QRCODE_ID !== 'undefined' && index >= 0) {
                console.log("Deleting from DB, ID:", item.QRCODE_ID);
    
                let deleteQuery = `DELETE FROM ${AppTables.QRCODE_SALE} WHERE STORE_ID = '${StoreId}'AND VISIT_DATE = '${d2}'AND QRCODE_ID = '${item.QRCODE_ID}' `;
    
                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"){

        // if(val!=''){
        //     let isValid=validateNumber(val,type);
        //     console.log("type:",type,isValid);
        //     if(!isValid){
        //         return;
        //     }r
        // }    
        let data=AddVisFormData;
        data[key]=val;
        setAddVisFormData(data);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);

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

   


    function _renderSaleData(){
        //{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 }}>{skus.id || skus.QRCODE_ID}</Text>
                                                      <View style={customStyle.qrCodeScanner}>
                                                      <Text style={customStyle.qrCodeInputStyle} > {skus.code || skus.UNIQUE_QRCODE}</Text>
                                                      <Text >{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,ST.Doyoureallywanttoremovethisvisibility)}
        {/* <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);  
          }}
        />
        
        <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>

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

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