import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles, GetPageTheme } from "../styles/Global";
import { TextInput, View, Text, TouchableOpacity, Platform, FlatList, Alert, KeyboardAvoidingView, AppState, Keyboard, StyleSheet, Modal } from 'react-native';
import { connect, } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { checkMDStockScreenExists, getKPIFields, validateNumber } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { db } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import GradientButton from '../components/gradientButton';
import { ConfirmSaveAlert } from '../components/alert';
import { CustomPicker } from '../components/CustomPicker';

function Sale(props) {
    const route = useRoute();
    // get all theme styles acc to current theme set 
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);
    const [processing, setProcessing] = useState(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 [KPIFields, setKPIFields] = useState([]);
    const [SKUStockData, setSKUStockData] = useState([]);
    const [IsMidDayStockScreen, setIsMidDayStockScreen] = useState(false);
    const [IsOpeningStockScreen, setIsOpeningStockScreen] = useState(false);
    const [IsStockScreen, setIsStockScreen] = useState(false);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const SKUStockDataRef = React.useRef(SKUStockData);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');
    const [globalBrandData, setGlobalBrandData] = useState([]);
    const [filtervalue, setFilterValue] = useState({});
    const [catfilter, setcatFilter] = useState([]);
    const [subcatfilter, setsubcatFilter] = useState([]);
    const [brandfilter, setbrandFilter] = useState([]);
    const [searchedItem, setSearchedItem] = useState('');
    const [rerenderdata2, setrerenderdata2] = useState(0);
    const [modalVisible, setModalVisible] = useState(false);

    const defCat = { "CategoryId": "", "CategoryName": "-Select-" };
    const defSubCat = { 'SubCategoryId': "", 'SubCategoryName': "-Select-" };
    const defBrand = { 'BrandId': "", 'BrandName': "-Select-" };
    const [showMrpPtr, setShowMrpPtr] = useState('NA');
    const showMrpPtrRef = useRef('NA');
    const inputRefs = useRef({});
    // error field states
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = useState(false);
    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 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(SKUStockData, pro, hasUnsavedChanges) });
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

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


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

        }

    }

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

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

    function onBeforeRemove(e) {
        if (hasUnsavedChanges == 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: "OK", onPress: async () => {
                        BgUnsavedChanges(false)
                        await clear_item('storeData')
                        props.navigation.dispatch(e.data.action);
                    }
                }
            ]
        );
    }


    function updateShowMrpPtr(newVal) {
        showMrpPtrRef.current = newVal; // instant
        setShowMrpPtr(newVal);          // triggers UI update
    }
    async function getData(storeData1, menu1) {
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;
            let isMDSTOCKExists = await checkMDStockScreenExists(storeData1, 'MDSTOCK')
            setIsMidDayStockScreen(isMDSTOCKExists);
            let isOPSTOCKExists = await checkMDStockScreenExists(storeData1, 'OPSTOCK')
            setIsOpeningStockScreen(isOPSTOCKExists);
            let isSTOCKExists = await checkMDStockScreenExists(storeData1, 'STOCK')
            setIsStockScreen(isSTOCKExists);
            let AllKPIFields = await getKPIFields(menu1);
            setKPIFields(AllKPIFields);
            let ShowCompetionSku = AllKPIFields?.findIndex((i) => i.KPIFieldName == "ShowCompetionSku");
            let ShowCompetionObj = ShowCompetionSku >= 0 ? AllKPIFields[ShowCompetionSku] : {};
            let ShowCompetionSkuNo = ShowCompetionObj?.KPIFieldDisplayName || 0
            let ShowCompetionSkuNoSplitArr = ShowCompetionObj?.KPIFieldDisplayName?.split(",") || []
            const isCompetitorValues = ShowCompetionSkuNoSplitArr;
            let isShowMrpPtrIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'ShowMRPPTR')
            let isShowMrpPtrKPIObj = isShowMrpPtrIndex >= 0 ? AllKPIFields[isShowMrpPtrIndex] : {};
            let isShowMrpPtrEnable = isShowMrpPtrIndex >= 0 ? isShowMrpPtrKPIObj['KPIFieldEnable'] : false;
            if (isShowMrpPtrEnable == true) {
                let isShowMrpPtrName = isShowMrpPtrIndex >= 0 ? isShowMrpPtrKPIObj['KPIFieldDisplayName'] : 'NA';
                updateShowMrpPtr(isShowMrpPtrName)
            }
            console.log('iscompetitorValues1', isShowMrpPtrEnable)
            // Check if isCompetitorValues is empty, null, or undefined
            let isCompetitorClause = !isCompetitorValues || isCompetitorValues.length === 0 ? "p.IsCompetitor = 0" : `p.IsCompetitor IN (${isCompetitorValues.join(",")})`;
            let storeBGData1 = [], bgStoreJson = {}, isBgDataExists = false;
            let windData = await get_item('storeData');
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData)
                console.log("StoreJson11--", StoreJson)
                let { storeBGData, menuName, StoreId1, visiteDate } = StoreJson
                if (storeBGData.length > 0 && menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                    isBgDataExists = true
                    storeBGData1 = storeBGData;
                    bgStoreJson = StoreJson
                    BgUnsavedChanges(true)
                    SKUStockDataRef.current = storeBGData
                    setSKUStockData(storeBGData);
                }
            }

            await db.transaction(async function (txn) {

                let join7 = '', where_q = '', cols = ''
                if (isOPSTOCKExists || isMDSTOCKExists) {
                    cols = ' ,o.MIDDAY_STOCK,o.OPENING_STOCK ';
                    where_q = `AND (CAST(IFNULL(o.OPENING_STOCK, 0) AS INTEGER) + CAST(IFNULL(o.MIDDAY_STOCK, 0) AS INTEGER)) > 0`
                    join7 = ` inner join ${AppTables.STOCK_DATA} o on p.ProductId=o.PRODUCT_ID and o.STORE_ID='${StoreId}' and o.VISIT_DATE='${d2}' `;
                }
                else if (isSTOCKExists) {
                    cols = ' ,o.STOCK as OPENING_STOCK ';
                    where_q = ' AND CAST(IFNULL(o.STOCK, 0) AS INTEGER) > 0'
                    join7 = ` inner join ${AppTables.STOCK2_DATA} o on p.ProductId=o.PRODUCT_ID and o.STORE_ID='${StoreId}' and o.VISIT_DATE='${d2}' `;
                }
                let join = ` INNER JOIN Product_Master p on c.CategoryId=p.CategoryId  `;
                let join2 = ` INNER JOIN Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId `;
                let q2 = ` SELECT * FROM ( SELECT c.CategoryId,c.CategoryName,'' as MSL ${cols}, p.CategorySequence, ROW_NUMBER() OVER (PARTITION BY c.CategoryId ORDER BY c.CategoryId) as rn from Master_Category c ${join} ${join2} ${join7} Where mp.StoreId ='${StoreId}' and p.IsCompetitor='0' ${where_q} ) t WHERE rn = 1 ORDER BY CategorySequence`;
                console.log("checkquery_header", q2)

                console.log("checkquery", q2)
                await txn.executeSql(q2, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        console.log('inputs found', txnres.rows.length);
                        let arr = [], arr2 = [defCat];
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            let catobj = { "CategoryId": data.CategoryId, "CategoryName": data.CategoryName }
                            arr.push(data);
                            arr2.push(catobj);
                            if (i == txnres.rows.length - 1) {
                                setcatFilter(arr2);
                                setrerenderdata(!rerenderdata);
                                getSKU(arr, storeData1, AllKPIFields, bgStoreJson, menu1, isOPSTOCKExists, isMDSTOCKExists, isSTOCKExists, isBgDataExists);
                            }
                        }
                    }

                }, function (txnE, txnerr) { console.log(txnerr); },);
            });
        } catch (err) {
            console.log(err);
        }
    }



    async function getSKU(brands = [], storeData1 = {}, AllKPIFields = [], bgStoreJson = {}, menu1 = {}, isOPSTOCKExists, isMDSTOCKExists, isSTOCKExists, isBgDataExists = false) {
        console.log('getSKU')
        try {

            let ShowCompetionSku = AllKPIFields?.findIndex((i) => i.KPIFieldName == "ShowCompetionSku");
            let ShowCompetionObj = ShowCompetionSku >= 0 ? AllKPIFields[ShowCompetionSku] : {};
            let ShowCompetionSkuNo = ShowCompetionObj?.KPIFieldDisplayName || 0
            let ShowCompetionSkuNoSplitArr = ShowCompetionObj?.KPIFieldDisplayName?.split(",") || []
            const isCompetitorValues = ShowCompetionSkuNoSplitArr;
            // Check if isCompetitorValues is empty, null, or undefined
            let isCompetitorClause = !isCompetitorValues || isCompetitorValues.length === 0 ? "p.IsCompetitor = 0" : `p.IsCompetitor IN (${isCompetitorValues.join(",")})`;
            console.log("checkiscpmp2--", isCompetitorClause)
            let { StoreId } = storeData1;
            let arr2 = [defSubCat];
            let arr3 = [defBrand];
            await db.transaction(async function (txn) {
                var allSKUData = [];
                await Promise.all(
                    brands.map(async (item, index) => {
                        let cols = '', join_o = '', where_stock = '';
                        if (isOPSTOCKExists || isMDSTOCKExists) {
                            cols = ' ,o.MIDDAY_STOCK,o.OPENING_STOCK ';
                            where_stock = `AND (CAST(IFNULL(o.OPENING_STOCK, 0) AS INTEGER) + CAST(IFNULL(o.MIDDAY_STOCK, 0) AS INTEGER)) > 0`;
                            join_o = ` left join ${AppTables.STOCK_DATA} o on p.ProductId=o.PRODUCT_ID and o.STORE_ID='${StoreId}' and o.VISIT_DATE='${d2}' `;
                        }
                        else if (isSTOCKExists) {
                            cols = ' ,o.STOCK as OPENING_STOCK ';
                            where_stock = ' AND CAST(IFNULL(o.STOCK, 0) AS INTEGER) > 0';
                            join_o = ` left join ${AppTables.STOCK2_DATA} o on p.ProductId=o.PRODUCT_ID and o.STORE_ID='${StoreId}' and o.VISIT_DATE='${d2}' `;
                        }

                        let seletlist = `  ifnull(p.Mrp,0) as Mrp, ifnull(p.ptr,0) as ptr, p.ProductName, p.ProductId, a.MSL,a.ArticleCode, p.SubCategoryName, p.SubCategoryId, p.BrandName, p.BrandId, s.STOCK ${cols} `;
                        let join2 = ` inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
                        let join = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=p.ProductId and a.StoreId='${StoreId}' `;
                        let join5 = ` left join ${AppTables.SALES} s on s.PRODUCT_ID=p.ProductId and s.STORE_ID='${StoreId}' and s.VISIT_DATE='${d2}' and s.CATEGORY_ID='${item.CategoryId}' `;
                        let sku_q = `SELECT DISTINCT ${seletlist} FROM Product_Master p ${join} ${join2} ${join5} ${join_o} WHERE (p.CategoryId='${item.CategoryId}' or p.CategoryId=${item.CategoryId}) and ${isCompetitorClause} ${where_stock} ORDER BY p.ProductSequence`;
                        console.log("checkskud--", sku_q)
                        return await txn.executeSql(sku_q, [], async function (txn2, txnres) {
                            if (txnres.rows.length > 0) {
                                let arr = [];
                                for (var i = 0; i < txnres.rows.length; i++) {
                                    let data = txnres.rows.item(i);
                                    inputRefs.current['input1_' + item.CategoryId + '_' + data.ProductId] = '';
                                    arr.push(data);
                                    let subcatIndex = arr2.findIndex(i => i.SubCategoryId == data.SubCategoryId)
                                    let subcatobj = { 'SubCategoryId': data.SubCategoryId, 'SubCategoryName': data.SubCategoryName }
                                    if (subcatIndex < 0) {
                                        arr2.push(subcatobj);

                                    }
                                    let subbrandIndex = arr3.findIndex(i => i.BrandId == data.BrandId)
                                    let subbrandobj = { 'BrandId': data.BrandId, 'BrandName': data.BrandName }
                                    if (subbrandIndex < 0) {
                                        arr3.push(subbrandobj);
                                    }
                                    let defData = {
                                        'CategoryId': item.CategoryId, 'ProductId': data.ProductId, 'Stock': data.STOCK, 'ProductName': data.ProductName,
                                        'ptr': showMrpPtrRef.current === 'PTR' ? data.ptr : data.Mrp
                                    };

                                    allSKUData.push(defData);
                                    if (i == txnres.rows.length - 1) {
                                        item['skulist'] = arr;
                                        brands[index] = item;
                                        if (index == brands.length - 1) {
                                            let { storeBGData, menuName, StoreId1, visiteDate } = bgStoreJson
                                            if (!isBgDataExists) {
                                                SKUStockDataRef.current = allSKUData
                                                setSKUStockData(allSKUData);
                                            }

                                            setGlobalBrandData(brands);
                                            setBrandData(brands);
                                            setsubcatFilter(arr2);
                                            setbrandFilter(arr3);
                                            setProcessing(true);
                                            setrerenderdata(!rerenderdata);
                                        }

                                        return item;
                                    }
                                }
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); return item; },);
                        return item;
                    })
                ).then((res) => {
                    setTimeout(() => {
                        setProcessing(false);
                    }, 3000);

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

    async function focusToNext(cat, sku, type = '1') {
        let activeKey = '';
        let arr = Object.keys(inputRefs.current);
        activeKey = 'input' + type + '_' + cat.CategoryId + '_' + sku.ProductId;
        let activeIndex = arr.indexOf(activeKey);
        if (activeIndex < arr.length - 1) {
            let nextKey = arr[++activeIndex]
            let nextRef = inputRefs.current[nextKey];
            console.log("nextKey", nextKey, nextRef, inputRefs.current[nextKey])
            nextRef.focus();
        }
        else {
            return
        }
    }

    async function submitData() {
        let isvalid = await validate();
        if (isvalid) {
            Keyboard.dismiss();
            const totalStockQty = SKUStockData.reduce(
                (sum, item) => sum + (parseFloat(item.Stock) > 0 ? parseFloat(item.Stock) : 0),
                0
            );
            if ((showMrpPtr !== 'NA' || showMrpPtrRef.current !== 'NA') && totalStockQty > 0) {
                setModalVisible(true);
            } else {
                setShowAlert(true);
            }
        }
    }

    async function saveData() {
        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.SALES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                //  remove old data
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('sales data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);
                var stock_values = '';
                for (var i = 0; i < globalBrandData.length; i++) {
                    let catIndex = i;
                    let item = globalBrandData[catIndex];
                    let skulist = item['skulist'] || [];
                    for (var j = 0; j < skulist.length; j++) {
                        let skuItem = skulist[j];
                        let { MSL, ProductId, ProductName, ArticleCode } = skulist[j];
                        ArticleCode = ArticleCode != null && ArticleCode != undefined && ArticleCode != 'undefined' && ArticleCode != '' ? ArticleCode : ''
                        stock_values += stock_values != '' ? ' , ' : '';
                        let allSKUData = SKUStockData;
                        const skud_index = allSKUData.findIndex(ci => ci.CategoryId == item.CategoryId && ci.ProductId == skuItem.ProductId);
                        const skud = skud_index >= 0 ? (allSKUData[skud_index] || {}) : {};
                        let StockVal = skud['Stock'] || '';
                        stock_values += ` ('${StoreId}','${d2}','${item.CategoryName}','${item.CategoryId}','${ProductName}','${ProductId}','${MSL}','${StockVal}','${d2}','${ArticleCode}') `;
                    }
                }

                let add_Stock = `INSERT INTO ${AppTables.SALES} (STORE_ID,VISIT_DATE,CATEGORY,CATEGORY_ID,PRODUCT,PRODUCT_ID,MSL,STOCK,ADDED_DATE,ARTICLE_CODE) VALUES ${stock_values} `;
                await txn.executeSql(add_Stock, [], async function (txn2, txnres) {
                    console.log('sales added');
                    notify('Sales updated successfully');
                    setProcessing(false);
                    // clear store data in local storage to avoiding re-set data for the store  
                    hasUnsavedChangesRef.current = false
                    await clear_item('storeData')
                    props.navigation.goBack();
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot update Sales') },);


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

    function FilterStores(searchedQry, filtervalue1) {
        searchedQry = searchedQry.toLowerCase();
        console.log('searchedQry', searchedQry);
        let arr = [];
        let newBrandList = [];
        let filterCatId = filtervalue1.CategoryId;
        let filterSubCatId = filtervalue1.SubCategoryId;
        let filterBrandId = filtervalue1.BrandId;
        if ((searchedQry != null && searchedQry != '') || (filterCatId != null && filterCatId != '') || (filterSubCatId != null && filterSubCatId != '') || (filterBrandId != null && filterBrandId != '')) {
            console.log('searchquerytrue')
            for (let i = 0; i < globalBrandData.length; i++) {
                let item = globalBrandData[i];
                let { CategoryId } = item;
                let skulist = item.skulist || [];
                let newBrand = Object.assign({ 'test2': '2' }, item);
                let newSkulist = [];
                for (let j = 0; j < skulist.length; j++) {
                    let sku = skulist[j];
                    let { ProductName, SubCategoryId, BrandId } = sku;
                    let isQueryMatched = false, isCatMatch = false, isSubCatMatch = false, isBrandMatch = false;
                    if ((searchedQry != null && searchedQry != '') && ProductName.toLowerCase().includes(searchedQry)) {
                        isQueryMatched = true;
                    }
                    else if (searchedQry == '' || searchedQry == null) {
                        isQueryMatched = true;
                    }

                    if ((filterCatId != null && filterCatId != '') && filterCatId == CategoryId) {
                        isCatMatch = true;

                    }
                    else if (filterCatId == '' || filterCatId == null) {
                        isCatMatch = true;
                    }

                    if ((filterSubCatId != null && filterSubCatId != '') && filterSubCatId == SubCategoryId) {
                        isSubCatMatch = true;

                    }
                    else if (filterSubCatId == '' || filterSubCatId == null) {
                        isSubCatMatch = true;
                    }

                    if ((filterBrandId != null && filterBrandId != '') && filterBrandId == BrandId) {
                        isBrandMatch = true;

                    }
                    else if (filterBrandId == '' || filterBrandId == null) {
                        isBrandMatch = true;
                    }

                    if (isQueryMatched && isCatMatch && isSubCatMatch && isBrandMatch) {
                        newSkulist.push(sku);
                    }

                    if (j == skulist.length - 1) {
                        newBrand.skulist = newSkulist;

                        if (newBrand.skulist.length > 0) {
                            newBrandList.push(newBrand);
                        }
                    }
                }


            }
        }
        else {
            newBrandList = globalBrandData;
        }

        setBrandData(newBrandList);
        setrerenderdata(!rerenderdata)
        setrerenderdata2(!rerenderdata2)
    }

    async function onselectionChange(option, keyLbl, keyVal, otherData) {
        // console.log('trueeeeeeeeeeee')
        setProcessing(true);
        // let CategoryName=otherData.CategoryName!=null?otherData.CategoryName:'';
        let data = filtervalue || {};
        // console.log('setFilterValue',data)
        data[keyVal] = option.value;
        data[keyLbl] = option.label;
        await FilterHierarchy(keyVal, option.value);
        if (keyVal == "CategoryId") {
            data["SubCategoryId"] = defSubCat.SubCategoryId;
            data["SubCategoryName"] = defSubCat.SubCategoryName;
            data["BrandId"] = defBrand.BrandId;
            data["BrandName"] = defBrand.BrandName;
        }
        else if (keyVal == "SubCategoryId") {
            data["BrandId"] = defBrand.BrandId;
            data["BrandName"] = defBrand.BrandName;
        }
        setFilterValue(data);
        FilterStores(searchedItem, data)
        console.log('filtersrores', searchedItem, data)

        setrerenderdata(!rerenderdata);
        setrerenderdata2(!rerenderdata2)
        setProcessing(false);
    }

    async function FilterHierarchy(keyVal, val) {
        let join = `  inner join Mapping_ProductAssortmentStorewise m on p.ProductId=m.ProductId `;// assortment join
        let { StoreId } = storeData
        if (keyVal == "CategoryId") {
            // Filter Brand based on category
            let brandq = `Select Distinct p.BrandId,p.BrandName from Product_Master p  ${join} where m.StoreId='${StoreId}' and (p.CategoryId='${val}' or p.CategoryId= ${val}) and (CompanyId='1' or CompanyId =1) order by p.BrandSequence `;
            let brands = await executeQuery(brandq, [defBrand]);
            setbrandFilter(brands);
            // Filter Sub cats based on category
            let subcatq = `Select Distinct p.SubCategoryId,p.SubCategoryName from Product_Master p  ${join} where m.StoreId='${StoreId}' and (p.CategoryId='${val}' or p.CategoryId= ${val}) and (CompanyId='1' or CompanyId =1) order by p.BrandSequence `;
            let subCats = await executeQuery(subcatq, [defSubCat]);
            setsubcatFilter(subCats);
        }
        else if (keyVal == "SubCategoryId") {
            // Filter Brands based on Sub-category
            let brandq = `Select Distinct p.BrandId,p.BrandName from Product_Master p  ${join} where m.StoreId='${StoreId}' and (p.SubCategoryId='${val}' or p.SubCategoryId= ${val}) and (CompanyId='1' or CompanyId =1) order by p.BrandSequence `;
            let brands = await executeQuery(brandq, [defBrand]);
            setbrandFilter(brands);
        }
    }

    async function executeQuery(query, defData) {
        return await new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                await txn.executeSql(query, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let arr = defData;
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            arr.push(data);
                            if (i == txnres.rows.length - 1) {
                                resolve(arr);
                            }
                        }
                    }
                    else {
                        resolve(defData);
                    }

                }, function (txnE, txnerr) { console.log(txnerr); resolve(defData); },);
                // setProcessing(false);
            });
        }).catch((err) => {
            console.log(err);
            return defData;
        })
    }

    async function validate() {
        let isValid = true;
        let isAnyFilled = false;
        await Promise.all(
            globalBrandData.map(async (item, index) => {
                if (isValid) {
                    let errorobj = { 'EF_brand': item };
                    let skulist = item.skulist || [];
                    if (skulist.length > 0) {
                        await Promise.all(
                            skulist.map(async (skuItem, skuIndex) => {
                                if (isValid) {
                                    let skuData = SKUStockData.find(ci => ci.CategoryId == item.CategoryId && ci.ProductId == skuItem.ProductId) || {};
                                    let OS = skuItem.OPENING_STOCK || 0;
                                    let MDS = skuItem.MIDDAY_STOCK || 0;
                                    let maxClosingStock = IsMidDayStockScreen == true ? parseInt(OS) + parseInt(MDS) : parseInt(OS);
                                    errorobj['EF_product'] = skuItem;
                                    let error_bid = item.CategoryId
                                    let error_pid = skuItem.ProductId
                                    let show_errorH = false, error_HInputKey = '';
                                    if ((IsOpeningStockScreen == true || IsMidDayStockScreen == true || IsStockScreen == true) && parseInt(skuData.Stock) > maxClosingStock) {
                                        if (IsOpeningStockScreen == true || IsMidDayStockScreen == true) {
                                            IsMidDayStockScreen == true ? notify('Sale Should not be greater than the sum of Opening-Stock and Midday-Stock for ' + skuItem.ProductName) : notify('Sale Should not be greater than Opening-Stock for ' + skuItem.ProductName);
                                        } else if (IsStockScreen) {
                                            // notify('Sale Should not be greater than the stock for '+skuItem.ProductName)
                                            notify('SALES value cannot exceed STOCK Value ' + skuItem.ProductName)
                                        }
                                        isValid = false;
                                        show_errorH = true, error_HInputKey = 'input1_';
                                    }

                                    if (skuData.Stock === 0 || (skuData.Stock != null && skuData.Stock != '')) {
                                        isAnyFilled = true;
                                    }

                                    if (index == globalBrandData.length - 1 && skuIndex == skulist.length - 1 && !isAnyFilled) {
                                        notify('Please enter Sale for atleast one Product (If not present then Enter "0")', 'SHORT');
                                        isValid = false;
                                    }
                                    if (show_errorH) {
                                        errorobj['EF_InputKey'] = error_HInputKey;
                                        setErrorField(errorobj)
                                        setError(true)
                                        let refIn1 = inputRefs.current[error_HInputKey + error_bid + '_' + error_pid];
                                        refIn1.focus();
                                    }
                                }
                            })
                        );
                    }
                }
            })
        );

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

    function onStockValChange(item, skuItem, val, key, type = '') {
        setError(false);
        setErrorField({});
        if (val != '') {
            let isValid = validateNumber(val, type);
            if (!isValid) {
                return;
            }
        }

        let allSKUData = SKUStockData;
        let defData = { 'CategoryId': item.CategoryId, 'ProductId': skuItem.ProductId };
        const skud_index = allSKUData.findIndex(i => i.CategoryId == item.CategoryId && i.ProductId == skuItem.ProductId);
        const skud = skud_index >= 0 ? (allSKUData[skud_index] || defData) : defData;
        skud[key] = val;
        skud_index >= 0 ? allSKUData[skud_index] = skud : allSKUData.push(skud);
        SKUStockDataRef.current = allSKUData
        setSKUStockData(allSKUData);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onSaveCancel() {
        setShowAlert(false);
    }

    function clearFilter(obj, key1, key2) {
        let fdata = filtervalue;
        fdata[key1] = obj[key1];
        fdata[key2] = obj[key2];
        if (key1 == "CategoryId") {
            fdata["SubCategoryId"] = defSubCat.SubCategoryId;
            fdata["SubCategoryName"] = defSubCat.SubCategoryName;
            fdata["BrandId"] = defBrand.BrandId;
            fdata["BrandName"] = defBrand.BrandName;
        } else if (key1 == "SubCategoryId") {
            fdata["BrandId"] = defBrand.BrandId;
            fdata["BrandName"] = defBrand.BrandName;
        }
        setFilterValue(fdata);
        FilterStores(searchedItem, fdata);
    }


    const calculatetotalStockQty = (data) => {
        const totalStockQty = data.reduce(
            (sum, item) => sum + (parseFloat(item.Stock) > 0 ? parseFloat(item.Stock) : 0),
            0
        );
        return totalStockQty;
    };

    const calculatetotalAmount = (data) => {
        const totalAmount = data.reduce(
            (sum, item) =>
                sum +
                (parseFloat(item?.Stock) > 0
                    ? parseFloat(item?.Stock) * parseFloat(item?.ptr || 0)
                    : 0),
            0
        );
        return totalAmount.toFixed(2); // ensures 2 decimal places
    };

    const renderModalContent = () => {
        // ✅ Calculate Totals
        const totalStockQty = SKUStockData.reduce(
            (sum, item) => sum + (parseFloat(item.Stock) > 0 ? parseFloat(item.Stock) : 0),
            0
        );
        const totalAmount = SKUStockData.reduce(
            (sum, item) =>
                sum +
                (parseFloat(item?.Stock) > 0
                    ? parseFloat(item?.Stock) * parseFloat(item?.ptr || 0)
                    : 0),
            0
        );

        return (
            <View style={styles.modalContainer}>
                <Text style={styles.modalTitle}>Preview Sales Data</Text>
                <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                    <Text style={styles.modalTitle}>Sales</Text>
                    <Text style={styles.modalTitle}>Values</Text>
                </View>

                <FlatList
                    nestedScrollEnabled={true}
                    removeClippedSubviews={false}
                    scrollToOverflowEnabled={true}
                    legacyImplementation={true}
                    data={SKUStockData.filter(item => parseFloat(item.Stock) > 0)}
                    keyExtractor={(item, index) => `preview-${index}`}
                    renderItem={({ item }) => (
                        <View style={styles.modalItemRow}>
                            <Text style={styles.modalProduct}>{item.ProductName}</Text>
                            <View style={styles.qtyRow}>
                                <TextInput
                                    style={styles.modalInput}
                                    keyboardType="number-pad"
                                    editable={false}
                                    value={item.Stock && item.Stock !== '' ? item?.Stock.toString() : '0'}
                                />
                                <Text style={styles.calculatedValue}>
                                    {(parseFloat(item?.Stock || 0) * parseFloat(item?.ptr || 0)).toFixed(2)}
                                </Text>
                            </View>
                        </View>
                    )}
                />

                {/* ✅ Totals Section */}
                <View style={styles.totalsContainer}>
                    <Text style={styles.totalText}>Total Sale: {totalStockQty}</Text>
                    <Text style={styles.totalText}>Total Amount: {totalAmount.toFixed(2)}</Text>
                </View>

                <View style={styles.modalButtons}>

                    <TouchableOpacity
                        style={[styles.modalButton, { backgroundColor: '#ccc' }]} // gray button
                        onPress={() => setModalVisible(false)}
                    >
                        <Text style={[styles.modalButtonText, { color: '#333' }]}>Cancel</Text>
                    </TouchableOpacity>

                    <TouchableOpacity
                        style={styles.modalButtonYes}
                        onPress={() => { setModalVisible(false); saveData() }}
                    >
                        <Text style={styles.modalButtonText}>Proceed</Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    };

    function _renderSalesFilter() {
        let salesCatFilterI = KPIFields.findIndex(i => i.KPIFieldName == 'salesCatFilter')
        let salesCatFilterObj = salesCatFilterI >= 0 ? KPIFields[salesCatFilterI] : {};
        let salesCatFilter = salesCatFilterI >= 0 ? salesCatFilterObj['KPIFieldEnable'] : false;
        let salesSubCatFilterI = KPIFields.findIndex(i => i.KPIFieldName == 'salesSubCatFilter')
        let salesSubCatFilterObj = salesSubCatFilterI >= 0 ? KPIFields[salesSubCatFilterI] : {};
        let salesSubCatFilter = salesSubCatFilterI >= 0 ? salesSubCatFilterObj['KPIFieldEnable'] : false;
        let salesBrandFilterI = KPIFields.findIndex(i => i.KPIFieldName == 'salesBrandFilter')
        let salesBrandFilterObj = salesBrandFilterI >= 0 ? KPIFields[salesBrandFilterI] : {};
        let salesBrandFilter = salesSubCatFilterI >= 0 ? salesBrandFilterObj['KPIFieldEnable'] : false;
        if (rerenderdata == rerenderdata && (salesCatFilter || salesSubCatFilter || salesBrandFilter)) {
            return (
                <View>
                    {salesCatFilter &&
                        <View style={[customStyle.openStk_prd_colflex, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_textLabel]}>{'Category'}</Text>
                            <View style={customStyle.Sale_filterwrap}>
                                {CustomPicker(props, catfilter, 'CategoryName', 'CategoryId', 'CategoryName', 'CategoryId', onselectionChange, { value: filtervalue.CategoryId, otherData: {} }, customStyle.Sale_filterSelStyle, customStyle.Sale_filterSelInputStyle, true)}
                                <TouchableOpacity style={customStyle.Sale_clrfilterBtn} onPress={() => { clearFilter(catfilter[0], 'CategoryId', 'CategoryName') }}>
                                    <Entypo name="cross" size={24} color={PageTheme.$primary_color} />
                                </TouchableOpacity>
                            </View>
                        </View>}

                    {salesSubCatFilter &&
                        <View style={[customStyle.openStk_prd_colflex, customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_textLabel]}>{'SubCategory'}</Text>
                            <View style={customStyle.Sale_filterwrap}>
                                {CustomPicker(props, subcatfilter, 'SubCategoryName', 'SubCategoryId', 'SubCategoryName', 'SubCategoryId', onselectionChange, { value: filtervalue.SubCategoryId, otherData: {} }, customStyle.Sale_filterSelStyle, customStyle.Sale_filterSelInputStyle, true)}
                                <TouchableOpacity style={customStyle.Sale_clrfilterBtn} onPress={() => { clearFilter(subcatfilter[0], 'SubCategoryId', 'SubCategoryName') }}>
                                    <Entypo name="cross" size={24} color={PageTheme.$primary_color} />
                                </TouchableOpacity>
                            </View>
                        </View>}

                    {salesBrandFilter &&
                        <View style={[customStyle.openStk_prd_colflex, customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_textLabel]}>{'Brand'}</Text>
                            <View style={customStyle.Sale_filterwrap}>
                                {CustomPicker(props, brandfilter, 'BrandName', 'BrandId', 'BrandName', 'BrandId', onselectionChange, { value: filtervalue.BrandId, otherData: {} }, customStyle.Sale_filterSelStyle, customStyle.Sale_filterSelInputStyle, true)}
                                <TouchableOpacity style={customStyle.Sale_clrfilterBtn} onPress={() => { clearFilter(brandfilter[0], 'BrandId', 'BrandName') }}>
                                    <Entypo name="cross" size={24} color={PageTheme.$primary_color} />
                                </TouchableOpacity>
                            </View>
                        </View>}
                </View>
            )
        }
        else {
            return null;
        }
    }


    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
                <View style={[customStyle.pageContentWrapper]}>

                    <View style={[customStyle.storel_searchbar2]}>
                        <TextInput
                            style={[customStyle.storel_searchInput]}
                            placeholder={'Search by Product Name '}
                            autoComplete='off'
                            placeholderTextColor={PageTheme.$placeholder_color}
                            value={searchedItem}
                            onChangeText={(val) => { setSearchedItem(val); FilterStores(val, filtervalue) }}
                        />

                        <TouchableOpacity style={customStyle.storel_searchBtn} onPress={() => { FilterStores(searchedItem, filtervalue) }}>
                            <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
                        </TouchableOpacity>

                    </View>

                    {(showMrpPtr !== 'NA' || showMrpPtrRef.current !== 'NA') && <View style={{ backgroundColor: '#67abcaff', padding: 10, borderRadius: 8, marginTop: 10, marginBottom: 5, marginLeft: 10, marginRight: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                        <Text style={{ fontWeight: 'bold', fontSize: 15, color: 'white' }}>
                            Total Amount : Rs {calculatetotalAmount(SKUStockData)}
                        </Text>
                        <Text style={{ fontWeight: 'bold', fontSize: 15, color: 'white' }} >
                            Total Sales : {calculatetotalStockQty(SKUStockData)}
                        </Text>
                    </View>}

                    {Object.keys(storeData).length > 0 &&
                        <KeyboardAvoidingView style={[customStyle.keyba_view, customStyle.keyba_viewContent]} behavior="position" enabled keyboardVerticalOffset={(Platform.OS == 'ios' ? 10 : -100)} >

                            <FlatList
                                nestedScrollEnabled={true}
                                removeClippedSubviews={false}
                                scrollToOverflowEnabled={true}
                                legacyImplementation={true}
                                data={brandData}
                                extraData={rerenderdata}
                                ListHeaderComponent={_renderSalesFilter}
                                contentContainerStyle={customStyle.opening_Stock_scroll}
                                style={customStyle.opening_Stock_scrollOuter}
                                renderItem={({ item, index }) => {
                                    const cat = item;
                                    const catIndex = index;
                                    // get error field brand id
                                    let EF_brand = errorfield.EF_brand != null ? errorfield.EF_brand : {};
                                    let error_bid = EF_brand.CategoryId || '';
                                    return (
                                        <View style={customStyle.opening_Stock_wrap}>
                                            <View style={customStyle.opening_Stock_cat}>
                                                <LinearGradient colors={[PageTheme.$primary_color, PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                                    <Text style={customStyle.opening_Stock_catText}>{item.CategoryName}</Text>
                                                </LinearGradient>
                                            </View>
                                            <View style={customStyle.opening_Stock_prds}>
                                                {
                                                    <FlatList
                                                        nestedScrollEnabled={true}
                                                        removeClippedSubviews={false}
                                                        scrollToOverflowEnabled={true}
                                                        legacyImplementation={true}
                                                        data={item.skulist}
                                                        renderItem={({ item, index }) => {
                                                            const skus = item;
                                                            const sku_index = index;
                                                            let thisCatSkuData_i = SKUStockData.findIndex(i => i.CategoryId == cat.CategoryId && i.ProductId == skus.ProductId);
                                                            let thisCatSkuData = thisCatSkuData_i >= 0 ? (SKUStockData[thisCatSkuData_i] || {}) : {};
                                                            let stock = thisCatSkuData.Stock != null ? thisCatSkuData.Stock : '';

                                                            // get error field product id
                                                            let EF_product = errorfield.EF_product != null ? errorfield.EF_product : {};
                                                            let error_pid = EF_product.ProductId || '';
                                                            let EF_InputKey = errorfield.EF_InputKey;
                                                            let show_errorhere = error_bid == cat.CategoryId && error_pid == skus.ProductId;

                                                            let errorStyle_ST = (error && show_errorhere && EF_InputKey == 'input1_' ? customStyle.stk_inptSTyle_error : {});

                                                            return (
                                                                <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                                                    <View style={{}}>
                                                                        <Text style={customStyle.openStk_prd_name}>
                                                                            {skus.ArticleCode && skus.ArticleCode.trim() !== ""
                                                                                ? `${skus.ProductName} [${skus.ArticleCode}]`
                                                                                : skus.ARTICLE_CODE && skus.ARTICLE_CODE.trim() !== ""
                                                                                    ? `${skus.ProductName} [${skus.ARTICLE_CODE}]`
                                                                                    : skus.ProductName}
                                                                        </Text>

                                                                        {(showMrpPtr !== 'NA' || showMrpPtrRef.current !== 'NA') && (<Text
                                                                            style={{
                                                                                fontWeight: 'bold',
                                                                                backgroundColor: '#67abcaff',
                                                                                borderRadius: 10,

                                                                                paddingHorizontal: 8,
                                                                                paddingVertical: 4,
                                                                                color: 'white',
                                                                                flexWrap: 'wrap',
                                                                                alignSelf: 'flex-start',

                                                                            }}
                                                                            numberOfLines={1}
                                                                            ellipsizeMode="tail" // or "clip" if you don’t want "..."
                                                                        >

                                                                            {showMrpPtr + " : " + (showMrpPtr === 'PTR' ? skus?.ptr : skus?.Mrp)}

                                                                        </Text>)

                                                                        }

                                                                    </View>

                                                                    {(IsOpeningStockScreen == true || IsMidDayStockScreen == true || IsStockScreen == true) &&
                                                                        <View style={[customStyle.openStk_prddetails, customStyle.openStk_prd_borderT, customStyle.openStk_prd_borderB]}>
                                                                            <View style={[customStyle.openStk_prdd_wrap]}>
                                                                                {IsMidDayStockScreen == true &&
                                                                                    <View style={customStyle.openStk_prdd_wrap}>
                                                                                        <Text style={customStyle.openStk_prdd_flabel}>{`Opening Stock + Midday Stock : (${skus.OPENING_STOCK} + ${skus.MIDDAY_STOCK}) :`}</Text>
                                                                                        <Text style={customStyle.openStk_prdd_fvalue}>{(parseInt(skus.MIDDAY_STOCK) + parseInt(skus.OPENING_STOCK))}</Text>
                                                                                    </View>
                                                                                }
                                                                                {IsMidDayStockScreen == false && (IsStockScreen == true || IsOpeningStockScreen == true) &&
                                                                                    <Text style={customStyle.openStk_prdd_flabel}>{`Opening Stock : ${skus.OPENING_STOCK}`}</Text>
                                                                                }
                                                                            </View>
                                                                        </View>}
                                                                    <View style={[customStyle.openStk_prd_form, (IsOpeningStockScreen == false && IsMidDayStockScreen == false && IsStockScreen == false ? customStyle.openStk_prd_borderT2 : {})]}>
                                                                        {

                                                                            <View
                                                                                style={{ flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between' }}
                                                                            >
                                                                                <View style={customStyle.openStk_prd_row}>
                                                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                                                        <Text style={customStyle.openStk_prd_flexlabel}>Sale</Text>
                                                                                        <TextInput
                                                                                            ref={(reff) => { inputRefs.current['input1_' + cat.CategoryId + '_' + skus.ProductId] = reff; }}
                                                                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inputShort2, errorStyle_ST]}
                                                                                            placeholder=""
                                                                                            autoComplete='off'
                                                                                            placeholderTextColor={PageTheme.$placeholder_color}
                                                                                            value={(stock + '' || '')}
                                                                                            keyboardType='number-pad'
                                                                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                                                            blurOnSubmit={false}
                                                                                            onSubmitEditing={() => { focusToNext(cat, skus, '1') }}
                                                                                            onChangeText={(val) => { onStockValChange(cat, skus, val, 'Stock', 'numeric') }}
                                                                                        />
                                                                                    </View>

                                                                                </View>
                                                                                {stock !== undefined && stock !== '' && stock !== 0 && (showMrpPtr !== 'NA' || showMrpPtrRef.current !== 'NA') ? <View style={[customStyle.openStk_prd_colflex]}>
                                                                                    <Text style={{ fontWeight: 'bold' }}>Sale value :</Text>
                                                                                    <Text style={{ fontWeight: 'bold', marginStart: 2 }}>
                                                                                        {(() => {
                                                                                            const rate = skus?.ptr === 0;
                                                                                            const value = rate * (stock || 0);
                                                                                            return Number.isInteger(value) ? value : value.toFixed(2);
                                                                                        })()}
                                                                                    </Text>
                                                                                </View> : <></>}
                                                                            </View>
                                                                        }
                                                                    </View>
                                                                </View>
                                                            )
                                                        }} />
                                                }
                                            </View>
                                        </View>
                                    );
                                }}
                            />
                        </KeyboardAvoidingView>
                    }
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                        <GradientButton {...props} title={'Save'} onPress={() => { submitData() }} />
                    </View>
                </View>
            </LinearGradient>

            <Modal
                transparent={true}
                visible={modalVisible}
                onRequestClose={() => setModalVisible(false)}
                animationType="slide"
            >
                <View style={styles.modalBackground}>
                    <View style={styles.modalContainer}>
                        {renderModalContent()}
                    </View>
                </View>
            </Modal>
        </Container>
    );
}



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

const styles = StyleSheet.create({
    modalBackground: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalContainer: {
        paddingVertical: 16,
        paddingHorizontal: 10, // ✅ Reduce padding from left/right
        backgroundColor: '#fff',
        borderRadius: 10,
        maxHeight: '100%',
        width: '100%',
    },
    modalTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 10,
        textAlign: 'center',
        marginLeft: 20,
        marginRight: 20,
        color: 'black'
    },
    modalItem: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#ccc',
    },
    modalProduct: {
        fontSize: 14,
        alignContent: 'flex-start',
        textAlign: 'flex-start',
        padding: 5
    },
    modalButtons: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginTop: 20,
    },
    modalButton: {
        padding: 15,
        backgroundColor: '#0066cc',
        borderRadius: 50,
        width: '50%'
    },
    modalButtonText: {
        color: '#fff',
        fontWeight: 'bold',
        textAlign: 'center'
    },
    modalButtonYes: {
        padding: 15,
        backgroundColor: '#0066cc',
        borderRadius: 50,
        width: '50%',
        marginStart: 28
    },

    modalItemRow: {
        flexDirection: 'column',
        backgroundColor: '#F9F9F9',
        borderRadius: 5,
        marginBottom: 5,
        padding: 5,
        borderColor: '#ccc',
        marginHorizontal: 10,
    },

    qtyRow: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',

    },

    modalInput: {
        padding: 5,
        width: 60,
        alignContent: 'flex-start',
        textAlign: 'flex-start',
        color: 'black'
    },
    calculatedValue: {
        fontWeight: 'bold',
        color: '#333',
        minWidth: 60,
        padding: 5,
        alignContent: 'right',
        textAlign: 'right',
    },
    totalsContainer: {
        marginTop: 10,
        paddingVertical: 8,
        borderTopWidth: 1,
        borderColor: '#ccc',
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingHorizontal: 5,
    },

    totalText: {
        fontWeight: 'bold',
        fontSize: 16,
        color: '#000',
    },

});