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, Animated } 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, marktext1, marktext2, validateNumber } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr, visiCoolerImgPath, ImageFolderPath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
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 * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import CameraImg from '../assets/performics/camera_front_image.svg'
import { ConfirmSaveAlert } from '../components/alert';
import CustomCamera from '../components/Camera';

function DBVisiCooler(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 animatedChoice = useRef(new Animated.Value(0)).current;

    const [processing, setProcessing] = useState(true);
    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 [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);

    const [AddVisibility, setAddVisibility] = useState([]);
    const [PreviousVisicooler, setPreviousVisicooler] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [isAddVisPresent, setIsAddVisPresent] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [Categories, setCategories] = useState([]);
    const [SubCategories, setSubCategories] = useState([]);
    const [Brands, setBrands] = useState([]);
    const [DisplayList, setDisplayList] = useState([]);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [clickImageType, setClickImageType] = useState('1');
    const [toRemoveId, setToRemoveId] = useState('');
    const [toRemoveItem, setToRemoveItem] = useState({});
    const [showRemoveConfirm_M, setshowRemoveConfirm_M] = useState(false);
    const [showRAllC_M, setShowRAllC_M] = useState(false);

    const [QREnable, setQREnable] = useState(false);
    const [QRqtnData, setQRqtnData] = useState({});
    const [showQRCamera, setShowQRCamera] = useState(false);

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


    useEffect(() => {
        setLoaderTitle(ST.Loading + '...')
        let params = props.route.params ? props.route.params : {};
        let storeData1 = params.storeData || {};
        let menu1 = params.menu || {};
        let cameraAllow = storeData1.CameraAllow == 'true' || storeData1.CameraAllow == 1 ? true : false;
        setStoreCameraAllow(cameraAllow);

        let isAdhoc = params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        getData(storeData1);

        props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
            props.navigation.removeListener('beforeRemove', onBeforeRemove);
        };
    }, []);

    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [hasUnsavedChanges]);

    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [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 onRemoveScreen(e) {
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
                {
                    text: ST.Cancel,
                    onPress: () => { },
                    style: "cancel"
                },
                { text: ST.OK, onPress: () => { setHasUnsavedChanges(false); props.navigation.dispatch(e.data.action); } }
            ]
        );
    }

    async function getData(storeData1) {
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;

            await db.transaction(async function (txn) {


                let q3 = `Select * from ${AppTables.DB_VISICOOLER} WHERE DISTRIBUTOR_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                await txn.executeSql(q3, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let { QRCODE, ASSETCODE, IMAGE, KEY_ID } = data;
                            let datan = { QRCode: QRCODE, AssetCode: ASSETCODE, Image1: IMAGE, keyId: KEY_ID }
                            // datan.Image1Path=IMAGE!=''?"file://"+visiCoolerImgPath+"/"+IMAGE:'';
                            // let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
                            console.log("Image-777-", IMAGE);
                            console.log("Image-77788-", ImageFolderPath);
                            console.log("-currntmenuuu-", currentMenu.ScreenName);
                            datan.Image1Path = IMAGE != '' ? "file://" + ImageFolderPath + 'DBVISICOOLERONEAPP' + "/" + IMAGE : '';
                            //  let imagePath=Image1!=null && Image1!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+Image1:'';
                            console.log("Image-77799988-", datan);

                            arr.push(datan)
                            if (i == txnres2.rows.length - 1) {
                                setAddVisibility(arr);
                                setProcessing(false);
                            }
                        }
                    }
                    else {
                        setProcessing(false);
                    }
                }, function (txn2, txnerr) { console.log(txnerr); setProcessing(false); },);

                let q4 = `Select * from Distributor_PreviousVisicooler WHERE DistributorId='${StoreId}'  `;
                await txn.executeSql(q4, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let { VC_QRCode, VC_AssetCode } = data;
                            let datan = { QRCode: VC_QRCode, AssetCode: VC_AssetCode, Image1: "" }
                            datan.Image1Path = '';
                            arr.push(datan)
                            if (i == txnres2.rows.length - 1) {
                                setPreviousVisicooler(arr);
                            }
                        }
                    }

                }, function (txn2, txnerr) { console.log(txnerr); },);


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



    async function getImage(imgdata) {
        let type = clickImageType;
        if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify(ST.Cameraunavailable);
        }
        else if (typeof imgdata == 'object' && imgdata.uri != null) {
            const img = imgdata;
            const imgurl = img.uri, imgWidth = img.width, imgHeight = img.height;
            let picture_clicked_timee = new Date();
            let picture_clicked_time = moment(picture_clicked_timee).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name = moment(picture_clicked_timee).format('MMDDYYYY_HHmmss')

            console.log("time", picture_clicked_time);
            console.log("time1", picture_clicked_time_for_pic_name);
            let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
            let calculate_tym_date_over_img = picture_clicked_time;
            const mark_text1 = calculate_tym_date_over_img;
            const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: Add. Visibility' + ' | Date:' + calculate_tym_date_over_img;

            await marktext1(mark_text1, imgurl)
                .then((res) => {
                    if (res.success) {
                        let uri = res.uri;
                        marktext2(mark_text2, uri, imgWidth, imgHeight)
                            .then((res) => {
                                if (res.success) {
                                    let filename = storeData.StoreId + '_' + (props.UserId || '') + '_DbVisicoolerImg-' + calculate_tym_date_for_filename + '.jpg';
                                    let addvisdata = AddVisFormData;
                                    let image_key = 'Image1';
                                    let image_path_key = 'Image1Path';
                                    addvisdata[image_key] = filename;
                                    // renamefile
                                    let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;
                                    console.log("imgpath---", imagePath, ImageFolderPath, currentMenu.ScreenName);
                                    RNFS.copyFile(res.uri, imagePath)
                                        .then(resn => {
                                            let uri = 'file://' + imagePath;
                                            console.log('image marker', uri);
                                            addvisdata[image_path_key] = uri;
                                            setAddVisFormData(addvisdata);
                                            setHasUnsavedChanges(true);
                                            setrerenderdata2(!rerenderdata2);
                                        })
                                        .catch(err => {
                                            console.log('ERROR: image file write failed!!!');
                                            console.log(err.message, err.code);
                                        });

                                }
                                else {
                                    if (res.imagenotfound) {
                                        notify(ST.Pleasecaptureaimage);
                                    }
                                    else {
                                        notify(res.error);
                                    }
                                }
                            });
                    }
                    else {
                        if (res.imagenotfound) {
                            notify(ST.Pleasecaptureaimage);
                        }
                        else {
                            notify(res.error);
                        }
                    }
                });
        }
    }

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

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

    async function saveData() {
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle(ST.SavingData + '...');
        setProcessing(true);
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
            await db.transaction(async function (txn) {

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

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

                var values = '';
                for (var i = 0; i < AddVisibility.length; i++) {
                    let catIndex = i;
                    let item = AddVisibility[catIndex];
                    let { QRCode, AssetCode, Image1, Image1Path } = item;
                    values += values != '' ? ' , ' : '';
                    values += ` ('${StoreId}','${d2}','${QRCode}','${AssetCode}','${(Image1 || '')}','${d2}') `;

                }

                console.log('values:', values);
                let add_data = `INSERT INTO ${AppTables.DB_VISICOOLER} (DISTRIBUTOR_ID,VISIT_DATE,QRCODE,ASSETCODE,IMAGE,ADDED_DATE) VALUES ${values} `;

                await txn.executeSql(add_data, [], async function (txn2, txnres) {
                    console.log('av added');
                    notify(ST.AdditionalVisibilityaddedsuccessfully, 'SHORT');
                    setProcessing(false);
                    props.navigation.goBack();
                }, function (txn2, txnerr) { console.log(txnerr); setProcessing(false); notify(ST.Cannotaddadditionalvisibility) },);


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




    async function validate() {

        let isValid = true;
        if (AddVisibility.length <= 0) {
            isValid = false;
            notify(ST.Pleaseaddfirst, 'SHORT');
        }

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

    async function validateForm() {
        let isValid = true;
        let { AssetCode, QRCode, Image1, Image1Path } = AddVisFormData;
        if ((QRCode == '' || QRCode == null)) {
            isValid = false;
            notify("Please Scanner code", 'SHORT');
        } else if ((AssetCode == '' || AssetCode == null)) {
            isValid = false;
            notify("Please Enter Asset Code", 'SHORT');
        }

        else if ((Image1 == '' || Image1 == null)) {
            // else if(StoreCameraAllow==true && (Image1=='' || Image1==null )){
            isValid = false;
            notify(ST.Pleaseclickimage, 'SHORT');
        }


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

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

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

    function onselectionChange(option, keyLbl, keyVal) {
        let data = AddVisFormData;
        data[keyVal] = option.value;
        data[keyLbl] = option.label;

        if (keyLbl == 'CategoryName') {
            loadData(option.value, 'SubCategories');

            // clear subcategory and brand
            data['SubCategoryId'] = '';
            data['SubCategoryName'] = '';
            data['BrandId'] = '';
            data['BrandName'] = '';
        }
        else if (keyLbl == 'SubCategoryName') {
            loadData(option.value, 'Brands');

            // clear brand
            data['BrandId'] = '';
            data['BrandName'] = '';
        }

        setAddVisFormData(data);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);


    }

    async function loadData(qId, type) {
        try {
            await db.transaction(async function (txn) {
                let q = '';
                if (type == 'SubCategories') q = `Select Distinct p.SubCategoryId,p.SubCategoryName from Product_Master p where (p.CategoryId='${qId}' or p.CategoryId=${qId}) and (p.IsCompetitor='0' or p.IsCompetitor=0) order by p.SubCategorySequence`;
                else if (type == 'Brands') q = `Select Distinct p.BrandName,p.BrandId from Product_Master p Where (p.SubCategoryId='${qId}' or p.SubCategoryId= ${qId}) and (p.IsCompetitor='0' or p.IsCompetitor=0) order by p.BrandSequence`;

                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    // console.log('rowcount:,',type,':',txnres2.rows.length);
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                if (type == 'SubCategories') setSubCategories(arr);
                                else if (type == 'Brands') setBrands(arr);
                            }
                        }
                    }
                }, function (txn2, txnerr) { console.log(txnerr); },);

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



    function onChoiceSelect(val, key) {
        if (val == 0 && AddVisibility.length > 0) {
            setShowRAllC_M(true);
            return;
        }
        var val1 = val == 1 ? 1 : 0;
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        setIsAddVisPresent(val);
        setHasUnsavedChanges(true);
        if (val == 0) {
            setAddVisibility([]);
            setAddVisFormData({});
        }
    }

    function onConfirmRemoveAll() {
        // Remove all data 
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: 0,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        setIsAddVisPresent(0);
        setHasUnsavedChanges(true);
        setAddVisibility([]);
        setAddVisFormData({});
        setShowRAllC_M(false);
    }

    function onSaveCancel() {
        setShowAlert(false);
    }

    async function onQRScanned(imgdata) {
        // let qtn=QRqtnData.qtn || {};
        // let window=QRqtnData.window || {};
        let QR_withValidChars = imgdata != null && imgdata != '' ? imgdata.replace(/["']/g, '') : '';
        let value = QR_withValidChars;//imgdata && imgdata[0] && imgdata[0].displayValue ? imgdata[0].displayValue :""
        // setTextValue(value,qtn,window)
        console.log("value------", value)
        onFormDataChange(value, 'QRCode', 'qrtext')
    }

    async function Add_AddVis() {
        let isValid = await validateForm();
        console.log('isValid add:', isValid);
        if (isValid) {
            let arr = AddVisibility;

            arr.push(AddVisFormData);
            setAddVisibility(arr);
            setHasUnsavedChanges(true);
            notify(ST.AdditionalVisibilityaddedsuccessfully, 'LONG');
            setrerenderdata(!rerenderdata);

            // clear data
            setAddVisFormData({});
        }

    }

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

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

    }

    // function Remove_AddVis(){
    //     let index=toRemoveId
    //     let item=toRemoveItem;
    //     let arr=AddVisibility;
    //     console.log('toRemoveId:',index);
    //     if(index>=0 && index<arr.length){
    //         arr.splice(index,1);
    //         setAddVisibility(AddVisibility);
    //         setHasUnsavedChanges(true);
    //         notify(ST.Visibilityremovedsuccessfully,'LONG')
    //         setrerenderdata(!rerenderdata);
    //     }
    //     else{
    //         notify(ST.CannotremoveVisibilitynotfound,'LONG')
    //     }
    //     setToRemoveId('');
    //     setToRemoveItem({});
    //     setshowRemoveConfirm_M(false);

    // }

    async function Remove_AddVis() {
        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 = AddVisibility;
            if (index > 0) {
                console.log("check-keyId-", index)

                let deleteQuery = `DELETE FROM ${AppTables.DB_VISICOOLER} WHERE DISTRIBUTOR_ID='${StoreId}' and VISIT_DATE='${d2}' AND KEY_ID='${index}' `;

                txn.executeSql(deleteQuery, [], function (txn3, txnres) {
                    console.log('Visicooler data deleted', item.keyId, +"" + index);
                    let updatedVisibility = AddVisibility.filter(item => item.keyId !== index);
                    setAddVisibility(updatedVisibility);
                    setHasUnsavedChanges(true);
                    notify('Visicooler removed successfully', 'LONG');
                    setrerenderdata(!rerenderdata);
                    setToRemoveId('');
                    setToRemoveItem({});
                    setshowRemoveConfirm_M(false);

                }, function (txnE, txnerr) {
                    console.log('Error deleting survey data:', txnerr);
                });

            }
            else {
                let index = toRemoveId
                let item = toRemoveItem;
                let arr = AddVisibility;
                console.log('toRemoveId:', index);
                if (index >= 0 && index < arr.length) {
                    arr.splice(index, 1);
                    setAddVisibility(arr);
                    setHasUnsavedChanges(true);
                    notify('Visicooler removed successfully', 'LONG')
                    setrerenderdata(!rerenderdata);
                }
                else {
                    notify('Cannot remove! Visicooler not found', 'LONG')
                }
                setToRemoveId('');
                setToRemoveItem({});
                setshowRemoveConfirm_M(false);
            }

        });
    }


    function _render_addVisFormTop() {
        let xpos = 0;
        if (animatedChoice != null) {
            xpos = animatedChoice.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -75],
            });
        }
        return (
            <View style={[customStyle.addvisCon]}>

                {
                    (rerenderdata == rerenderdata) &&
                    <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.DBVisScroll}>
                        <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 style={[customStyle.addVisCol100]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{"Asset Code"}</Text>
                                        <TextInput
                                            style={customStyle.addVisInputStyle}
                                            value={(AddVisFormData.AssetCode || '')}
                                            onChangeText={(val) => { onFormDataChange(val, 'AssetCode'); }}
                                            autoComplete='off'
                                        />
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol100]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{ST.Image}</Text>
                                        <View style={customStyle.addVisCameras}>
                                            <View style={customStyle.openStkCameraCon}>
                                                {(AddVisFormData.Image1Path == '' || AddVisFormData.Image1Path == null) &&
                                                    <TouchableOpacity style={[customStyle.osCat_action_openCam, customStyle.osCat_actn_margin]} onPress={() => { openCamera('1') }}>
                                                        <CameraImg width={80} height={80}  />
                                                    </TouchableOpacity>
                                                }
                                                {(AddVisFormData.Image1Path != '' && AddVisFormData.Image1Path != null) &&
                                                    <View style={customStyle.osCatImageView}>
                                                        <Image style={customStyle.osCatImage} source={{ uri: AddVisFormData.Image1Path }} />
                                                        <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={() => { openCamera('1') }}>
                                                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color} />
                                                        </TouchableOpacity>
                                                    </View>
                                                }
                                            </View>

                                        </View>
                                    </View>
                                </View>
                                <View style={customStyle.addVis_btnWrap}>
                                    <TouchableOpacity style={customStyle.addVis_btn} onPress={() => { Add_AddVis() }}>
                                        <Text style={customStyle.addVisBtnText}>{ST.Add}</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>

                        <View style={customStyle.addVis_list}>
                            <Text style={customStyle.addVis_listhdrText}>{"Added Visicooler List"}</Text>
                            <View style={customStyle.addVis_listInner}>
                                {
                                    AddVisibility.length > 0 &&
                                    AddVisibility.map((item, index) => {
                                        console.log(item);
                                        return (
                                            <View key={index} style={customStyle.addVis_listItem}>
                                                <View style={customStyle.addVis_listI_row2}>
                                                    <View style={customStyle.addVis_listIcol1}>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>{'QR Code :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.QRCode}</Text>
                                                        </View>

                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={[customStyle.addVis_listI_Label, { width: '60%' }]}>{'Asset Code :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.AssetCode}</Text>
                                                        </View>

                                                    </View>
                                                    <View style={customStyle.addVis_listIcol2}>
                                                        <Text style={[customStyle.addVis_listI_Label2, customStyle.mb20]}>{ST.Image}</Text>
                                                        {console.log("Image1Path--------", item.Image1Path)}
                                                        {(item.Image1Path != null && item.Image1Path != '') && <Image style={customStyle.addVis_listI_Image} source={{ uri: item.Image1Path }} />}
                                                    </View>
                                                    <TouchableOpacity style={customStyle.addVis_btnRemove} onPress={() => { showRemoveConfirm(item, index) }}>
                                                        <FontAwesome name='trash' size={20} color={'red'} />
                                                    </TouchableOpacity>
                                                </View>


                                            </View>
                                        );
                                    })
                                }
                            </View>
                        </View>

                        <View style={customStyle.addVis_list}>
                            {PreviousVisicooler.length > 0 && <Text style={customStyle.addVis_listhdrText}>{"Previous Visicooler List"}</Text>}
                            <View style={customStyle.addVis_listInner}>
                                {
                                    PreviousVisicooler.length > 0 &&
                                    PreviousVisicooler.map((item, index) => {
                                        console.log(item);
                                        return (
                                            <View key={index} style={[customStyle.addVis_listItem, { backgroundColor: "#cfd3d3" }]}>
                                                <View style={customStyle.addVis_listI_row2}>
                                                    <View style={[customStyle.addVis_listIcol1, { width: "100%" }]}>
                                                        <View style={[customStyle.addVis_listI_row, { borderBottomColor: '#adabab' }]}>
                                                            <Text style={customStyle.addVis_listI_Label}>{'QR Code :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.QRCode}</Text>
                                                        </View>

                                                        <View style={[customStyle.addVis_listI_row, { borderBottomColor: '#adabab' }]}>
                                                            <Text style={[customStyle.addVis_listI_Label, { width: '60%' }]}>{'Asset Code :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.AssetCode}</Text>
                                                        </View>

                                                    </View>
                                                    {
                                                        (item.Image1Path != null && item.Image1Path != '') &&
                                                        <View style={customStyle.addVis_listIcol2}>
                                                            <Text style={[customStyle.addVis_listI_Label2, customStyle.mb20]}>{ST.Image}</Text>
                                                            {(item.Image1Path != null && item.Image1Path != '') && <Image style={customStyle.addVis_listI_Image} source={{ uri: item.Image1Path }} />}
                                                        </View>
                                                    }

                                                </View>

                                            </View>
                                        );
                                    })
                                }
                            </View>
                        </View>
                    </ScrollView>
                }
            </View>
        )
    }

    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            {ConfirmSaveAlert(props, showRemoveConfirm_M, () => { setshowRemoveConfirm_M(false) }, Remove_AddVis, ST.Doyoureallywanttoremovethisvisibility)}
            {ConfirmSaveAlert(props, showRAllC_M, () => { setShowRAllC_M(false) }, onConfirmRemoveAll, ST.Doyoureallywanttoremoveallvisibilitydata)}
            <CustomCamera cameraType={'back'} QRCodeEnable={QREnable} onImageCaptured={(imgData) => { setShowQRCamera(false); onQRScanned(imgData) }} showCamera={showQRCamera} onHideCamera={() => { setShowQRCamera(false); }} />

            <CustomCamera cameraType={'back'} 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, customStyle.zIndex0]}>
                <View style={[customStyle.pageContentWrapper]}>
                    {Object.keys(storeData).length > 0 &&
                        <View style={customStyle.addVis_Wrapper}>
                            {_render_addVisFormTop()}
                        </View>
                    }
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                        <GradientButton {...props} title={ST.Save} onPress={() => { onSubmitData() }} />
                    </View>
                </View>

            </LinearGradient>

        </Container>
    );
}



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