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, StyleSheet, Modal } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import { notify } from '../components/notify';
import moment from 'moment';
import { getDownloadJson, getKPIFields, marktext1, marktext2, 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 { Card, Menu, Switch } from 'react-native-paper';
import { AntDesign, Entypo, FontAwesome, Fontisto, 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 CustomModal from '../components/CustomModal';
import { ConfirmSaveAlert } from '../components/alert';
import { CustomPicker } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import DateTimePicker from '@react-native-community/datetimepicker';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';
import DateTimePickerModal from "react-native-modal-datetime-picker";
import CheckBox from '@react-native-community/checkbox';
import { log } from '@react-native-firebase/crashlytics';


function AdditionalVisibility(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 [ShowDatePicker1, setShowDatePicker1] = useState(false);
    const [ShowDatePicker, setShowDatePicker] = useState(false);
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);

    const [AddVisibility, setAddVisibility] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({ AssertCount: 1 });
    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 [StockList, setStockList] = 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 [KPIFields, setKPIFields] = useState([]);
    const [dateValue, setDateValue] = useState('');
    const [FromDate, setFromDate] = useState('');
    const [FromDate2, setFromDate2] = useState("");
    const [FromDateObj, setFromDateObj] = useState({});
    const [ToDate, setToDate] = useState('');
    const [ToDate2, setToDate2] = useState(new Date());
    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 [showSwitchCamera, setShowSwitchCamera] = useState(false);
    const [productCheck, setProductCheck] = useState(false);
    const [selectedItems, setSelectedItems] = useState({});
    const [dialogVisible, setDialogVisible] = useState(false);
    const [selectedItem, setSelectedItem] = useState(null);
    const VisFormDataRef = React.useRef(AddVisFormData);
    const isAddVisPresentRef = React.useRef(isAddVisPresent);
    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;
        StoreIdRef.current = storeData1.StoreId
        ScreenNameRef.current = menu1.ScreenName
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
        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;
        };
    }, []);

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

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

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

    function BgUnsavedChanges(val) {
        hasUnsavedChangesRef.current = val
        setHasUnsavedChanges(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);
    }


    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: async () => {
                        BgUnsavedChanges(false)
                        await clear_item('storeData')
                        // setHasUnsavedChanges(false);
                        props.navigation.dispatch(e.data.action);
                    }
                }
            ]
        );
    }

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

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

            let isProductCheckIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'ProductCheck');
            let isProductCheckObj = isFromDateIndex >= 0 ? AllKPIFields[isProductCheckIndex] : {};
            let isProductCheckEnable = isFromDateIndex >= 0 ? isProductCheckObj['KPIFieldEnable'] : true;
            setProductCheck(isProductCheckEnable)
            let isFromDateIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
            let isFromDateKPIObj = isFromDateIndex >= 0 ? AllKPIFields[isFromDateIndex] : {};
            let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;
            let isToDateIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'ShowToDate');
            let isToDateKPIObj = isToDateIndex >= 0 ? AllKPIFields[isToDateIndex] : {};
            let isToDateEnable = isToDateIndex >= 0 ? isToDateKPIObj['KPIFieldEnable'] : true;
            // 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')
            console.log("bg storeData:", windData);
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData)
                let { storeBGData, menuName, StoreId1, AddFormData, visiteDate } = StoreJson
                if (menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                    isBgDataExists = true;
                    bgStoreJson = StoreJson
                    if (storeBGData.length > 0) {
                        storeBGData1 = storeBGData;
                        BgWindowData(storeBGData)
                    }

                    if (AddFormData != null && Object.keys(AddFormData).length > 0) {
                        let { CategoryId, BrandId, DisplayId, SubCategoryId, FromDate, ToDate, StockList } = AddFormData;
                        // load subcategories if category exists 
                        console.log("AddFormData------",JSON.stringify(AddFormData))
                        if (CategoryId != null && CategoryId != '') {
                            loadData(CategoryId, 'SubCategories');
                        }
                        if (SubCategoryId != null && CategoryId != '') {
                            loadData(SubCategoryId, 'Brands');
                        }
                        if (FromDate != null && FromDate != '') {
                            setFromDate(FromDate);
                            setFromDate2(new Date(FromDate));
                        }
                        if (ToDate != null && ToDate != '') {
                            setToDate(ToDate);
                            setToDate2(new Date(ToDate));
                        }

                        if (BrandId != null && BrandId != '' && DisplayId != null && DisplayId != '' && isProductCheckEnable) {
                            console.log("called", BrandId, DisplayId);
                            getStock(BrandId, DisplayId, StockList);
                        }
                        BgAddVisFormData(AddFormData)
                    }
                    BgUnsavedChanges(true)
                }
            }
            await db.transaction(async function (txn) {

                let q = `Select Distinct p.CategoryId,p.CategoryName from Product_Master p where (p.IsCompetitor='0' or p.IsCompetitor=0) order by p.CategorySequence`;
                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) { setCategories(arr); }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);


                let q2 = `Select Distinct DisplayId,DisplayName from Master_Display where Additional='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.ADDITIONAL_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, CATEGORY, CATEGORY_ID, SUB_CATEGORY, SUB_CATEGORY_ID, BRAND, BRAND_ID, DISPLAY, DISPLAY_ID, ASSERT_COUNT, REMARK, IMAGE, FROM_DATE, TO_DATE, SHOWFROMDATE, KEY_ID } = data;
                            let datan = { CategoryName: CATEGORY, CategoryId: CATEGORY_ID, SubCategoryName: SUB_CATEGORY, SubCategoryId: SUB_CATEGORY_ID, BrandName: BRAND, BrandId: BRAND_ID, DisplayName: DISPLAY, DisplayId: DISPLAY_ID, AssertCount: ASSERT_COUNT, Remark: REMARK, Image1: IMAGE, FromDate: String(FROM_DATE), ToDate: String(TO_DATE), showFromDateFlag: SHOWFROMDATE, keyId: KEY_ID }
                            datan.Image1Path = IMAGE != '' ? 'file://' + ImageFolderPath + menu1.ScreenName + "/" + IMAGE : '';
                            let isPresent = PRESENT;
                            if (isPresent == 1) {
                                try {

                                    const stockList = await getAdditionalVisibilityStock({
                                        StoreId,
                                        d2,
                                        CATEGORY_ID,
                                        BRAND_ID,
                                        DISPLAY_ID
                                    });
                                    console.log("Final stock list:", stockList);
                                    datan['StockList'] = stockList;
                                    arr.push(datan)
                                    // Do something with stockList here
                                } catch (err) {
                                    console.error("Failed to fetch stock list:", err);
                                }
                            }

                            if (i == txnres2.rows.length - 1) {
                                let { menuName, StoreId1, isVisPresent, visiteDate } = bgStoreJson

                                if (!isBgDataExists) {
                                    BgWindowData(arr);
                                }
                                else {
                                    isPresent = isVisPresent == 1 ? 1 : 0;
                                }


                                Animated.timing(animatedChoice, {
                                    toValue: isPresent,
                                    duration: 400,
                                    useNativeDriver: false,
                                }).start();

                                BgIsAddVisPresent(isPresent);
                                // setAddVisibility(arr);
                                setProcessing(false);
                            }
                        }
                    }
                    else {

                        if (isBgDataExists) {
                            let { isVisPresent } = bgStoreJson
                            let isPresent = isVisPresent == 1 ? 1 : 0;
                            Animated.timing(animatedChoice, {
                                toValue: isPresent,
                                duration: 400,
                                useNativeDriver: false,
                            }).start();
                            BgIsAddVisPresent(isPresent);

                        }
                        setProcessing(false);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); },);

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

    async function getAdditionalVisibilityStock({
        StoreId,
        d2,
        CATEGORY_ID,
        BRAND_ID,
        DISPLAY_ID
    }) {
        const stkq = `SELECT DISTINCT DISPLAY_ID as DisplayId,CATEGORY_ID as CategoryId,SUB_CATEGORY_ID as SubCategoryId,BRAND_ID as BrandId,PRODUCT_ID as ProductId,PRODUCT_NAME as ProductName,STOCK_REQ as StockRequire,STOCK as Stock,IS_SELECT as isSelect FROM ${AppTables.ADDITIONAL_VISIBILITY_STOCK} WHERE STORE_ID='${StoreId}' AND VISIT_DATE='${d2}' AND CATEGORY_ID='${CATEGORY_ID}' AND BRAND_ID='${BRAND_ID}' AND DISPLAY_ID='${DISPLAY_ID}'`;

        console.log("stk_query", stkq);

        return new Promise((resolve, reject) => {
            db.transaction(txn => {
                txn.executeSql(
                    stkq,
                    [],
                    (txn2, txnres5) => {
                        const arrstk = [];
                        console.log("stk_query rows:", txnres5.rows.length);
                        for (let i = 0; i < txnres5.rows.length; i++) {
                            arrstk.push(txnres5.rows.item(i));
                        }

                        resolve(arrstk);
                    },
                    (txnE, txnerr) => {
                        console.error("SQL error:", txnerr);
                        reject(txnerr); // reject the promise on error
                        return true;
                    }
                );
            });
        });
    }


    async function getStock(brandId, displayId, StockList) {
        try {
            console.log("Anitaaaaa")
            console.log(brandId, displayId, StockList, "get stock data ");
            if (StockList != null && StockList != undefined && StockList?.length > 0) {
                setStockList(StockList);
            } else {
                await db.transaction(async function (txn) {
                    let q4 = `SELECT T.*,P.ProductName from Mapping_AdditionalVisibilityProduct T inner join Product_Master P on P.ProductId = T.ProductId inner join Master_Display D on D.DisplayId = T.DisplayId Where (T.DisplayId = '${displayId}' or T.DisplayId = ${displayId})  and (P.BrandId = '${brandId}' or P.BrandId = ${brandId})`;
                    console.log("query stock data", q4)
                    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);
                                console.log("stock_items", data);

                                data['isSelect'] = 0
                                data['Stock'] = ""
                                arr.push(data);
                                if (i === txnres2.rows.length - 1) {
                                    let data1 = AddVisFormData;
                                    data1['StockList'] = arr;
                                    setStockList(arr);
                                    BgAddVisFormData(data1)
                                }
                            }
                        }
                    }, function (txnE, txnerr) {
                        console.log(txnerr);
                    });
                });
            }
        } catch (err) {
            console.log(err);
        }
    }


    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 })
        console.log("checkrecapmodal-->", reCapImgModalObj, "---" + window)
        // _OpenCaptureImage_Modal(imgPath,window,splitItem,splitItemIndex,cameraType)

    }

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

    async function getImage(imgdata) {
        if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify(ST.Cameraunavailable);
        }
        else if (typeof imgdata == 'object' && imgdata.uri != null) {
            const img = imgdata;
            const imgurl = img.uri, imgWidth = img.width, imgHeight = img.ExtendedHeight;
            let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
            let picture_clickedd = isImgFromGallery == true ? img.datetime : new Date();
            ////change by jeevanp
            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);
            ////change by jeevanp
            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 || '') + '_AddVisibilityImg-' + calculate_tym_date_for_filename + '.jpg';
            console.log("filename=>", filename)
            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;

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

            let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    // render data with clicked image
                    let uri = 'file://' + imagePath;
                    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) {
        console.log("checkmodal--", showImageSaveOp)
        const isImageCap = (img != '' || img != null) ? true : false;
        // console.log("imag pop is trigger",isImageCap,showModal,img)
        let { window, splitItem, splitItemIndex, cameraType } = reCapImgModalObj
        let camera2Label = (window && window.PromoImage2Lable) || '';
        return (
            <CustomModal
                style={customStyle.PromoImgModal}
                title={"Additional Visibility 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') {
        console.log('openCamera');
        setClickImageType(type);
        setShowCamera(true);
    }

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

    async function saveData() {
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(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.ADDITIONAL_VISIBILITY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                //  remove old data
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('av data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);

                let q1 = `DELETE FROM ${AppTables.ADDITIONAL_VISIBILITY_STOCK} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                //  remove old data
                await txn.executeSql(q1, [], async function (txn2, txnres) {
                    console.log('ADDITIONAL_VISIBILITY_STOCK data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);

                var values = '', stkValues = '';
                let isFromDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
                let isFromDateKPIObj = isFromDateIndex >= 0 ? KPIFields[isFromDateIndex] : {};
                let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;

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

                        console.log("saveStocks", JSON.stringify(AddVisibility));

                        if (item?.StockList != null && item?.StockList != undefined && item?.StockList.length > 0) {
                            for (let k = 0; k < item?.StockList.length; k++) {
                                let stkIndex = k;
                                let stkitem = item?.StockList[stkIndex];
                                let { ProductId, ProductName, Stock, StockRequire, isSelect } = stkitem;
                                stkValues += stkValues != '' ? ' , ' : '';
                                stkValues += ` ('${StoreId}','${d2}','${CategoryId}','${SubCategoryId}','${BrandId}','${DisplayId}','${ProductId}','${ProductName}', '${(StockRequire == true || StockRequire === "true" ? 1 : 0)}','${(Stock == '' ? 0 : Stock)}','${isSelect}') `;
                            }
                        }
                    }
                }
                else {
                    values += ` ('${StoreId}','${d2}','${isAddVisPresent}','','','','','','','','','1','','','1','','','false','${d2}') `;
                }

                console.log('values additional_visibility:', values);
                let add_data = `INSERT INTO ${AppTables.ADDITIONAL_VISIBILITY} (STORE_ID,VISIT_DATE,PRESENT,CATEGORY,CATEGORY_ID,SUB_CATEGORY,SUB_CATEGORY_ID,BRAND,BRAND_ID,DISPLAY,DISPLAY_ID,ASSERT_COUNT,REMARK,IMAGE,IS_UPDATED,FROM_DATE,TO_DATE,SHOWFROMDATE,ADDED_DATE) VALUES ${values} `;

                await txn.executeSql(add_data, [], async function (txn2, txnres) {
                    console.log('av added');
                    console.log('values additional_visibility:', stkValues);
                    let add_Stk_data = `INSERT INTO ${AppTables.ADDITIONAL_VISIBILITY_STOCK} (STORE_ID,VISIT_DATE,CATEGORY_ID,SUB_CATEGORY_ID,BRAND_ID,DISPLAY_ID,PRODUCT_ID,PRODUCT_NAME,STOCK_REQ,STOCK,IS_SELECT) VALUES ${stkValues} `;
                    await txn.executeSql(add_Stk_data, [], async function (txn2, txnres) {
                        console.log('avStk added');
                    }, function (txnE, txnerr) {
                        console.log(txnerr);
                    },);
                    notify(ST.AdditionalVisibilityaddedsuccessfully, '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(ST.Cannotaddadditionalvisibility)
                },);
            });
        } catch (err) {
            console.log(err);
        }
    }




    async function validate() {
        let isValid = true;
        if (isAddVisPresent == 1 && AddVisibility.length <= 0) {
            isValid = false;
            notify(ST.Pleaseaddfirst, 'SHORT');
        }

        console.log('isValid----:', isValid + "\n" + JSON.stringify(AddVisibility));
        return isValid;
    }

    function validateStock(products) {
        // Ensure at least one product is selected
        const selectedItems = products.filter(item => item.isSelect === 1);
        if (selectedItems.length === 0) {
            notify('At least one product must be selected', 'SHORT');
            console.warn("At least one product must be selected.");
            return false;
        }

        // Check if any selected item requires stock but has no stock value
        const invalidItems = selectedItems.filter(item =>
            (item?.StockRequire === "true" || item?.StockRequire === true || item?.StockRequire === 1) &&
            (!item?.Stock || item?.Stock?.trim() === "")
        );

        if (invalidItems.length > 0) {
            notify('Please Enter Stock', 'SHORT');
            console.warn("Stock value is missing for required items:", invalidItems);
            return false;
        }

        return true;
    }


    async function validateForm() {
        let isValid = true;
        let { CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, AssertCount, Remark, Image1, Image1Path, FromDate, ToDate, showFromDateFlag, StockList } = AddVisFormData;

        console.log("StockList----", StockList);

        let isFromDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
        let isFromDateKPIObj = isFromDateIndex >= 0 ? KPIFields[isFromDateIndex] : {};
        let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;

        let isToDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowToDate');
        let isToDateKPIObj = isToDateIndex >= 0 ? KPIFields[isToDateIndex] : {};
        let isToDateEnable = isToDateIndex >= 0 ? isToDateKPIObj['KPIFieldEnable'] : true;

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


        if ((CategoryName == '' || CategoryName == null) || (CategoryId == '' || CategoryId == null)) {
            isValid = false;
            notify(ST.PleaseSelectCategory, 'SHORT');
        }
        else if ((SubCategoryName == '' || SubCategoryName == null) || (SubCategoryId == '' || SubCategoryId == null)) {
            isValid = false;
            notify(ST.Pleaseselectsubcategory, 'SHORT');
        }
        else if ((BrandName == '' || BrandName == null) || (BrandId == '' || BrandId == null)) {
            isValid = false;
            notify(ST.Pleaseselectbrand, 'SHORT');
        }
        else if ((DisplayName == '' || DisplayName == null) || (DisplayId == '' || DisplayId == null)) {
            isValid = false;
            notify(ST.Pleaseselectdisplaytype, 'SHORT');
        } else if (AssertCount == 0) {
            isValid = false;
            notify("Please fill the Asset Count minimum 1", 'SHORT');
        } else if (isFromDateEnable == true && !AddVisFormData.hasOwnProperty("FromDate") && (FromDate == '' || FromDate == null)) {
            isValid = false;
            notify('Please Select The From Date ', 'SHORT');
        } else if (isToDateEnable == true && !AddVisFormData.hasOwnProperty("ToDate") && (ToDate == '' || ToDate == null)) {
            isValid = false;
            notify('Please Select The To Date ', 'SHORT');
        }
        else if (StoreCameraAllow == true && AddVisCameraReq && (Image1 == '' || Image1 == null)) {
            isValid = false;
            notify(ST.Pleaseclickimage, 'SHORT');
        } else if (StockList != null && StockList != undefined && StockList?.length > 0 && !validateStock(StockList)) {
            isValid = false;
        }

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

    function onFormDataChange(val, key, type = '') {
        if (val != '') {
            let isValid = validateNumber(val, type);
            if (!isValid) {
                return;
            }
        }
        // ✅ Clone the object to create a new reference
        let data = { ...AddVisFormData };
        data[key] = val;
        console.log("DatePicket_data", data);

        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function StockDataChange(val, key, type = '', item) {
        console.log(item, "itemmmstockk====");

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


        // Update the correct item in the Stock array
        let updatedStock = AddVisFormData?.StockList?.map(itm => {
            if (itm.ProductId == item.ProductId) {
                let obj = {
                    ...itm,
                    [key === 'Stock' ? 'Stock' : 'isSelect']: val
                };
                if (key == 'isSelect') {
                    obj["Stock"] = ""
                }

                return obj
            }
            return itm;
        });

        console.log("updatedStock ===", updatedStock);

        let updatedData = {
            ...AddVisFormData,
            StockList: updatedStock
        };

        BgAddVisFormData(updatedData);
        BgUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }


    function onselectionChange(option, keyLbl, keyVal) {
        let data = AddVisFormData;
        data[keyVal] = option.value;
        data[keyLbl] = option.label;
        console.log("jeevanp----", data);


        console.log(option, keyLbl, keyVal, "option, keyLbl, keyVal")
        CleanSelector(option, keyLbl, data)
        if (data.BrandId && data.DisplayId && productCheck) {
            getStock(data.BrandId, data.DisplayId, null);
        }
        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

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

            data['DisplayId'] = ''
            data['DisplayName'] = ''
            data['Remark'] = ''
            data['Image1Path'] = ''

            setToDate('');
            setToDate2("");
            // setToDate2(new Date(null));

            setFromDate('');
            setFromDate2('');
            // data['FromDate']='';
        }
        else if (keyLbl == 'SubCategoryName') {
            loadData(option.value, 'Brands');

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

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

            data['Image1Path'] = ''

            data['Remark'] = ''

            setToDate('');
            setToDate2("")

            setFromDate('');
            setFromDate2('');
        } else if (keyLbl == 'BrandName') {

            // clear brand

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

            data['Image1Path'] = ''

            data['Remark'] = ''

            setToDate('');
            setToDate2("")

            setFromDate('');
            setFromDate2('');
        } else if (keyLbl == 'DisplayName') {

            // clear brand

            data['Image1Path'] = ''

            data['Remark'] = ''

            setToDate('');
            setToDate2("")

            setFromDate('');
            setFromDate2('');;
        }

    }

    function CleanSelectorYes() {
        let data = AddVisFormData;

        // clear subcategory and brand
        data['SubCategoryId'] = '';
        data['SubCategoryName'] = '';
        data['BrandId'] = '';
        data['BrandName'] = '';


        data['DisplayId'] = ''
        data['DisplayName'] = ''
        data['Remark'] = ''
        data['Image1Path'] = ''

        setToDate('');
        setToDate2("")

        setFromDate('');
        setFromDate2('');
        BgAddVisFormData(data)
        // data['FromDate']='';


    }
    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 (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);
        if (val == 0) {
            CleanSelectorYes()
        }
        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 { CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, Remark, Image1, Image1Path, StockList } = AddVisFormData;
            let formData = AddVisFormData;
            if (StockList != null && StockList != undefined && StockList.length > 0) {
                const filteredList = StockList?.filter(
                    (stock) => stock.isSelect === 1
                );
                // ✅ Replace StockList in AddVisFormData
                formData = {
                    ...AddVisFormData,
                    StockList: filteredList,
                };
            }
            console.log("temp_sdf", JSON.stringify(formData));
            arr.push(formData);
            console.log("temp_sdf", JSON.stringify(arr));
            BgWindowData(arr)
            setStockList([]);
            BgUnsavedChanges(true)
            setShowDatePicker(false);
            setShowDatePicker1(false)
            notify(ST.AdditionalVisibilityaddedsuccessfully, 'LONG');
            setrerenderdata(!rerenderdata);
            // clear data
            setFromDate('');
            BgAddVisFormData({ AssertCount: '1' })
            setToDate('');
            setToDate2("")
            setFromDate2('');
        }

    }

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

    async function Remove_AddVis() {
        let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
        let { MenuId } = currentMenu;

        db.transaction(async function (txn) {
            let index = toRemoveId;
            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.ADDITIONAL_VISIBILITY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' AND KEY_ID='${index}' `;

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

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

                let deleteQueryStk = `DELETE FROM ${AppTables.ADDITIONAL_VISIBILITY_STOCK} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' AND COMMON_ID='${index}' `;

                txn.executeSql(deleteQueryStk, [], function (txn3, txnres) {
                    console.log('AdditionalVisibiltyStk data deleted', item.keyId, +"" + index);
                }, 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('AdditionalVisibilty removed successfully', 'LONG')
                    setrerenderdata(!rerenderdata);
                }
                else {
                    notify('Cannot remove! AdditionalVisibilty not found', 'LONG')
                }
                setToRemoveId('');
                setToRemoveItem({});
                setshowRemoveConfirm_M(false);
            }

        });
    }


    function RenderDatePicker() {
        let { curDate, setTimeStamp, setDate, ColumnName, setShowDate } = FromDateObj
        let today = new Date();
        let d1 = curDate != null && curDate != '' ? curDate : new Date();
        // let d1=new Date();
        console.log('d1 date:', d1);
        return (
            <DateTimePicker
                testID="dateTimePicker"
                value={d1}
                mode={'date'}
                display="default"
                // maximumDate={today}
                minimumDate={(FromDate2 && (ColumnName != "FromDate")) ? FromDate2 : new Date(null)}
                onChange={(event, selectedDate) => {
                    console.log('onchange date', event, selectedDate);
                    if (((selectedDate != null) && (event?.type != 'dismissed'))) {
                        console.log('change date', selectedDate);
                        let d2 = moment(selectedDate).format('DD/MM/YYYY');
                        let dateString = String(d2)
                        setShowDate(false);
                        setTimeStamp(selectedDate);
                        setDate(d2);
                        onFormDataChange(dateString, ColumnName)

                    }
                    setShowDatePicker(false)
                }}

            />
        );
    }

    const handleStockChange = (key, value) => {
        setSelectedItems((prev) => ({
            ...prev,
            [key]: {
                ...prev[key],
                stock: value,
            },
        }));
    };

    const toggleSelect = (item) => {
        setSelectedItems((prev) => {
            const key = `${item.DisplayId}-${item.ProductId}`;
            const isSelected = !!prev[key];

            if (isSelected) {
                const updated = { ...prev };
                delete updated[key];
                return updated;
            } else {
                return {
                    ...prev,
                    [key]: {
                        ...item,
                        stock: '', // force input
                    },
                };
            }
        });
    }



    const styles = StyleSheet.create({
        itemContainer: {
            padding: 10,
            borderBottomWidth: 1,
            borderColor: '#ddd',
        },
        checkbox: {
            position: 'absolute',
            left: 10,
            top: 15,
        },
        checkboxText: {
            fontSize: 18,
        },
        itemText: {
            marginLeft: 30,
            fontSize: 16,
        },
        input: {
            // marginTop: 10,
            marginLeft: 30,
            borderWidth: 1,
            borderColor: '#ccc',
            // padding: 5,
            // width: 150,

        },
        openButton: {
            backgroundColor: '#4CAF50',
            padding: 10,
            borderRadius: 8,
            alignSelf: 'center',
        },
        openButtonText: {
            color: '#fff',
            fontSize: 16,
            fontWeight: '600',
        },
        modalOverlay: {
            flex: 1,
            backgroundColor: 'rgba(0,0,0,0.4)',
            justifyContent: 'center',
            alignItems: 'center',
        },
        dialogBox: {
            backgroundColor: 'white',
            width: '85%',
            padding: 20,
            borderRadius: 12,
            maxHeight: '80%',
        },
        title: {
            fontSize: 20,
            fontWeight: 'bold',
            marginBottom: 15,
            textAlign: 'center',
            color: PageTheme.$primary_color
        },
        stockRow: {
            marginBottom: 10,
        },
        productName: {
            fontSize: 16,
            fontWeight: '500',
        },
        stockValue: {
            fontSize: 15,
            color: '#666',
        },
        closeButton: {
            backgroundColor: '#2196F3',
            padding: 10,
            borderRadius: 8,
            marginTop: 20,
            alignItems: 'center',
        },
        closeButtonText: {
            color: '#fff',
            fontWeight: '600',
        },

    });
    const renderItem = ({ item }) => {
       // console.log("itemmmmmm====", item)
       // console.log("AddVisFormData?.Stock", AddVisFormData?.StockList)

        let res = AddVisFormData?.StockList?.find((itn) => itn.ProductId == item.ProductId)


        return (
            <View>
                <View style={[customStyle.openStkP_checkboxWrap, { marginLeft: 10, marginTop: 10 }]}>
                    <View style={[customStyle.openStkP_checkboxCon,]}>
                        <CheckBox
                            boxType='square'
                            // value={true}
                            value={res?.isSelect == 1 || false}
                            onValueChange={(val) => { console.log('valchange:', val); let val1 = (val == true) ? 1 : 0; StockDataChange(val1, 'isSelect', '0', item); }}
                            style={[customStyle.openStkP_checkbox, (Platform.OS == 'ios' ? { height: 20, width: 20, marginTop: 8, marginLeft: 8, } : {})]}
                            tintColors={{ true: PageTheme.$primary_color, false: PageTheme.$text_color_light }}
                        />
                    </View>
                    <Text style={[customStyle.openStk_prd_name, customStyle.openStkP_checkbox_pName]}>{item.ProductName}</Text>
                </View>

                {res?.isSelect == 1 && (res?.StockRequire === 'true' || res?.StockRequire === true || res?.StockRequire === '1' || res?.StockRequire === 1) &&
                    <View style={[]}>
                        <TextInput
                            style={[customStyle.addVisInputStyle, { marginEnd: 35, marginStart: 35 }]}
                            placeholder="Stock"
                            autoComplete='off'
                            maxLength={6}
                            placeholderTextColor={PageTheme.$placeholder_color}
                            value={(res?.Stock || '')}
                            keyboardType='number-pad'
                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                            blurOnSubmit={false}
                            onChangeText={(val) => { StockDataChange(val, 'Stock', 'numeric', item) }}
                        // onSubmitEditing={()=>{focusToNext(cat,brand,skus,'1')}}
                        />
                    </View>
                }
            </View>
        );
    };


    function StockListDialog({ item, onClose }) {
        return (
            <Modal
                visible={true}
                animationType="slide"
                transparent={true}
                onRequestClose={onClose}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.dialogBox}>
                        <Text style={styles.title}>Products</Text>
                        <FlatList
                            data={item?.StockList || []}
                            keyExtractor={(item) => item.ProductId.toString()}
                            renderItem={({ item }) => (
                                <View style={styles.stockRow}>
                                    <Text style={styles.productName}>{item.ProductName}</Text>
                                    <Text style={styles.stockValue}>
                                        {(item.StockRequire === 'true' || item.StockRequire === true || item.StockRequire === '1' || item.StockRequire === 1) && item.isSelect === 1
                                            ? `Stock: ${item.Stock || 'N/A'}`
                                            : ''}
                                    </Text>
                                </View>
                            )}
                        />
                        <TouchableOpacity style={styles.closeButton} onPress={onClose}>
                            <Text style={styles.closeButtonText}>Close</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </Modal>
        );
    }

    function _render_addVisFormTop() {
        let xpos = 0;
        if (animatedChoice != null) {
            xpos = animatedChoice.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -75],
            });
        }

        let isFromDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
        let isFromDateKPIObj = isFromDateIndex >= 0 ? KPIFields[isFromDateIndex] : {};
        let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;

        let isToDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowToDate');
        let isToDateKPIObj = isToDateIndex >= 0 ? KPIFields[isToDateIndex] : {};
        let isToDateEnable = isToDateIndex >= 0 ? isToDateKPIObj['KPIFieldEnable'] : true;

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


        let isAssetCountIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowAssetCount');
        let isAssetCountKPIObj = isAssetCountIndex >= 0 ? KPIFields[isAssetCountIndex] : {};
        let isAssetCountEnable = isAssetCountIndex >= 0 ? isAssetCountKPIObj['KPIFieldEnable'] : true;
        let isAssetCountDisplayName = isAssetCountIndex >= 0 ? isAssetCountKPIObj['KPIFieldDisplayName'] : '';


        // console.log("StockList==",StockList )
        console.log("AddVisFormData", AddVisFormData)


        return (
            <View style={[customStyle.addvisCon]}>
                <View style={[customStyle.addvis_pCon]}>
                    <Text style={[customStyle.addvis_pText]}>{ST.IsPresent}</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 : {})]}>{ST.Yes}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(0, 'isPresent') }}>
                                <Text style={[customStyle.openStkCh_text, (isAddVisPresent == 0 ? customStyle.openStkCh_textactive : {})]}>{ST.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}>{ST.Category}</Text>
                                        {CustomPicker(props, Categories, 'CategoryName', 'CategoryId', 'CategoryName', 'CategoryId', onselectionChange, { value: AddVisFormData.CategoryName })}

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

                                        {CustomPicker(props, SubCategories, 'SubCategoryName', 'SubCategoryId', 'SubCategoryName', 'SubCategoryId', onselectionChange, { value: AddVisFormData.SubCategoryName })}
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{ST.Brands}</Text>

                                        {CustomPicker(props, Brands, 'BrandName', 'BrandId', 'BrandName', 'BrandId', onselectionChange, { value: AddVisFormData.BrandName })}
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol2]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{ST.DisplayType}</Text>
                                        {CustomPicker(props, DisplayList, 'DisplayName', 'DisplayId', 'DisplayName', 'DisplayId', onselectionChange, { value: AddVisFormData.DisplayName })}
                                    </View>
                                </View>
                                {isFromDateEnable == true &&
                                    <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                        <View style={[customStyle.addVisFormGrp, { width: '100%' }]}>
                                            <Text style={customStyle.addVisLabel}>{'From Date'}</Text>
                                            <View style={[customStyle.AddStockM_col, customStyle.openStk_prd_date_inputCon, { width: '100%', paddingRight: 5 }]} >
                                                <Text style={customStyle.openStk_prd_dateInput}>{FromDate}</Text>
                                                <TouchableOpacity style={customStyle.openStk_prd_datePicker} onPress={() => {
                                                    setFromDateObj({ curDate: FromDate2, setTimeStamp: setFromDate2, setDate: setFromDate, ColumnName: 'FromDate', setShowDate: setShowDatePicker1 })
                                                    setShowDatePicker(true);
                                                }}>
                                                    <Fontisto size={20} color={PageTheme.$accent_color} name="date" />
                                                </TouchableOpacity>
                                            </View>
                                        </View>
                                    </View>}
                                {isToDateEnable == true &&
                                    <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                        <View style={[customStyle.addVisFormGrp, { width: '100%' }]}>
                                            <Text style={customStyle.addVisLabel}>{'To Date'}</Text>
                                            <View style={[customStyle.AddStockM_col, customStyle.openStk_prd_date_inputCon, { width: '100%', paddingLeft: 5 }]} >
                                                <Text style={customStyle.openStk_prd_dateInput}>{ToDate}</Text>
                                                <TouchableOpacity style={customStyle.openStk_prd_datePicker} onPress={() => {
                                                    if ((FromDate2 != "") && isFromDateEnable == true) {
                                                        setFromDateObj({ curDate: ToDate2, setTimeStamp: setToDate2, setDate: setToDate, ColumnName: 'ToDate', setShowDate: setShowDatePicker })
                                                        setShowDatePicker(true);
                                                    } else {
                                                        notify("Please fill From Date first");
                                                    }
                                                }}>
                                                    <Fontisto size={20} color={PageTheme.$accent_color} name="date" />
                                                </TouchableOpacity>
                                            </View>
                                        </View>
                                    </View>}

                                {isAssetCountEnable &&
                                    <View style={[customStyle.addVisCol100]}>
                                        <View style={customStyle.addVisFormGrp}>
                                            <Text style={customStyle.addVisLabel}>{isAssetCountDisplayName ? isAssetCountDisplayName : ''}</Text>
                                            <TextInput
                                                style={customStyle.addVisInputStyle}
                                                defaultValue='1'
                                                autoComplete='off'
                                                keyboardType='number-pad'
                                                value={(AddVisFormData.AssertCount || '')}
                                                onChangeText={(val) => { onFormDataChange(val, 'AssertCount', 'numeric'); }}
                                            />
                                        </View>
                                    </View>
                                }

                                <View style={[customStyle.addVisCol100]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{ST.Remark}</Text>
                                        <TextInput
                                            style={customStyle.addVisInputStyle}
                                            autoComplete='off'
                                            value={(AddVisFormData.Remark || '')}
                                            onChangeText={(val) => { onFormDataChange(val, 'Remark', 'text'); }}
                                        />
                                    </View>
                                </View>
                                {AddVisCameraReq &&
                                    <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 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>
                                }

                                {StockList.length > 0 &&
                                    <View style={[customStyle.addVisCol100]}>
                                        <Card style={{
                                            borderRadius: 10,
                                            elevation: 4,

                                            backgroundColor: '#fff'
                                        }}>
                                            <Card.Title title="Select Products" />
                                            <Card.Content>
                                                <FlatList
                                                    data={StockList}
                                                    keyExtractor={(item, index) => `${item.DisplayId}-${item.ProductId}`}
                                                    renderItem={renderItem}
                                                />
                                            </Card.Content>
                                        </Card>

                                    </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}>{ST.AddedVisibilities}</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={[AddVisCameraReq ? customStyle.addVis_listIcol1 : customStyle.addVis_listIcol100]}>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>{ST.Category + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.CategoryName}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>{ST.SubCategory + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.SubCategoryName}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>{ST.Brands + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.BrandName}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>{ST.DisplayType + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.DisplayName}</Text>
                                                        </View>
                                                        <View style={[customStyle.addVis_listI_row]}>
                                                            <Text style={customStyle.addVis_listI_Label}>{'Asset Count :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.AssertCount}</Text>
                                                        </View>
                                                        <View style={[customStyle.addVis_listI_row]}>
                                                            <Text style={customStyle.addVis_listI_Label}>{ST.Remark + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item.Remark}</Text>
                                                        </View>
                                                        {item.FromDate &&
                                                            <View style={[customStyle.addVis_listI_row]}>
                                                                <Text style={customStyle.addVis_listI_Label}>{'From Date :'}</Text>
                                                                <Text style={customStyle.addVis_listI_Val}>{item.FromDate}</Text>
                                                            </View>
                                                        }

                                                        {item.ToDate &&
                                                            <View style={[customStyle.addVis_listI_row, customStyle.addVis_listI_lastrow]}>
                                                                <Text style={customStyle.addVis_listI_Label}>{'To Date :'}</Text>
                                                                <Text style={customStyle.addVis_listI_Val}>{item.ToDate}</Text>
                                                            </View>
                                                        }

                                                    </View>

                                                    {AddVisCameraReq && 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 }} />}

                                                            {item?.StockList != null && item?.StockList != undefined && item?.StockList.length > 0 && (
                                                                <TouchableOpacity
                                                                    style={customStyle.stockListButton}
                                                                    onPress={() => {
                                                                        setDialogVisible(true);
                                                                        setSelectedItem(item); // Set the current item
                                                                        // handle your button action
                                                                        // <StockListDialog item={item} />
                                                                        console.log('StockList pressed', item);
                                                                    }}
                                                                >
                                                                    <Text style={customStyle.stockListButtonText}>Products</Text>
                                                                </TouchableOpacity>
                                                            )}

                                                            {/* ✅ Conditionally Rendered Dialog */}
                                                            {dialogVisible && selectedItem && (
                                                                <StockListDialog item={selectedItem} onClose={() => {
                                                                    setDialogVisible(false)
                                                                    setSelectedItem(null);
                                                                }} />
                                                            )}

                                                        </View>}


                                                    <TouchableOpacity style={customStyle.addVis_btnRemove} onPress={() => { showRemoveConfirm(item, index) }}>
                                                        <FontAwesome name='trash' size={20} color={'red'} />
                                                    </TouchableOpacity>
                                                </View>
                                            </View>
                                        );
                                    })
                                }
                            </View>
                        </View>
                    </ScrollView>
                }
            </View>
        )
    }

    const hideDatePicker = () => {
        setShowDatePicker(false);
    };

    const handleConfirm = (date) => {
        setTextValue(date)
    };

    function setTextValue(value) {
        let d2 = moment(value).format('DD/MM/YYYY');
        let dateString = String(d2)

        hideDatePicker();
        if (FromDateObj?.ColumnName == 'FromDate') {
            setFromDate(dateString)
            setFromDate2(value)
            // ✅ Clear ToDate
            setToDate('');
            setToDate2(null);
        } else if (FromDateObj?.ColumnName == 'ToDate') {
            setToDate(dateString)
            setToDate2(value)
        }

        onFormDataChange(dateString, FromDateObj?.ColumnName)
    }

    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()}
            <DateTimePickerModal
                isVisible={ShowDatePicker}
                mode="month"
                display="spinner"
                date={(FromDateObj?.curDate != null && FromDateObj?.curDate != '') ? new Date(FromDateObj?.curDate) : new Date()}
                minimumDate={(FromDate2 && (FromDateObj?.ColumnName != "FromDate")) ? new Date(FromDate2) : new Date(null)}
                onConfirm={
                    handleConfirm
                }
                onCancel={hideDatePicker}
            />
            {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'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: ' + currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData) => { setShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { setShowCamera(false); }} />

            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper, 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)(AdditionalVisibility);