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, AppState, Keyboard } 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 } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, FontAwesome, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import { launchCamera, launchImageLibrary, CameraOptions } from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

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

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';

function CompetitionVisibility(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('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera, setShowSwitchCamera] = useState(false);

    const [AddVisibility, setAddVisibility] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [isAddVisPresent, setIsAddVisPresent] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [Companies, setCompanies] = useState([]);
    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 showCameraRef = React.useRef(false);
    const [getImageProps, setGetImageProps] = useState({});
    const [toRemoveId, setToRemoveId] = useState('');
    const [toRemoveItem, setToRemoveItem] = useState({});
    const [showRemoveConfirm_M, setshowRemoveConfirm_M] = useState(false);
    const [showRAllC_M, setShowRAllC_M] = useState(false);
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [ImgMadCount, setImgMadCount] = useState({ img1: 0, img2: 0 });

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(AddVisibility);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');

    const VisFormDataRef = React.useRef(AddVisFormData);
    const isAddVisPresentRef = React.useRef(isAddVisPresent)

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


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

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

        StoreIdRef.current = storeData1.StoreId
        ScreenNameRef.current = menu1.ScreenName
        getData(storeData1, menu1);

        const AppStateSubscription = AppState.addEventListener('change', (pro) => { _handleAppStateChange(pro) });
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
            AppStateSubscription.remove();
            return unsubscribe;
        };
    }, []);

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

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

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

    function onBeforeRemove(e) {
        if (showCameraRef.current == true) {
            e.preventDefault();
            BgShowCamera(false);
        }
        else {
            if (hasUnsavedChangesRef.current == true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else {
                return;
            }
        }
    }

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

    function BgUnsavedChanges(val) {
        hasUnsavedChangesRef.current = val
        setHasUnsavedChanges(val);
    }

    function BgShowCamera(val) {
        showCameraRef.current = val
        setShowCamera(val);
    }

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

    function BgAddVisFormData(val) {
        VisFormDataRef.current = val
        setAddVisFormData(val);
    }

    function BgIsAddVisPresent(val) {
        isAddVisPresentRef.current = val
        setIsAddVisPresent(val);
    }

    async function OpenImgModal(imgPath, window, splitItem, splitItemIndex, cameraType) {
        setSelectedImg(imgPath)
        setShowModal(true);
        if ((imgPath != '' && imgPath != null)) {
            setShowImageSaveOp(false);
        }
        else {
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({ window, splitItem, splitItemIndex, cameraType })
        // _OpenCaptureImage_Modal(imgPath,window,splitItem,splitItemIndex,cameraType)

    }

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


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

            let AllKPIFields = await getKPIFields(menu1);
            setKPIFields(AllKPIFields);
            // set switch camera flag as defined in mapping menu flag (if exists)
            let SwitchingCameraI = AllKPIFields.findIndex(i => i.KPIFieldName == 'SwitchingCamera');
            let SwitchingCameraObj = SwitchingCameraI >= 0 ? AllKPIFields[SwitchingCameraI] : {};
            let SwitchingCamera = SwitchingCameraI >= 0 ? SwitchingCameraObj['KPIFieldEnable'] : false;
            setShowSwitchCamera(SwitchingCamera);

            let storeBGData1 = [], bgStoreJson = {}, isBgDataExists = false;
            let windData = await get_item('storeData')
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData)
                let { storeBGData, menuName, StoreId1, AddFormData, visiteDate, isVisPresent } = StoreJson
                if (menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                    isBgDataExists = true

                    // Check if isVisPresent data exists in bg data
                    let bgPresent = isVisPresent == 1 ? 1 : 0;
                    Animated.timing(animatedChoice, {
                        toValue: bgPresent,
                        duration: 400,
                        useNativeDriver: false,
                    }).start();
                    BgIsAddVisPresent(bgPresent);


                    // Check if added visibilities data exists in bg data
                    if (storeBGData.length > 0) {
                        storeBGData1 = storeBGData;
                        bgStoreJson = bgStoreJson
                        BgWindowData(storeBGData)
                    }

                    // Check if form data exists in bg data
                    if (AddFormData != null && Object.keys(AddFormData).length > 0) {
                        // BgUnsavedChanges(true)
                        let { CategoryId, SubCategoryId, CompanyId } = AddFormData;
                        // load categories if company exists 
                        if (CategoryId != null && CategoryId != '') {
                            loadData(CompanyId, 'Categories');
                        }
                        // load subcategories if category exists 
                        if (CategoryId != null && CategoryId != '') {
                            loadData(CategoryId, 'SubCategories', CompanyId);
                        }
                        // load brands if subcategory exists 
                        if (SubCategoryId != null && CategoryId != '') {
                            loadData(SubCategoryId, 'Brands', CompanyId);
                        }
                        BgAddVisFormData(AddFormData)
                    }

                    BgUnsavedChanges(true)
                }
            }

            await db.transaction(async function (txn) {

                let q4 = `Select distinct CompanyId,Company from Master_Competitor order by Company`;
                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);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) { setCompanies(arr); }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

                let q2 = `Select Distinct DisplayId,DisplayName from Master_Display where (Competitor='1' or Competitor=1) order by DisplayName`;
                await txn.executeSql(q2, [], 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);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) { setDisplayList(arr); }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);


                let q3 = `Select * from ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_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 { PRESENT, COMPANY, COMPANY_ID, CATEGORY, CATEGORY_ID, SUB_CATEGORY, SUB_CATEGORY_ID, BRAND, BRAND_ID, DISPLAY, DISPLAY_ID, REMARK, IMAGE, KEY_ID } = data;
                            let datan = { Company: COMPANY, CompanyId: COMPANY_ID, CategoryName: CATEGORY, CategoryId: CATEGORY_ID, SubCategoryName: SUB_CATEGORY, SubCategoryId: SUB_CATEGORY_ID, BrandName: BRAND, BrandId: BRAND_ID, DisplayName: DISPLAY, DisplayId: DISPLAY_ID, Remark: REMARK, Image1: IMAGE, keyId: KEY_ID }
                            datan.Image1Path = "file://" + ImageFolderPath + menu1.ScreenName + "/" + IMAGE;
                            PRESENT == 1 ? arr.push(datan) : '';
                            let isPresent = PRESENT;
                            if (i == txnres2.rows.length - 1) {

                                if (!isBgDataExists) {
                                    BgWindowData(arr);
                                    Animated.timing(animatedChoice, {
                                        toValue: isPresent,
                                        duration: 400,
                                        useNativeDriver: false,
                                    }).start();
                                    BgIsAddVisPresent(isPresent);
                                }
                                setProcessing(false);
                            }
                        }
                    } else {
                        setProcessing(false);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); },);



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



    async function getImage(imgdata) {
        let type = getImageProps.type || '';
        if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify('Camera unavailable');
        }
        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('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name = moment(picture_clickedd).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;
            let filename = storeData.StoreId + '_' + (props.UserId || '') + '_CompVisibilityImg-' + calculate_tym_date_for_filename + '.jpg';
            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: Comp. Visibility' + ' | Date:' + calculate_tym_date_over_img;

            let addvisdata = AddVisFormData;
            let image_key = 'Image1';
            let image_path_key = 'Image1Path';
            addvisdata[image_key] = filename;

            // Add MetaData
            let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    // render data with clicked image
                    let uri = 'file://' + imagePath;
                    console.log('image marker', uri);
                    addvisdata[image_path_key] = uri;

                    setSelectedImg(uri)
                    BgAddVisFormData(addvisdata)
                    BgUnsavedChanges(true)
                    setrerenderdata2(!rerenderdata2);
                    // 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('ERROR: image file write failed!!!');
                    console.log(err.message, err.code);
                });
        }

    }

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

                        {!showImageSaveOp &&
                            <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelImage() }}>
                                <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                            </TouchableOpacity>
                        }
                    </View>
                }
            </CustomModal>
        )
    }


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

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

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

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

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

                var values = '';
                if (isAddVisPresent == 1 && AddVisibility.length > 0) {
                    for (var i = 0; i < AddVisibility.length; i++) {
                        let catIndex = i;
                        let item = AddVisibility[catIndex];
                        let { Company, CompanyId, CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, Remark, Image1, Image1Path } = item;
                        values += values != '' ? ' , ' : '';
                        values += ` ('${StoreId}','${d2}','${isAddVisPresent}','${Company}','${CompanyId}','${CategoryName}','${CategoryId}','${SubCategoryName}','${SubCategoryId}','${BrandName}','${BrandId}','${DisplayName}','${DisplayId}','${Remark}','${Image1}','${d2}') `;

                    }
                }
                else {
                    values += ` ('${StoreId}','${d2}','${isAddVisPresent}','','','','','','','','','','','','','${d2}') `;
                }

                console.log('values:', values);
                let add_data = `INSERT INTO ${AppTables.COMPETITION_VISIBILITY} (STORE_ID,VISIT_DATE,PRESENT,COMPANY,COMPANY_ID,CATEGORY,CATEGORY_ID,SUB_CATEGORY,SUB_CATEGORY_ID,BRAND,BRAND_ID,DISPLAY,DISPLAY_ID,REMARK,IMAGE,ADDED_DATE) VALUES ${values} `;

                await txn.executeSql(add_data, [], async function (txn2, txnres) {
                    console.log('av added');
                    notify('Competition Visibility added successfully', 'SHORT');
                    setProcessing(false);
                    // clear store data in local storage to avoiding re-set data for the store  
                    clear_item('storeData')
                    props.navigation.goBack();
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot add competition visibility') },);


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




    async function validate() {

        let isValid = true;
        if (isAddVisPresent == 1 && AddVisibility.length <= 0) {
            isValid = false;
            notify('Please add first', 'SHORT');
        }

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

    async function validateForm() {
        let isValid = true;
        let { Company, CompanyId, CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, Remark, Image1, Image1Path } = AddVisFormData;

        let AddVisCameraReqI = KPIFields.findIndex(i => i.KPIFieldName == 'CompVisCameraReq');
        let AddVisCameraReqObj = AddVisCameraReqI >= 0 ? KPIFields[AddVisCameraReqI] : {};
        let CompVisCameraReq = AddVisCameraReqI >= 0 ? AddVisCameraReqObj['KPIFieldEnable'] : true;



        if ((Company == '' || Company == null) || (CompanyId == '' || CompanyId == null)) {
            isValid = false;
            notify('Please select company', 'SHORT');
        }
        else if ((CategoryName == '' || CategoryName == null) || (CategoryId == '' || CategoryId == null)) {
            isValid = false;
            notify('Please select category', 'SHORT');
        }
        else if ((SubCategoryName == '' || SubCategoryName == null) || (SubCategoryId == '' || SubCategoryId == null)) {
            isValid = false;
            notify('Please select sub category', 'SHORT');
        }
        else if ((BrandName == '' || BrandName == null) || (BrandId == '' || BrandId == null)) {
            isValid = false;
            notify('Please select brand', 'SHORT');
        }
        else if ((DisplayName == '' || DisplayName == null) || (DisplayId == '' || DisplayId == null)) {
            isValid = false;
            notify('Please select display type', 'SHORT');
        }
        // else if((Remark=='' || Remark==null )){
        //     isValid=false;
        //     notify('Please enter remark','SHORT');
        // }
        else if (StoreCameraAllow && CompVisCameraReq && (Image1 == '' || Image1 == null)) {
            isValid = false;
            notify('Please click image', 'SHORT');
        }


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

    function onFormDataChange(val, key, type = '') {
        if (val != '') {
            let isValid = validateNumber(val, type);
            if (!isValid) {
                return;
            }
        }

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

    function onselectionChange(option, keyLbl, keyVal, otherData) {
        let CompanyId = otherData.CompanyId != null ? otherData.CompanyId : '';
        let data = AddVisFormData;
        data[keyVal] = option.value;
        data[keyLbl] = option.label;
        // setAddVisFormData(data);
        // setHasUnsavedChanges(true);
        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        CleanSelector(option, keyLbl, data, CompanyId)
        setrerenderdata(!rerenderdata);


    }

    function CleanSelector(option, keyLbl = '', data = {}, CompanyId) {

        if (keyLbl == 'Company') {
            loadData(option.value, 'Categories');

            data['CategoryId'] = '';
            data['CategoryName'] = '';
            data['SubCategoryId'] = '';
            data['SubCategoryName'] = '';
            data['BrandId'] = '';
            data['BrandName'] = '';

            data['DisplayId'] = ''
            data['DisplayName'] = ''

            data['Image1Path'] = ''

            data['Remark'] = ''
        }
        else if (keyLbl == 'CategoryName') {
            console.log('CompanyId:', CompanyId);
            loadData(option.value, 'SubCategories', CompanyId);

            data['SubCategoryId'] = '';
            data['SubCategoryName'] = '';
            data['BrandId'] = '';
            data['BrandName'] = '';

            data['DisplayId'] = ''
            data['DisplayName'] = ''

            data['Image1Path'] = ''

            data['Remark'] = ''
        }
        else if (keyLbl == 'SubCategoryName') {
            console.log('CompanyId:', CompanyId,option.value,CompanyId);
            loadData(option.value, 'Brands', CompanyId);

            data['BrandId'] = '';
            data['BrandName'] = '';

            data['DisplayId'] = ''
            data['DisplayName'] = ''

            data['Image1Path'] = ''

            data['Remark'] = ''
        } else if (keyLbl == 'BrandName') {

            // clear brand

            data['DisplayId'] = ''
            data['DisplayName'] = ''

            data['Image1Path'] = ''

            data['Remark'] = ''

        } else if (keyLbl == 'DisplayName') {

            // clear brand

            data['Image1Path'] = ''

            data['Remark'] = ''

        }
        setrerenderdata(!rerenderdata);
    }

    async function loadData(qId, type, CompanyId) {
        try {
            console.log("load_data",qId,CompanyId)
            await db.transaction(async function (txn) {
                let q = '';
                if (type == 'Categories') q = `select distinct CategoryId,CategoryName from Master_Competitor where (CompanyId ='${qId}' or CompanyId = ${qId}) order by CategoryName`;
                else if (type == 'SubCategories') q = `Select Distinct p.SubCategoryId,p.SubCategoryName from Product_Master p where (p.CategoryId='${qId}' or p.CategoryId=${qId}) and (CompanyId ='${CompanyId}' or CompanyId = ${CompanyId}) 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 (CompanyId ='${CompanyId}' or CompanyId = ${CompanyId}) order by p.BrandSequence`;

                console.log("qury---",type,q);
                await txn.executeSql(q, [], 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);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                if (type == 'Categories') setCategories(arr);
                                else if (type == 'SubCategories') setSubCategories(arr);
                                else if (type == 'Brands') setBrands(arr);
                            }
                        }
                    }
                }, function (txnE, 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);
        BgIsAddVisPresent(val);
        BgUnsavedChanges(true)
        if (val == 0) {
            // setAddVisibility([]);
            // setAddVisFormData({});
            BgWindowData([])
            BgAddVisFormData({})
        }
    }

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

    function onSaveCancel() {
        setShowAlert(false);
    }

    async function Add_AddVis() {
        let isValid = await validateForm();
        console.log('isValid add:', isValid);
        if (isValid) {
            let arr = AddVisibility;
            let { Company, CompanyId, CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, Remark, Image1, Image1Path } = AddVisFormData;
            console.log(AddVisFormData);
            // let index=AddVisibility.findIndex(i=> i.CompanyId==CompanyId && i.CategoryId==CategoryId && i.SubCategoryId==SubCategoryId && i.BrandId==BrandId && i.DisplayId==DisplayId);
            // if(index>=0){
            //     notify('This visibility has already been added','LONG');
            // }
            // else{
            arr.push(AddVisFormData);
            // setAddVisibility(arr);
            // setHasUnsavedChanges(true);
            BgWindowData(arr)
            BgUnsavedChanges(true)
            notify('Visibility added successfully', 'LONG');
            setrerenderdata(!rerenderdata);

            // clear data
            // setAddVisFormData({});
            // setFromDate('');
            BgAddVisFormData({})
            // }
        }

    }

    function showRemoveConfirm(item, index) {
        // setToRemoveId(index);
        // setToRemoveItem(item);
        // setshowRemoveConfirm_M(true);
        if (item.keyId > 0) {
            setToRemoveId(item.keyId);
            setToRemoveItem(item);
            setshowRemoveConfirm_M(true);
        }
        else {
            setToRemoveId(index);
            setToRemoveItem(item);
            setshowRemoveConfirm_M(true);
        }
    }

    // function showRemoveConfirm(item,index){
    //     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(arr);
    //         // setHasUnsavedChanges(true);
    //         BgWindowData(AddVisibility)
    //         BgUnsavedChanges(true)
    //         notify('Visibility removed successfully','LONG')
    //         setrerenderdata(!rerenderdata);
    //     }
    //     else{
    //         notify('Cannot remove! Visibility not found','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 (item.keyId != null && item.keyId != 'undefined' && index > 0) {
                console.log("check-keyId-", index)
                let deleteQuery = `DELETE FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' AND KEY_ID='${index}' `;

                txn.executeSql(deleteQuery, [], function (txn3, txnres) {
                    console.log('Visibility data deleted', item.keyId, +"" + index);
                    let updatedVisibility = AddVisibility.filter(item => item.keyId !== index);
                    setAddVisibility(updatedVisibility);
                    setHasUnsavedChanges(true);
                    notify('Visibility 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('Visibility removed successfully', 'LONG')
                    setrerenderdata(!rerenderdata);
                }
                else {
                    notify('Cannot remove! Visibility 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],
            });
        }

        let AddVisCameraReqI = KPIFields.findIndex(i => i.KPIFieldName == 'CompVisCameraReq');
        let AddVisCameraReqObj = AddVisCameraReqI >= 0 ? KPIFields[AddVisCameraReqI] : {};
        let CompVisCameraReq = AddVisCameraReqI >= 0 ? AddVisCameraReqObj['KPIFieldEnable'] : true;




        return (
            <View style={[customStyle.addvisCon]}>
                <View style={[customStyle.addvis_pCon]}>
                    <Text style={[customStyle.addvis_pText]}>{'Is Present'}</Text>
                    <View style={customStyle.addvis_pChoiceBoxCon}>
                        <View style={[customStyle.openStk_prd_choiceBox, customStyle.addvis_pChoiceBoxbg]}>
                            <Animated.View style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, (isAddVisPresent == '1' ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red),
                            {
                                transform: [{
                                    translateX: xpos
                                }],
                            }
                            ]}></Animated.View>
                            <TouchableOpacity style={customStyle.openStkCh_con1} onPress={() => { onChoiceSelect(1, 'isPresent') }}>
                                <Text style={[customStyle.openStkCh_text, (isAddVisPresent == 1 ? customStyle.openStkCh_textactive : {})]}>Yes</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(0, 'isPresent') }}>
                                <Text style={[customStyle.openStkCh_text, (isAddVisPresent == 0 ? customStyle.openStkCh_textactive : {})]}>No</Text>
                            </TouchableOpacity>
                        </View>
                    </View>

                </View>
                {
                    isAddVisPresent == 1 && (rerenderdata == rerenderdata) &&
                    <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.addVisScroll}>
                        <View style={customStyle.addVisForm}>
                            <View style={customStyle.addVisRow}>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>Company</Text>
                                        {CustomPicker(props, Companies, 'Company', 'CompanyId', 'Company', 'CompanyId', onselectionChange, { value: AddVisFormData.Company, otherData: {} })}
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol2]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>Category</Text>
                                        {CustomPicker(props, Categories, 'CategoryName', 'CategoryId', 'CategoryName', 'CategoryId', onselectionChange, { value: AddVisFormData.CategoryName, otherData: { 'CompanyId': AddVisFormData.CompanyId != null ? AddVisFormData.CompanyId : '' } })}

                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>Sub Category</Text>

                                        {CustomPicker(props, SubCategories, 'SubCategoryName', 'SubCategoryId', 'SubCategoryName', 'SubCategoryId', onselectionChange, { value: AddVisFormData.SubCategoryName, otherData: { 'CompanyId': AddVisFormData.CompanyId != null ? AddVisFormData.CompanyId : '' } })}
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol2]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>Brands</Text>

                                        {CustomPicker(props, Brands, 'BrandName', 'BrandId', 'BrandName', 'BrandId', onselectionChange, { value: AddVisFormData.BrandName })}
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>Display Type</Text>
                                        {CustomPicker(props, DisplayList, 'DisplayName', 'DisplayId', 'DisplayName', 'DisplayId', onselectionChange, { value: AddVisFormData.DisplayName })}
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol2]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>Remark</Text>
                                        <TextInput
                                            style={customStyle.addVisInputStyle}
                                            value={(AddVisFormData.Remark || '')}
                                            autoComplete='off'
                                            onChangeText={(val) => { onFormDataChange(val, 'Remark', 'text'); }}
                                        />
                                    </View>
                                </View>
                                {CompVisCameraReq &&
                                    <View style={[customStyle.addVisCol100]}>
                                        <View style={customStyle.addVisFormGrp}>
                                            <Text style={customStyle.addVisLabel}>Image</Text>
                                            <View style={customStyle.addVisCameras}>
                                                <View style={customStyle.openStkCameraCon}>

                                                    {(AddVisFormData.Image1Path == '' || AddVisFormData.Image1Path == null) ?
                                                        <TouchableOpacity onPress={() => { openCamera('1') }}>
                                                            <CameraImg5 width={50} height={50} />
                                                        </TouchableOpacity> : (AddVisFormData.Image1Path != '' && AddVisFormData.Image1Path != null) ?
                                                            <TouchableOpacity onPress={() => { OpenImgModal(AddVisFormData.Image1Path, '1') }}>
                                                                <CameraImg3 width={50} height={50} />
                                                            </TouchableOpacity> : null
                                                    }
                                                </View>

                                            </View>
                                        </View>
                                    </View>}
                                <View style={customStyle.addVis_btnWrap}>
                                    <TouchableOpacity style={customStyle.addVis_btn} onPress={() => { Add_AddVis() }}>
                                        <Text style={customStyle.addVisBtnText}>Add</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                        <View style={customStyle.addVis_list}>
                            <Text style={customStyle.addVis_listhdrText}>Added Visibilities</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={[CompVisCameraReq ? customStyle.addVis_listIcol1 : customStyle.addVis_listIcol100]}>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>Company :</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.Company}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>Category :</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.CategoryName}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>Sub Category :</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.SubCategoryName}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>Brand :</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.BrandName}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>Display Type :</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.DisplayName}</Text>
                                                        </View>
                                                        <View style={[customStyle.addVis_listI_row, customStyle.addVis_listI_lastrow]}>
                                                            <Text style={customStyle.addVis_listI_Label}>Remark :</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.Remark}</Text>
                                                        </View>
                                                    </View>
                                                    {CompVisCameraReq &&
                                                        <View style={customStyle.addVis_listIcol2}>
                                                            {/* <View style={[customStyle.addVis_listI_row,customStyle.addVis_listI_lastrow]}> */}
                                                            <Text style={[customStyle.addVis_listI_Label2, customStyle.mb20]}>Image</Text>
                                                            {(item.Image1Path != null && item.Image1Path != '') && <Image style={customStyle.addVis_listI_Image} source={{ uri: item.Image1Path }} />}
                                                            {/* </View> */}
                                                        </View>}
                                                    <TouchableOpacity style={customStyle.addVis_btnRemove} onPress={() => { showRemoveConfirm(item, index) }}>
                                                        <FontAwesome name='trash' size={20} color={'red'} />
                                                    </TouchableOpacity>
                                                </View>


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

    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <View style={{ zIndex: 10 }}>
                <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            </View>
            {_OpenCaptureImage_Modal()}
            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            {ConfirmSaveAlert(props, showRemoveConfirm_M, () => { setshowRemoveConfirm_M(false) }, Remove_AddVis, 'Do you really want to remove this visibility?')}
            {ConfirmSaveAlert(props, showRAllC_M, () => { setShowRAllC_M(false) }, onConfirmRemoveAll, 'Do you really want to remove all visibility data?')}
            <CustomCamera cameraType={'back'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: ' + currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData) => { BgShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { BgShowCamera(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={'Save'} onPress={() => { onSubmitData() }} />
                    </View>
                </View>

            </LinearGradient>

        </Container>
    );
}



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