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, Animated, Alert, KeyboardAvoidingView, 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 { checkMDStockScreenExists, getDownloadJson, getKPIFields, marktext1, marktext2, validateNumber } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { Card, Menu, Switch } from 'react-native-paper';
import { AntDesign, Fontisto, MaterialCommunityIcons } from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import { launchCamera, launchImageLibrary, CameraOptions } from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import cameraImg from '../assets/performics/camera_front_image.svg';
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { Q_GetAvailabityDefaultData, Q_MenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import DateTimePicker from '@react-native-community/datetimepicker';
import { CustomPicker2 } from '../components/CustomPicker';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import SearchableSelector from '../components/SearchableSelector';
import { KeyboardAwareFlatList } from 'react-native-keyboard-aware-scroll-view';

function Order(props) {
    const route = useRoute();
    const ST = props.StaticText || {};

    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);
    const animatedChoice = useRef(new Animated.Value(0)).current;

    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [SKUStockData, setSKUStockData] = useState([]);
    const [SystemPO, setSystemPO] = useState('');
    const [StorePO, setStorePO] = useState('');
    const [ContactName, setContactName] = useState('');
    const [ContactNo, setContactNo] = useState('');
    const [StockistDis, setStockistDis] = useState({});
    const [PODate, setPODate] = useState('');
    const [showRAllC_M, setShowRAllC_M] = useState(false);
    const [PODate2, setPODate2] = useState(new Date());
    const [reason, setReason] = useState({});
    const [ShowDatePicker, setShowDatePicker] = useState(false);
    const [KPIFields, setKPIFields] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [IsOrderPresent, setIsOrderPresent] = useState(0);
    const [reasons_list, setReasons_list] = useState([]);
    const [StockistList, setStockistList] = useState([]);
    const [StockistNew, setStockistNew] = useState('');
    const [StockisId, setStockistId] = useState('');
    const [modalVisible, setModalVisible] = useState(false);
    const [previewData, setPreviewData] = useState([]);
    const [showMrpPtr, setShowMrpPtr] = useState('NA');
    const showMrpPtrRef = useRef('NA');

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(SKUStockData);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');
    const IsOrderPresentRef = React.useRef(IsOrderPresent);
    const SystemPORef = React.useRef(SystemPO);
    const StorePORef = React.useRef(StorePO);
    const ContactNameRef = React.useRef(ContactName);
    const ContactNoRef = React.useRef(ContactNo);
    const PODateRef = React.useRef(PODate);
    const PODate2Ref = React.useRef(PODate2);
    const showRAllC_MRef = React.useRef(showRAllC_M);
    const StockistDisRef = React.useRef(StockistDis);
    const inputRefs = useRef({});

    const countries = ["Egypt", "Canada", "Australia", "Ireland", "Brazil", "England", "Dubai", "France", "Germany", "Saudi Arabia", "Argentina", "India"];
    const emojisWithIcons = [
        { StockistId: 'happy', StockistName: 'emoticon-happy-outline' },
        { StockistId: 'cool', StockistName: 'emoticon-cool-outline' },
        { StockistId: 'lol', StockistName: 'emoticon-lol-outline' },
        { StockistId: 'sad', StockistName: 'emoticon-sad-outline' },
        { StockistId: 'cry', StockistName: 'emoticon-cry-outline' },
        { StockistId: 'angry', StockistName: 'emoticon-angry-outline' },
        { StockistId: 'confused', StockistName: 'emoticon-confused-outline' },
        { StockistId: 'excited', StockistName: 'emoticon-excited-outline' },
        { StockistId: 'kiss', StockistName: 'emoticon-kiss-outline' },
        { StockistId: 'devil', StockistName: 'emoticon-devil-outline' },
        { StockistId: 'dead', StockistName: 'emoticon-dead-outline' },
        { StockistId: 'wink', StockistName: 'emoticon-wink-outline' },
        { StockistId: 'sick', StockistName: 'emoticon-sick-outline' },
        { StockistId: 'frown', StockistName: 'emoticon-frown-outline' },
    ];

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

        let SPO = storeData1.StoreId + '_' + moment().format('YYYYMMDDHHmmss');
        BgSystemPO(SPO);

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

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

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

    const _handleAppStateChange = async (nextAppState) => {
        if (nextAppState === 'background' && hasUnsavedChangesRef.current === true) {
            let newData = {
                storeBGData: WindowDataRef.current,
                menuName: ScreenNameRef.current,
                StoreId1: StoreIdRef.current,
                IsOrderPre: IsOrderPresentRef.current,
                BgSystemPOData: SystemPORef.current,
                BgStorePOData: StorePORef.current,
                BgContactNameData: ContactNameRef.current,
                BgContactNoData: ContactNoRef.current,
                BgPODateData: PODateRef.current,
                BgPODate2Data: PODate2Ref.current,
                BgshowRAllC_MData: showRAllC_MRef.current,
                visiteDate: d2,
                StockistDisBG: StockistDisRef.current
            };
            let WindowsStr = JSON.stringify(newData);
            await set_item('storeData', WindowsStr);
        }
    };

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

    function onBeforeRemove(e) {
        if (hasUnsavedChanges === true) {
            e.preventDefault();
            onRemoveScreen(e);
        } else {
            return;
        }
    }

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

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

    function BgSystemPO(val) {
        SystemPORef.current = val;
        setSystemPO(val);
    }

    function BgStorePO(val) {
        StorePORef.current = val;
        setStorePO(val);
    }

    function BgContactName(val) {
        ContactNameRef.current = val;
        setContactName(val);
    }

    function BgContactNo(val) {
        ContactNoRef.current = val;
        setContactNo(val);
    }

    function BgStockist(val) {
        StockistDisRef.current = val;
        setStockistDis(val);
    }

    function BgPODate(val) {
        PODateRef.current = val;
        setPODate(val);
    }

    function BgPODate2(val) {
        PODate2Ref.current = val;
        setPODate2(val);
    }

    function BgshowRAllC_M(val) {
        showRAllC_MRef.current = val;
        setShowRAllC_M(val);
    }

    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, StoreClassId, StoreCategoryId } = storeData1;
            let AllKPIFields = await getKPIFields(menu1);
            setKPIFields(AllKPIFields);
            let PODateAutoFillIndex = KPIFields.findIndex(i => i.KPIFieldName == 'PODateAutoFill');
            let PODateAutoFillKPIObj = PODateAutoFillIndex >= 0 ? KPIFields[PODateAutoFillIndex] : {};
            let PODateAutoFillEnable = PODateAutoFillIndex >= 0 ? PODateAutoFillKPIObj['KPIFieldEnable'] : true;
            if (PODateAutoFillEnable === true && (PODate === '' || PODate === null)) {
                let d1 = moment().format('DD/MM/YYYY');
                setPODate(d1);
            }
            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("tessdsdsd", showMrpPtrRef.current)
            let storeBGData1 = [], bgStoreJson = {}, IsOrdPresent = false, isBgDataExists = false;
            let windData = await get_item('storeData');
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData);
                let { storeBGData, menuName, StoreId1, visiteDate, IsOrderPre,
                    BgSystemPOData,
                    BgStorePOData,
                    BgContactNameData,
                    BgContactNoData,
                    BgPODateData,
                    BgPODate2Data,
                    BgshowRAllC_MData, StockistDisBG } = StoreJson;
                if (menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                    isBgDataExists = true;
                    storeBGData1 = storeBGData;
                    bgStoreJson = StoreJson;
                    IsOrdPresent = IsOrderPre;
                    BgStockist(StockistDisBG);
                    setIsOrderPresent(IsOrderPre);
                    IsOrderPresentRef.current = IsOrderPre;
                    var val1 = 0;
                    IsOrderPre == 1 ? val1 = 1 : '';
                    if (animatedChoice != null) {
                        Animated.timing(animatedChoice, {
                            toValue: val1,
                            duration: 400,
                            useNativeDriver: false,
                        }).start();
                    }
                    if (storeBGData.length > 0) {
                        BgWindowData(storeBGData);
                    }
                    if (BgSystemPOData != null && BgSystemPOData != '') {
                        BgSystemPO(BgSystemPOData);
                    }
                    BgStorePO(BgStorePOData);
                    BgContactName(BgContactNameData);
                    BgContactNo(BgContactNoData);
                    if (BgPODateData != null && BgPODateData != '') {
                        BgPODate(BgPODateData);
                    }
                    if (BgPODate2Data != null && BgPODate2Data != '') {
                        BgPODate2(BgPODate2Data);
                    }
                    BgshowRAllC_M(BgshowRAllC_MData);
                    BgUnsavedChanges(true);
                }
            }

            await db.transaction(async function (txn) {
                let q3 = `Select OrderReasonId as ReasonId, OrderReason as Reason From Master_NonOrderReason`;
                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);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                setReasons_list(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

                let q4 = `Select StockistId, StockistName From Master_Stockist`;
                await txn.executeSql(q4, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                setStockistList(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

                let seletlist = `IS_PRESENT, REASON_ID, REASON`;
                let q1 = `SELECT ${seletlist} from ${AppTables.ORDER}`;
                txn.executeSql(q1, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let isReasonId = data.REASON_ID != null ? data.REASON_ID : 0;
                            let isReason = data?.REASON != null ? data?.REASON : '';
                            let isPresent = data?.IS_PRESENT == 1 || data?.IS_PRESENT == '1';
                            if (i == txnres2.rows.length - 1) {
                                if (!isPresent) {
                                    setReason({ "label": isReason, "value": isReasonId });
                                }
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

                let join = ` INNER JOIN Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId `;
                let q = ` SELECT DISTINCT p.CategoryId, p.CategoryName, '' as MSL from Product_Master p ${join} Where mp.StoreId ='${StoreId}' and (IsCompetitor='0' or IsCompetitor =0) order by p.CategorySequence`;

                console.log("CatQuery", q)
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let arr = [], arr2 = [];
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            let SKU_d = await getSKU(data, storeData1, IsOrdPresent, bgStoreJson, isBgDataExists);
                            let skulist = SKU_d['skulist'] || [];
                            let skuData = SKU_d['skuData'] || [];
                            data['skulist'] = skulist;
                            arr.push(data);
                            // console.log("arrrr",JSON.stringify(arr))
                            arr2 = arr2.concat(skuData);
                            if (i == txnres.rows.length - 1) {
                                setBrandData(arr);
                                if (!isBgDataExists) {
                                    BgWindowData(arr2);
                                }
                                setProcessing(false);
                            }
                        }
                    } else {
                        setProcessing(false);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);
            });
        } catch (err) {
            console.log(err);
        }
    }

    function onselectionChange3(option, keyLbl, keyVal, otherData) {
        setReason(option);
    }

    async function getSKU(cat, storeData1 = {}, IsOrdPresent = false, bgStoreJson = [], isBgDataExists = false) {
        let defData = { 'skulist': [], 'skuData': [] };
        let { StoreId, ChainId, StateId, StoreTypeId, ExpiryStock, StoreClassId, StoreCategoryId } = storeData1;
        let bgStoreDataLength = Object.keys(bgStoreJson).length;
        return await new Promise(async (resolve, reject) => {
            db.transaction(async function (txn) {
                let seletlist = `p.ProductName, p.ProductId, ifnull(p.Mrp,0)as Mrp, ifnull(p.ptr,0)as ptr, o.IS_PRESENT, o.REASON_ID, o.REASON, o.STOCK, o.SYSTEM_PO, o.STORE_PO, o.PO_DATE, o.CONTACT_NAME, o.CONTACT_NO, o.STOCKIST_ID, o.STOCKIST_NAME`;
                let join2 = `Left Outer Join ${AppTables.ORDER} o on o.PRODUCT_ID=p.ProductId and (o.CATEGORY_ID='${cat.CategoryId}' or o.CATEGORY_ID=${cat.CategoryId}) and o.STORE_ID='${StoreId}' and o.VISIT_DATE='${d2}'`;
                let join = `inner join Mapping_ProductAssortmentStorewise m on p.ProductId=m.ProductId `;
                let q1 = `SELECT ${seletlist} from Product_Master p ${join} ${join2} where m.StoreId='${StoreId}' and (p.CategoryId='${cat.CategoryId}' or p.CategoryId=${cat.CategoryId}) and (p.IsCompetitor='0' or p.IsCompetitor=0) order by p.ProductSequence `;

                console.log("sku_query", q1)
                txn.executeSql(q1, [], async function (txn2, txnres) {
                    console.log("length", txnres.rows.length)
                    if (txnres.rows.length > 0) {
                        let arr = [], arr2 = [], isAdded = false;
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);

                            let { SYSTEM_PO, STORE_PO, PO_DATE, IS_PRESENT, CONTACT_NAME, CONTACT_NO, STOCKIST_ID, STOCKIST_NAME } = data;
                            inputRefs.current['input1_' + cat.CategoryId + '_' + data.ProductId] = '';

                            data.ptr = showMrpPtrRef.current === 'PTR' ? data.ptr : data.Mrp
                            console.log("data-------", data.ptr, showMrpPtrRef.current)
                            arr.push(data);
                            let defData1 = { 'CategoryId': cat.CategoryId, 'ProductId': data.ProductId, 'Stock': data.STOCK, 'ProductName': data.ProductName, 'CategoryName': cat.CategoryName };
                            arr2.push(defData1);
                            let isReasonId = data.REASON_ID != null ? data.REASON_ID : 0;
                            let isReason = data?.REASON != null ? data?.REASON : '';
                            let isPresent = IS_PRESENT == 1 || IS_PRESENT == '1';
                            if (isPresent && !isAdded) {
                                BgSystemPO(SYSTEM_PO);
                                BgStorePO(STORE_PO);
                                BgContactName(CONTACT_NAME);
                                BgContactNo(CONTACT_NO);
                                BgStockist(STOCKIST_NAME);
                                let d1 = moment(PO_DATE).format('DD/MM/YYYY');
                                let d2 = new Date(PO_DATE);
                                BgPODate(d1);
                                BgPODate2(d2);
                                setStockistNew(STOCKIST_NAME);
                                setStockistId(STOCKIST_ID);
                                if (isBgDataExists) {
                                    isPresent = IsOrdPresent == '1' || IsOrdPresent == 1 ? 1 : 0;
                                }
                                isAdded = true;

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

                            if (i == txnres.rows.length - 1) {
                                defData['skulist'] = arr;
                                defData['skuData'] = arr2;
                                resolve(defData);
                            }
                        }
                    } else {
                        let isPresent = 0;
                        if (isBgDataExists) {
                            isPresent = IsOrdPresent == '1' || IsOrdPresent == 1 ? 1 : 0;
                        }
                        Animated.timing(animatedChoice, {
                            toValue: isPresent,
                            duration: 400,
                            useNativeDriver: false,
                        }).start();
                        IsOrderPresentRef.current = isPresent;
                        setIsOrderPresent(isPresent);

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

    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];
            nextRef.focus();
        } else {
            return;
        }
    }

    async function submitData() {
        let isValid = await validate();
        if (isValid) {
            Keyboard.dismiss();
            if (IsOrderPresentRef.current == 1 && (showMrpPtr !== 'NA'||showMrpPtrRef.current!=='NA')) {
                setModalVisible(true); // Show modal immediately
                // Generate preview data
                const preview = [];
                brandData?.forEach(cat => {
                    (cat.skulist || []).forEach(sku => {
                        const skuData = SKUStockData.find(ci => ci.CategoryId === cat.CategoryId && ci.ProductId === sku.ProductId) || { Stock: '' };
                        if (skuData?.Stock != '' && parseInt(skuData?.Stock) > 0) {
                            preview.push({ CategoryName: cat.CategoryName, ProductName: sku.ProductName, Stock: skuData.Stock || '', ptr: sku?.ptr });
                        }
                    });
                });

                setPreviewData(preview); // Update state with preview data
            } 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.ORDER} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('Order data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);
            });
            await db.transaction(async function (txn) {
                var stock_values = '';
                let ReasonId = reason?.value != null ? reason?.value : 0;
                let Reason = reason?.label != null ? reason?.label : '';
                if (IsOrderPresent == 1) {
                    let PO_date1_MDY = moment(PODate2).format('MM/DD/YYYY');
                    for (var i = 0; i < SKUStockData.length; i++) {
                        let { CategoryId, ProductId, Stock } = SKUStockData[i];
                        let catIndex = brandData.findIndex(a => a.CategoryId == CategoryId);
                        let cat = catIndex >= 0 ? brandData[catIndex] : {};
                        let CategoryName = cat.CategoryName || '';
                        let skulist = cat.skulist || [];
                        let skuItem_in = skulist.findIndex(b => b.ProductId == ProductId);
                        let skuItem = skuItem_in >= 0 ? skulist[skuItem_in] : {};

                        stock_values += stock_values != '' ? ' , ' : '';
                        let stockValue = Stock != null && Stock !== '' && Stock !== 'undefined' ? Stock : '0';
                        stock_values += ` ('${StoreId}', '${d2}', '${CategoryName}', '${CategoryId}', '${skuItem.ProductName}', '${ProductId}', '', '1', '${(stockValue || '0')}', '${SystemPO}', '${StorePO}', '${PO_date1_MDY}', '${ContactName}', '${ContactNo}', '${d2}', '', '0', '${StockistDis?.StockistId || StockisId}', '${StockistDis?.StockistName || StockistNew}') `;
                    }
                } else {
                    stock_values += ` ('${StoreId}', '${d2}', '', '', '', '', '', '0', '', '', '', '', '', '', '${d2}', '${ReasonId}', '${Reason}', '${StockistDis?.StockistId || StockisId}', '${StockistDis?.StockistName || StockistNew}') `;
                }

                let add_Stock = `INSERT INTO ${AppTables.ORDER} (STORE_ID, VISIT_DATE, CATEGORY, CATEGORY_ID, PRODUCT, PRODUCT_ID, MSL, IS_PRESENT, STOCK, SYSTEM_PO, STORE_PO, PO_DATE, CONTACT_NAME, CONTACT_NO, ADDED_DATE, REASON_ID, REASON, STOCKIST_ID, STOCKIST_NAME) VALUES ${stock_values} `;
                await txn.executeSql(add_Stock, [], async function (txn2, txnres) {
                    console.log('Order added');
                    clear_item('storeData');
                    notify('Order updated successfully');
                    setProcessing(false);
                    props.navigation.goBack();
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot update order'); },);
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function validate() {
        let isValid = true;

        let ShowStorePOIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowStorePO');
        let ShowStorePOKPIObj = ShowStorePOIndex >= 0 ? KPIFields[ShowStorePOIndex] : {};
        let ShowStorePOEnable = ShowStorePOIndex >= 0 ? ShowStorePOKPIObj['KPIFieldEnable'] : true;
        let ShowStorePODis_Name = ShowStorePOIndex >= 0 ? ShowStorePOKPIObj['KPIFieldDisplayName'] : 'Store PO';

        let ShowPODateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowPODate');
        let ShowPODateKPIObj = ShowPODateIndex >= 0 ? KPIFields[ShowPODateIndex] : {};
        let ShowPODateEnable = ShowPODateIndex >= 0 ? ShowPODateKPIObj['KPIFieldEnable'] : true;
        let ShowPODateDis_Name = ShowPODateIndex >= 0 ? ShowPODateKPIObj['KPIFieldDisplayName'] : 'PO Date';

        let PODateAutoFillIndex = KPIFields.findIndex(i => i.KPIFieldName == 'PODateAutoFill');
        let PODateAutoFillKPIObj = PODateAutoFillIndex >= 0 ? KPIFields[PODateAutoFillIndex] : {};
        let PODateAutoFillEnable = PODateAutoFillIndex >= 0 ? PODateAutoFillKPIObj['KPIFieldEnable'] : true;

        let ShowCNameIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowContactName');
        let ShowCNameKPIObj = ShowCNameIndex >= 0 ? KPIFields[ShowCNameIndex] : {};
        let ShowCNameEnable = ShowCNameIndex >= 0 ? ShowCNameKPIObj['KPIFieldEnable'] : true;
        let ShowCNameMand = ShowCNameIndex >= 0 && ShowCNameKPIObj['KPIMandatory'] != null ? (ShowCNameKPIObj['KPIMandatory'] == 1 || ShowCNameKPIObj['KPIMandatory'] == '1' ? true : false) : true;
        let ShowCNameDis_Name = ShowCNameIndex >= 0 ? ShowCNameKPIObj['KPIFieldDisplayName'] : 'Contact Name';

        let ShowCNoIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowContactNumber');
        let ShowCNoKPIObj = ShowCNoIndex >= 0 ? KPIFields[ShowCNoIndex] : {};
        let ShowCNoEnable = ShowCNoIndex >= 0 ? ShowCNoKPIObj['KPIFieldEnable'] : true;
        let ShowCNoMand = ShowCNoIndex >= 0 && ShowCNoKPIObj['KPIMandatory'] != null ? (ShowCNoKPIObj['KPIMandatory'] == 1 || ShowCNoKPIObj['KPIMandatory'] == '1' ? true : false) : true;
        let ShowCNoDis_Name = ShowCNoIndex >= 0 ? ShowCNoKPIObj['KPIFieldDisplayName'] : 'Contact Number';

        let ShowReasonIndex = KPIFields.findIndex(i => i.KPIFieldName == 'IsReasonEnable');
        let ShowReasonKPIObj = ShowReasonIndex >= 0 ? KPIFields[ShowReasonIndex] : {};
        let ShowReasonEnable = ShowReasonIndex >= 0 ? ShowReasonKPIObj['KPIFieldEnable'] : true;

        if (IsOrderPresent == true) {
            if (ShowPODateEnable == true && PODateAutoFillEnable == false && (PODate == '' || PODate == null)) {
                notify('Please enter ' + ShowPODateDis_Name + '!', 'SHORT');
                isValid = false;
            } else if (ShowCNameEnable == true && ShowCNameMand == true && (ContactName == '' || ContactName == null)) {
                notify('Please enter ' + ShowCNameDis_Name + '!', 'SHORT');
                isValid = false;
            } else if (ShowCNoEnable == true && ShowCNoMand == true && (ContactNo == '' || ContactNo == null)) {
                notify('Please enter ' + ShowCNoDis_Name + '!', 'SHORT');
                isValid = false;
            } else if (ShowCNoEnable == true && ShowCNoMand == true && (ContactNo.length != 10)) {
                notify('Please enter valid ' + ShowCNoDis_Name + '!', 'SHORT');
                isValid = false;
            }
            else if (!StockistDis || (typeof StockistDis === 'object' && (StockistDis.StockistId === '' || StockistDis.StockistId == null)) || (typeof StockistDis === 'string' && StockistDis.trim() === '')) {
                notify('Please select Distributor name!', 'SHORT');
                isValid = false;
            } else {
                isValid = false
                for (const item of brandData) {
                    const skulist = item.skulist || [];

                    for (const skuItem of skulist) {
                        const skuData = SKUStockData.find(
                            (ci) => ci.CategoryId == item.CategoryId && ci.ProductId == skuItem.ProductId
                        ) || {};

                        const stockQty = parseInt(skuData?.Stock ?? 0, 10);
                        console.log("skuData?.Stock", skuData?.Stock)
                        if (stockQty > 0) {
                            isValid = true; // At least one SKU has quantity > 0
                            break; // No need to check further
                        }
                    }

                    if (isValid) break; // Stop outer loop if already valid
                }

                if (!isValid) {
                    notify("Please enter Order Qty greater than zero for at least one SKU", "SHORT");
                }
            }
        } else if (ShowReasonEnable == true && (reason?.value == null || reason?.value == '' || reason?.value == 0)) {
            notify('Please select reason', 'SHORT');
            isValid = false;
        }
        return isValid;
    }

    function onConfirmRemoveAll() {
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: 0,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        IsOrderPresentRef.current = 0;
        setIsOrderPresent(0);
        BgUnsavedChanges(true);
        BgStorePO('');
        BgContactName('');
        BgContactNo('');
        setSKUStockData([]);
        BgshowRAllC_M(false);
    }

    function onChoiceSelect(val, key) {
        if (val == 0 && SKUStockData.length > 0) {
            BgshowRAllC_M(true);
            return;
        }
        var val1 = val == 1 ? 1 : 0;
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        IsOrderPresentRef.current = val;
        setIsOrderPresent(val);
        BgUnsavedChanges(true);
        if (val1 == 1) {
            setReason({ "label": '', "value": 0 });
        }
        if (val == 0) {
            setSKUStockData([]);
        }
    }

    function onStockValChange(item, skuItem, val, key, type = '') {
        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);
        setSKUStockData(allSKUData);
        BgUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function onSaveCancel() {
        setShowAlert(false);
    }

    function renderDatePicker() {
        let today = new Date();
        let d1 = PODate2 != null && PODate2 != '' ? PODate2 : new Date();
        return (
            <DateTimePicker
                testID="dateTimePicker"
                value={d1}
                mode={'date'}
                display="default"
                maximumDate={today}
                onChange={(event, selectedDate) => {
                    if (selectedDate != null) {
                        let d1 = moment(selectedDate).format('DD/MM/YYYY');
                        setShowDatePicker(false);
                        BgPODate2(selectedDate);
                        BgPODate(d1);
                    }
                }}
            />
        );
    }

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

        let ShowSystemPOIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowSystemPO');
        let ShowSystemPOKPIObj = ShowSystemPOIndex >= 0 ? KPIFields[ShowSystemPOIndex] : {};
        let ShowSystemPOEnable = ShowSystemPOIndex >= 0 ? ShowSystemPOKPIObj['KPIFieldEnable'] : true;
        let ShowSystemPODis_Name = ShowSystemPOIndex >= 0 ? ShowSystemPOKPIObj['KPIFieldDisplayName'] : 'System PO';

        let ShowStorePOIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowStorePO');
        let ShowStorePOKPIObj = ShowStorePOIndex >= 0 ? KPIFields[ShowStorePOIndex] : {};
        let ShowStorePOEnable = ShowStorePOIndex >= 0 ? ShowStorePOKPIObj['KPIFieldEnable'] : true;
        let ShowStorePODis_Name = ShowStorePOIndex >= 0 ? ShowStorePOKPIObj['KPIFieldDisplayName'] : 'Store PO';

        let ShowPODateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowPODate');
        let ShowPODateKPIObj = ShowPODateIndex >= 0 ? KPIFields[ShowPODateIndex] : {};
        let ShowPODateEnable = ShowPODateIndex >= 0 ? ShowPODateKPIObj['KPIFieldEnable'] : true;
        let ShowPODateDis_Name = ShowPODateIndex >= 0 ? ShowPODateKPIObj['KPIFieldDisplayName'] : 'PO Date';

        let PODateAutoFillIndex = KPIFields.findIndex(i => i.KPIFieldName == 'PODateAutoFill');
        let PODateAutoFillKPIObj = PODateAutoFillIndex >= 0 ? KPIFields[PODateAutoFillIndex] : {};
        let PODateAutoFillEnable = false; //PODateAutoFillIndex >= 0 ? PODateAutoFillKPIObj['KPIFieldEnable'] : true;

        let ShowCNameIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowContactName');
        let ShowCNameKPIObj = ShowCNameIndex >= 0 ? KPIFields[ShowCNameIndex] : {};
        let ShowCNameEnable = ShowCNameIndex >= 0 ? ShowCNameKPIObj['KPIFieldEnable'] : true;
        let ShowCNameDis_Name = ShowCNameIndex >= 0 ? ShowCNameKPIObj['KPIFieldDisplayName'] : 'Contact Name';

        let ShowCNoIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowContactNumber');
        let ShowCNoKPIObj = ShowCNoIndex >= 0 ? KPIFields[ShowCNoIndex] : {};
        let ShowCNoEnable = ShowCNoIndex >= 0 ? ShowCNoKPIObj['KPIFieldEnable'] : true;
        let ShowCNoDis_Name = ShowCNoIndex >= 0 ? ShowCNoKPIObj['KPIFieldDisplayName'] : 'Contact Number';

        let ShowReasonIndex = KPIFields.findIndex(i => i.KPIFieldName == 'IsReasonEnable');
        let ShowReasonKPIObj = ShowReasonIndex >= 0 ? KPIFields[ShowReasonIndex] : {};
        let ShowReasonEnable = ShowReasonIndex >= 0 ? ShowReasonKPIObj['KPIFieldEnable'] : true;

        const calculateTotalValue = () => {
            let total = 0;
            brandData.forEach((cat) => {
                (cat.skulist || []).forEach((sku) => {
                    const thisCatSkuDataIndex = SKUStockData.findIndex(
                        (i) => i.CategoryId === cat.CategoryId && i.ProductId === sku.ProductId
                    );
                    const stock =
                        thisCatSkuDataIndex >= 0
                            ? SKUStockData[thisCatSkuDataIndex].Stock || 0
                            : 0;
                    total += sku?.ptr * (parseFloat(stock) || 0);
                });
            });
            return total.toFixed(2);
        };

        const calculateTotalStockQty = () => {
            let totalStockQty = 0;

            brandData.forEach((cat) => {
                (cat.skulist || []).forEach((sku) => {
                    const thisCatSkuDataIndex = SKUStockData.findIndex(
                        (i) => i.CategoryId === cat.CategoryId && i.ProductId === sku.ProductId
                    );

                    // ✅ Get Stock Value
                    const stock =
                        thisCatSkuDataIndex >= 0
                            ? parseFloat(SKUStockData[thisCatSkuDataIndex].Stock) || 0
                            : 0;

                    // ✅ Add Stock Qty only
                    totalStockQty += stock;
                });
            });

            return totalStockQty;
        };


        return (
            <View style={customStyle.Orders_PageWrap}>
                <View style={[customStyle.addvis_pCon, { flexDirection: 'row', alignItems: 'center' }]}>
                    <Text style={[customStyle.addvis_pText, { flex: 1 }]}>{'Is Present'}</Text>

                    <View style={[customStyle.addvis_pChoiceBoxCon, { flex: 2 }, IsOrderPresentRef.current == 1 ? { alignItems: 'center' } : {}]}>
                        <View style={[customStyle.openStk_prd_choiceBox, customStyle.addvis_pChoiceBoxbg]}>
                            <Animated.View style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, (IsOrderPresent == '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, (IsOrderPresent == 1 ? customStyle.openStkCh_textactive : {})]}>Yes</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(0, 'isPresent') }}>
                                <Text style={[customStyle.openStkCh_text, (IsOrderPresent == 0 ? customStyle.openStkCh_textactive : {})]}>No</Text>
                            </TouchableOpacity>
                        </View>
                    </View>

                    {IsOrderPresentRef.current == 1 ?
                        <View style={{ alignItems: 'center', flex: 1 }}>
                            <TouchableOpacity
                                style={{
                                    backgroundColor: 'transparent',
                                    borderRadius: 6,
                                    borderWidth: 1,
                                    borderColor: '#d4e7ffff',
                                    paddingVertical: 8,
                                    paddingHorizontal: 10,
                                    minWidth: 100, // optional, gives a consistent size
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    shadowColor: 'transparent',
                                    shadowOpacity: 0.1,
                                    shadowOffset: { width: 0, height: 2 },
                                    shadowRadius: 4,
                                    elevation: 2, // for Android shadow
                                }}
                                activeOpacity={0.4} // opacity effect when pressed
                                onPress={() => {
                                    console.log('Prev. Orders clicked');
                                    // 👉 put your navigation or action here
                                    props.navigation.navigate("PrevOrders", { storeData })
                                }}
                            >
                                <Text
                                    style={{
                                        fontWeight: 'normal',
                                        fontSize: 14,
                                        color: '#006AF4',
                                    }}
                                >
                                    Prev. Orders
                                </Text>
                            </TouchableOpacity>
                        </View>
                        : <></>}
                </View>

                {(IsOrderPresent != '1' && ShowReasonEnable == true) &&
                    <View style={[customStyle.openStk_prd_colflex, customStyle.pt10, customStyle.mb10]}>
                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel1]}>{ST.SelectReason}</Text>
                        {<CustomPicker2 {...props} Pickerdata={reasons_list} label_key={'Reason'} value_key={'ReasonId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'}
                            onChange={onselectionChange3}
                            selected_data={{ value: reason?.label }}
                            InputStyle={customStyle.PV_selectInputStyle1}
                            selectStyle={customStyle.PV_selectStyle} ErrorStyle={{}}
                        />}
                    </View>
                }

                {IsOrderPresent != '0' && (showMrpPtr !== 'NA'|| showMrpPtrRef.current!=='NA') && (
                    <View style={{ backgroundColor: '#67abcaff', padding: 10, borderRadius: 8, marginBottom: 4, marginLeft: 10, marginRight: 10, flexDirection: 'row', justifyContent: 'space-between' }}>
                        <Text style={{ fontWeight: 'bold', fontSize: 15, color: 'white' }}>
                            Total values : Rs {calculateTotalValue()}
                        </Text>
                        <Text style={{ fontWeight: 'bold', fontSize: 15, color: 'white' }} >
                            Total Qty : {calculateTotalStockQty()}
                        </Text>
                    </View>
                )}

                {(IsOrderPresent == true && Object.keys(storeData).length > 0) &&
                    <KeyboardAvoidingView style={[customStyle.keyba_view, customStyle.keyba_viewContent]} behavior="position" enabled keyboardVerticalOffset={(Platform.OS == 'ios' ? 10 : -100)}>
                        <ScrollView
                            contentContainerStyle={customStyle.opening_Stock_scroll}
                            style={customStyle.opening_Stock_scrollOuter}
                        >
                            {(ShowSystemPOEnable == true) &&
                                <View style={[customStyle.openStk_prd_row, customStyle.mb10]}>
                                    <View style={[customStyle.openStk_prd_colflex]}>
                                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ShowSystemPODis_Name}</Text>
                                        <Text style={[customStyle.openStk_prd_labelValRed]}>{SystemPO}</Text>
                                    </View>
                                </View>
                            }
                            {(ShowStorePOEnable == true) &&
                                <View style={[customStyle.openStk_prd_row, customStyle.mb10]}>
                                    <View style={[customStyle.openStk_prd_colflex]}>
                                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ShowStorePODis_Name}</Text>
                                        <TextInput
                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inplBlue]}
                                            placeholder=""
                                            autoComplete='off'
                                            placeholderTextColor={PageTheme.$placeholder_color}
                                            value={StorePO}
                                            onChangeText={(val) => { BgStorePO(val) }}
                                        />
                                    </View>
                                </View>
                            }
                            {(ShowPODateEnable == true) &&
                                <View style={[customStyle.openStk_prd_row, customStyle.mb10]}>
                                    <View style={[customStyle.openStk_prd_colflex]}>
                                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ShowPODateDis_Name}</Text>
                                        {PODateAutoFillEnable == true &&
                                            <Text style={[customStyle.openStk_prd_labelValRed]}>{PODate}</Text>}
                                        {PODateAutoFillEnable != true &&
                                            <View style={[customStyle.AddStockM_col, customStyle.openStk_prd_date_inputCon]} >
                                                <Text style={customStyle.openStk_prd_dateInput}>{PODate}</Text>
                                                <TouchableOpacity style={customStyle.openStk_prd_datePicker} onPress={() => { setShowDatePicker(true); }}>
                                                    <Fontisto size={20} color={PageTheme.$accent_color} name="date" />
                                                </TouchableOpacity>
                                            </View>}
                                        {(ShowDatePicker == true && PODateAutoFillEnable != true) &&
                                            renderDatePicker()
                                        }
                                    </View>
                                </View>
                            }
                            {(ShowCNameEnable == true) &&
                                <View style={[customStyle.openStk_prd_row, customStyle.mb10]}>
                                    <View style={[customStyle.openStk_prd_colflex]}>
                                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ShowCNameDis_Name}</Text>
                                        <TextInput
                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inplBlue]}
                                            placeholder=""
                                            autoComplete='off'
                                            placeholderTextColor={PageTheme.$placeholder_color}
                                            value={ContactName}
                                            onChangeText={(val) => { BgContactName(val) }}
                                        />
                                    </View>
                                </View>
                            }
                            {(ShowCNoEnable == true) &&
                                <View style={[customStyle.openStk_prd_row, customStyle.mb10]}>
                                    <View style={[customStyle.openStk_prd_colflex]}>
                                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ShowCNoDis_Name}</Text>
                                        <TextInput
                                            style={[customStyle.openStk_prd_inputStyle, customStyle.openStk_prd_flex_inputStyle, customStyle.openStk_prd_inplBlue]}
                                            placeholder=""
                                            autoComplete='off'
                                            keyboardType='phone-pad'
                                            maxLength={10}
                                            placeholderTextColor={PageTheme.$placeholder_color}
                                            value={ContactNo}
                                            onChangeText={(val) => { BgContactNo(val) }}
                                        />
                                    </View>
                                </View>
                            }

                            {ShowCNoEnable === true && (
                                <View style={[customStyle.openStk_prd_row, customStyle.mb10]}>
                                    <View style={[customStyle.openStk_prd_colflex]}>
                                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>
                                            {"Distributor List"}
                                        </Text>

                                        {(() => {
                                            const formattedList = StockistList.map(item => ({
                                                StockistName: item.StockistName,
                                                StockistId: item.StockistId
                                            }));
                                            const matched = formattedList.find(item => item.StockistName === StockistDis);
                                            return (
                                                <SearchableSelector
                                                    data={formattedList}
                                                    placeholder="Select Distributor"
                                                    customStyle={customStyle}
                                                    selectedVal={matched}
                                                    setSelectedVal={BgStockist}
                                                />
                                            );
                                        })()}
                                    </View>
                                </View>
                            )}

                            {rerenderdata == rerenderdata && brandData.length > 0 && (
                                <KeyboardAwareFlatList
                                    data={brandData}
                                    keyExtractor={(item, index) => `category-${item.CategoryId.toString() || index}`}
                                    renderItem={({ item: cat, index: catIndex }) => (
                                        <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}>
                                                        {cat.CategoryName}
                                                    </Text>
                                                </LinearGradient>
                                            </View>

                                            <View style={customStyle.opening_Stock_prds}>
                                                {console.log("cat?.skulist", cat?.skulist.length)}
                                                {(
                                                    <KeyboardAwareFlatList
                                                        data={cat?.skulist || []}
                                                        keyExtractor={(item, index) => `sku-${item.ProductId || index}`}
                                                        renderItem={({ item: skus, index: skuIndex }) => {
                                                            const thisCatSkuDataIndex = SKUStockData.findIndex((i) => i.CategoryId === cat.CategoryId && i.ProductId === skus.ProductId);
                                                            const thisCatSkuData =
                                                                thisCatSkuDataIndex >= 0
                                                                    ? SKUStockData[thisCatSkuDataIndex] || {}
                                                                    : {};
                                                            const stock =
                                                                thisCatSkuData.Stock != null ? thisCatSkuData.Stock : '';

                                                            return (
                                                                <View style={customStyle.openStk_prd_Con}>
                                                                    <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                                                                        <Text style={customStyle.openStk_prd_name}>
                                                                            {skus.ProductName}
                                                                        </Text>
                                                                        {(showMrpPtr !== 'NA'|| showMrpPtrRef.current!=='NA') && (
                                                                            <Text style={{ fontWeight: 'bold', backgroundColor: '#67abcaff', borderRadius: 10, padding: 5, color: 'white' }}>
                                                                                {showMrpPtr + " : " + skus?.ptr}
                                                                            </Text>
                                                                        )}
                                                                    </View>

                                                                    <View
                                                                        style={[
                                                                            customStyle.openStk_prd_form,
                                                                            customStyle.openStk_prd_borderT,
                                                                            customStyle.pt10,
                                                                        ]}
                                                                    >
                                                                        <View style={customStyle.openStk_prd_row}>
                                                                            <View style={customStyle.openStk_prd_colflex}>
                                                                                <Text style={customStyle.openStk_prd_flexlabel}>
                                                                                    Order Qty
                                                                                </Text>
                                                                                <TextInput
                                                                                    ref={(reff) => {
                                                                                        inputRefs.current[
                                                                                            `input1_${cat.CategoryId}_${skus.ProductId}`
                                                                                        ] = reff;
                                                                                    }}
                                                                                    style={[
                                                                                        customStyle.openStk_prd_inputStyle,
                                                                                        customStyle.order_taking_input,
                                                                                    ]}
                                                                                    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>
                                                                        {(showMrpPtr !== 'NA'|| showMrpPtrRef.current!=='NA') && (
                                                                            <View style={{ flexDirection: 'row', marginTop: 12 }}>
                                                                                <Text style={{ fontWeight: 'bold' }}>Order value:</Text>
                                                                                <Text style={{ fontWeight: 'bold', marginStart: 14 }}>
                                                                                    {Number.isInteger(skus?.ptr * stock)
                                                                                        ? skus?.ptr * stock
                                                                                        : (skus?.ptr * stock).toFixed(2)}
                                                                                </Text>
                                                                            </View>
                                                                        )}
                                                                    </View>
                                                                </View>
                                                            );
                                                        }}
                                                    />
                                                )}
                                            </View>
                                        </View>
                                    )}
                                />
                            )}
                        </ScrollView>
                    </KeyboardAvoidingView>
                }
            </View>
        );
    }

    const handleUpdateStock = (item, newStock) => {
        let updatedData = previewData.map(data =>
            data.ProductName === item.ProductName ? { ...data, Stock: newStock } : data
        );
        setPreviewData(updatedData);

        let allSKUData = [...SKUStockData];
        let defData = { 'CategoryId': item.CategoryId, 'ProductId': item.ProductId };
        const skud_index = allSKUData.findIndex(i => i.CategoryId === item.CategoryId && i.ProductId === item.ProductId);
        const skud = skud_index >= 0 ? (allSKUData[skud_index] || defData) : defData;
        skud['Stock'] = newStock;

        skud_index >= 0 ? allSKUData[skud_index] = skud : allSKUData.push(skud);
        setSKUStockData(allSKUData);
        BgUnsavedChanges(true);
    };

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

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

                <KeyboardAwareFlatList
                    data={previewData}
                    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'}
                                    onChangeText={(val) => handleUpdateStock(item, val)}
                                />
                                <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 Qty: {totalStockQty}</Text>
                    <Text style={styles.totalText}>Total Amount: {totalAmount.toFixed(2)}</Text>
                </View>

                <View style={styles.modalButtons}>
                    <TouchableOpacity
                        style={styles.modalButton}
                        onPress={() => { setModalVisible(false); setShowAlert(true); }}
                    >
                        <Text style={styles.modalButtonText}>OK</Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    };


    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            {ConfirmSaveAlert(props, showRAllC_M, () => { BgshowRAllC_M(false) }, onConfirmRemoveAll, 'Do you really want to remove all Order Data?')}
            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
                <View style={[customStyle.pageContentWrapper]}>
                    {_render_PresentQ()}
                    <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>
    );
}

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
    },
    modalItem: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#ccc',
    },
    modalProduct: {
        fontSize: 14,
    },
    modalButtons: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginTop: 20,
    },
    modalButton: {
        padding: 15,
        backgroundColor: '#0066cc',
        borderRadius: 50,
        width: '50%'
    },
    modalButtonText: {
        color: '#fff',
        fontWeight: 'bold',
        textAlign: 'center'
    },

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

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

    },

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

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

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