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, ScrollView, TouchableOpacity, Platform, PermissionsAndroid, Animated, 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 { 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, Fontisto, MaterialCommunityIcons } 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 DateTimePicker from '@react-native-community/datetimepicker';
import { CustomPicker2 } from '../components/CustomPicker';
import SearchableSelector from '../components/SearchableSelector';
import { KeyboardAwareFlatList } from 'react-native-keyboard-aware-scroll-view';

// import { log } from '@react-native-firebase/crashlytics';



function Order(props) {
  const route = useRoute();
  const ST = props.StaticText || {};
  const { item } = route.params;
  //console.log("checkprops-->", props)

  // get all theme styles acc to current theme set 
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const animatedChoice = useRef(new Animated.Value(0)).current;



  const [processing, setProcessing] = useState(false);
  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 [searchedItem, setSearchedItem] = useState('');
  const [storeList, setStoreList] = useState([]);
  const [selectedStore, setSelectedStore] = useState(null);
  const [previewData, setPreviewData] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  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');

  const fetchAndInsertData = async () => {
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    //console.log("loginDetails",loginDetails);

    try {
      const response = await fetch(
        'https://ap1.parinaam.in/Webservice/GenericService.svc/downloadJson',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            Downloadtype: 'StoreList_OfflineOrder',
            Param1: '',
            Param2: Platform.OS == "ios" ? "iOS" : "Android",
            Username: loginDetails.UserId,
          }),
        }
      );


      const rawJson = await response.json();
      //console.log('typeof rawJson:', typeof rawJson);

      let json = rawJson;

      if (typeof rawJson === 'string') {
        json = JSON.parse(rawJson);
      }

      // console.log('Parsed json:', json);

      const storeList = json?.StoreList_OfflineOrder;
      console.log('storeList:', storeList);


      if (Array.isArray(storeList) && storeList.length > 0) {
        console.log("Inserting store list...");
        setProcessing(true)

        db.transaction(
          tx => {
            // First delete OFFLINE_ORDER table data
            tx.executeSql(
              'DELETE FROM OFFLINE_ORDER',
              [],
              (_, result) => {
                console.log('Old OFFLINE_ORDER data cleared.');
              },
              (_, error) => {
                console.log('Failed to clear OFFLINE_ORDER data:', error);
                return true; // stop transaction on failure
              }
            );
            tx.executeSql(
              'DELETE FROM StoreList_OfflineOrder',
              [],
              (_, result) => {
                console.log('Old store data cleared.');
              },
              (_, error) => {
                console.log('Failed to clear old store data:', error);
                return true; // stop transaction on failure
              }
            );


            storeList.forEach(item => {
              console.log("Inserting item:", item);

              tx.executeSql(
                `INSERT INTO StoreList_OfflineOrder 
                (storeId, StoreName, Address, Pincode, CityName, StoreType, VisitDate)
                VALUES (?, ?, ?, ?, ?, ?, ?)`,
                [
                  item.storeId,
                  item.StoreName,
                  item.Address,
                  item.Pincode,
                  item.CityName,
                  item.StoreType,
                  item.VisitDate,
                ],
                (_, result) => {
                  console.log(`Inserted storeId ${item.storeId}`);
                },
                (_, error) => {
                  console.log(`Failed to insert storeId ${item.storeId}: `, error);
                  return false; // continue transaction on error
                }
              );
            });
          },
          error => {
            console.log('Transaction error:', error);
            Alert.alert('Error', 'Failed to insert store data.');
            setProcessing(false)
          },
          () => {
            console.log('All stores inserted successfully!');
            Alert.alert('Success', 'Store data downloaded and saved.');
            setProcessing(false)
          }
        );
      } else {
        console.log('No store data found in response.');
        Alert.alert('Info', 'No store data available.');
        setProcessing(false)
      }

    } catch (error) {
      console.log('Fetch or DB error:', error);
      Alert.alert('Error', 'Failed to download store data.');
      setProcessing(false)
    }
  };


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


  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=selectedStore?.StoreId+'_'+moment().format('YYYYMMDDHHmmss');
    // setSystemPO(SPO);
    // 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;
    };
  }, []);


  useEffect(() => {
    if (selectedStore) {
      getData(selectedStore, currentMenu);
      let SPO = selectedStore?.StoreId + '_' + moment().format('YYYYMMDDHHmmss');
      BgSystemPO(SPO)

    }
  }, [selectedStore]);

  const _handleAppStateChange = async (nextAppState) => {
    // console.log('getDAta-----bg-unsaved1--paid')
    if (nextAppState == 'background' && hasUnsavedChangesRef.current == true) {
      // console.log('getDAta-----bg-unsaved1--paid',hasUnsavedChangesRef )
      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)
      console.log('getDAta-----bg-unsaved2', WindowsStr)
      //  await set_item('storeData',WindowsStr); 
    }
  }

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

  function onBeforeRemove(e) {
    if (hasUnsavedChanges == true) {
      e.preventDefault(); // Prevent default behavior of leaving the screen
      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 () => {
            // setHasUnsavedChanges(false);
            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) {
    //console.log("selectedStore",selectedStore,menu1)    
    try {
      let AllKPIFields = await getKPIFields(menu1, true);
      setKPIFields(AllKPIFields);
      console.log("menuuu", menu1)
      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", isShowMrpPtrKPIObj)
      db.transaction(tx => {
        tx.executeSql(
          ` SELECT 
                    COUNT(*) as count, 
                    (SELECT VisitDate FROM StoreList_OfflineOrder ORDER BY VisitDate DESC) as latestVisitDate 
                FROM StoreList_OfflineOrder
                `,
          [],
          (_, { rows }) => {
            const count = rows.item(0).count;
            const latestVisitDate = rows.item(0).latestVisitDate;

            console.log('Local store count:', count);
            console.log('Latest Visit Date:', latestVisitDate);
            //   console.log('Today Date:', todayDate);

            if (count === 0) {
              console.log('No local data found. Downloading...');
              fetchAndInsertData();
            } else if (latestVisitDate !== d2) {
              console.log('Visit date does not match today. Downloading new data...');
              fetchAndInsertData();
            } else {
              console.log('Local data is up to date.');
            }
          },
          (_, error) => {
            console.log('Error checking local store data:', error);
          }
        );
      });


      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 storeBGData1 = [], bgStoreJson = {}, IsOrdPresent = false, isBgDataExists = false;

      db.transaction(async function (txn) {
        let q3 = `Select OrderReasonId as ReasonId,OrderReason as Reason From Master_NonOrderReason`;
        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`;
        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 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 = ${selectedStore?.StoreId} and (IsCompetitor='0' or IsCompetitor=0)  order by p.CategorySequence`;

        console.log("checkqq-->", q);


        txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            console.log('inputs found');
            let arr = [], arr2 = [];
            console.log("hea=der_length", txnres.rows.length);
            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);
              arr2 = arr2.concat(skuData);
              if (i == txnres.rows.length - 1) {
                console.log('arr2:', arr2);
                setBrandData(arr);
                if (!isBgDataExists) {
                  BgWindowData(arr2);
                }

                // setSKUStockData(arr2);
                setProcessing(false);
              }
            }

          } else {
          }

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

  function onselectionChange3(option, keyLbl, keyVal, otherData) {
    setReason(option)
    console.log("option------", 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.ptr,0)as ptr,ifnull(p.Mrp,0)as Mrp`;
        let join = `inner join Mapping_ProductAssortmentStorewise m on p.ProductId=m.ProductId `;
        let q1 = `SELECT ${seletlist} from Product_Master p ${join} where m.StoreId= ${selectedStore.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('product in orders q:', q1);
        txn.executeSql(q1, [], async function (txn2, txnres) {
          console.log('product in orders len:', 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 } = data;
              inputRefs.current['input1_' + cat.CategoryId + '_' + data.ProductId] = '';
              data.ptr = showMrpPtrRef.current === 'PTR' ? data.ptr : data.Mrp
              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)
                let d1 = moment(PO_DATE).format('DD/MM/YYYY');
                let d2 = new Date(PO_DATE);
                BgPODate(d1)
                BgPODate2(d2)

                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];
      console.log("nextKey", nextKey, 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);
      }
    }
  }

  function generateUniqueId(storeId) {
    const now = new Date();
    const timestamp = moment(now).format('YYYYMMDD_HHmmss');
    return `${storeId}_${timestamp}`;
  }

  async function saveData() {
    const uniqueId = generateUniqueId(selectedStore?.StoreId); // Generate unique ID
    BgUnsavedChanges(false);
    setShowAlert(false);
    setLoaderTitle('Saving Data...');
    setProcessing(true);

    try {
      let ReasonId = reason?.value != null ? reason?.value : 0;
      let Reason = reason?.label != null ? reason?.label : '';
      let PO_date1_MDY = moment(PODate2).format('MM/DD/YYYY');
      let allChilds = [];
      let allData = {};
      if (IsOrderPresent == 1) {
        for (let 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] : {};
          let stockValue = Stock != null && Stock !== '' && Stock !== 'undefined' ? Stock : '0';

          let obj = {
            UserId: props.UserId,
            CategoryId: CategoryId,
            ProductId: ProductId,
            OrderQty: stockValue
          };

          allChilds.push(obj);

          if (i === 0) {
            allData = {
              Unique_id: uniqueId,
              UserId: props.UserId,
              Visit_Date: d2,
              StoreId: selectedStore?.StoreId,
              IsPresent: 1,
              Reason: '',
              ReasonId: 0,
              SystemPO: SystemPO,
              StorePO: StorePO || '',
              ContactName: ContactName || '',
              ContactNo: ContactNo || '',
              StockistId: StockistDis?.StockistId || '',
              StockistName: StockistDis?.StockistName || ''

            };
          }
        }
      } else {
        allData = {
          Unique_id: uniqueId,
          UserId: props.UserId,
          Visit_Date: d2,
          StoreId: selectedStore?.StoreId,
          IsPresent: 0,
          Reason: Reason,
          ReasonId: ReasonId,
          SystemPO: '',
          StorePO: '',
          ContactName: '',
          ContactNo: '',
          StockistId: StockistDis?.StockistId || '',
          StockistName: StockistDis?.StockistName || '',
          OrderSKUList: []
        };
      }

      allData.OrderSKUList = allChilds;

      let postData = {
        MID: 0,
        Keys: "OfflineOrder",
        JsonData: JSON.stringify(allData),
        UserId: props.UserId
      };

      //console.log("Uploading order postData:", postData);

      const res = await fetch('https://ap1.parinaam.in/Webservice/GenericService.svc/UploadJson', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(postData)
      });

      const text = await res.text();
      //console.log('Raw response:', text);

      let json;
      try {
        json = JSON.parse(text);
      } catch (err) {
        console.error('Could not parse JSON:', err);
        setProcessing(false);
        notify('Upload failed');
        return;
      }

      if (json?.UploadJsonResult === "Success") {
        console.log("Data Uploaded suceesfully")
        notify('Offline Order uploaded successfully');
        //  notify('Offline Order uploaded');
        // ✅ Now insert locally only if upload succeeded
        db.transaction(async function (txn) {
          const deleteQuery = `DELETE FROM ${AppTables.OFFLINE_ORDER} WHERE STORE_ID='${selectedStore?.StoreId}' and VISIT_DATE='${d2}'`;
          txn.executeSql(deleteQuery, [], () => {
            console.log("Old order data deleted");
          });

          let stock_values = '';
          if (IsOrderPresent == 1) {
            for (let 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 = skulist.find(b => b.ProductId == ProductId) || {};

              let stockValue = Stock != null && Stock !== '' && Stock !== 'undefined' ? Stock : '0';

              stock_values += stock_values ? ',' : '';
              stock_values += `('${selectedStore?.StoreId}','${d2}','${CategoryName}','${CategoryId}','${skuItem.ProductName}','${ProductId}','','1','${stockValue}','${SystemPO}','${StorePO}','${PO_date1_MDY}','${ContactName}','${ContactNo}','${d2}','','0','${StockistDis?.StockistId}','${StockistDis?.StockistName}')`;
            }
          } else {
            stock_values += `('${selectedStore?.StoreId}','${d2}','','','','','','0','','','','','','','${d2}','${ReasonId}','${Reason}','${StockistDis?.StockistId}','${StockistDis?.StockistName}')`;
          }

          let insertQuery = `INSERT INTO ${AppTables.OFFLINE_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}`;

          txn.executeSql(insertQuery, [], () => {
            console.log("Order saved locally after upload");
            clear_item('storeData');
            // notify('Offline Order uploaded and saved locally');
            setProcessing(false);
            props.navigation.goBack();
          }, (txnE, err) => {
            console.log('Insert error:', err);
            setProcessing(false);
            notify('Upload succeeded, but local save failed');
          });
        });
      } else {
        notify('Upload failed', json?.UploadJsonResult);
        setProcessing(false);
      }
    } catch (err) {
      console.log('Final catch error:', err);
      setProcessing(false);
      notify('An unexpected error occurred');
    }
  }

  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?.StockistId == '' || StockistDis?.StockistId == null)) {
        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;
    }
    console.log('isValid:', isValid);
    return isValid;
  }

  function onConfirmRemoveAll() {
    // Remove all data 
    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);
    // setHasUnsavedChanges(true);
    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);
    // setHasUnsavedChanges(true);
    BgUnsavedChanges(true)
    setrerenderdata(!rerenderdata);
  }

  function onSaveCancel() {
    setShowAlert(false);
  }

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

            setShowDatePicker(false);
            // setPODate2(selectedDate);
            // setPODate(d1);
            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;

    return (
      <View style={customStyle.Orders_PageWrap}>
        {
          selectedStore != null && (
            <View style={[customStyle.addvis_pCon, { marginTop: 3 }]}>
              <Text style={[customStyle.addvis_pText]}>{'Is Present'}</Text>
              <View style={customStyle.addvis_pChoiceBoxCon}>
                <View style={[customStyle.openStk_prd_choiceBox, customStyle.addvis_pChoiceBoxbg]}>
                  <Animated.View style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, (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>
            </View>
          )
        }

        {(IsOrderPresent != '1' && ShowReasonEnable == true && selectedStore != null) &&
          <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={{}}
            // ShowError={error} 
            />}
          </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) &&
          <KeyboardAvoidingView style={[customStyle.keyba_view, customStyle.keyba_viewContent]} behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 60 : 0}
            enabled >
            <ScrollView
              contentContainerStyle={[customStyle.opening_Stock_scroll, { paddingBottom: 100 }]}
              style={customStyle.opening_Stock_scrollOuter}
              keyboardShouldPersistTaps="handled"
            >
              {(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) => {
                        //setStorePO(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) => { //setContactName(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) => {
                        // setContactNo(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>
                    <SearchableSelector data={StockistList} placeholder="Select Distributor" customStyle={customStyle} selectedVal={StockistDis} setSelectedVal={BgStockist} />
                  </View>
                </View>
              }

              {console.log("checkbdata-->", brandData.length)}
              {rerenderdata == rerenderdata && brandData.length > 0 && (
                <KeyboardAwareFlatList
                  data={brandData} // Main data array for categories
                  keyExtractor={(item, index) => `category-${item.CategoryId || index}`} // Unique key for each category
                  renderItem={({ item: cat, index: catIndex }) => (
                    <View style={customStyle.opening_Stock_wrap}>
                      {/* Category Header */}
                      <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>

                      {/* Products List */}
                      <View style={customStyle.opening_Stock_prds}>
                        {(
                          <KeyboardAwareFlatList
                            data={cat?.skulist || []} // List of SKUs for this category
                            keyExtractor={(item, index) => `sku-${item.ProductId || index}`} // Unique key for each SKU
                            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.openStk_prd_flex_inputStyle,
                                          ]}
                                          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>
    );
  }


  function FilterStores(searchedQry) {
    const query = searchedQry.toLowerCase();
    console.log('searchedQry:', query);

    let sql = 'SELECT * FROM StoreList_OfflineOrder';
    let params = [];

    if (query && query.trim() !== '') {
      sql += ' WHERE LOWER(StoreName) LIKE ? OR StoreId LIKE ?';
      params = [`%${query}%`, `%${query}%`];
    }

    db.transaction(tx => {
      tx.executeSql(
        sql,
        params,
        (_, results) => {
          const rows = results.rows;
          let arr = [];
          for (let i = 0; i < rows.length; i++) {
            arr.push(rows.item(i));
          }
          setStoreList(arr);
          setSelectedStore(null);
          setrerenderdata(prev => !prev);
        },
        (_, error) => {
          console.log('Failed to filter stores:', error);
          return false;
        }
      );
    });
  }


  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}>
              {console.log("data_preview", item)}
              <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={item.MenuName} projectCode={`${''} ${''}`} />

      {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
      {ConfirmSaveAlert(props, showRAllC_M, () => {
        {/* setShowRAllC_M(false) */ }
        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]}>
          <View style={customStyle.storel_searchbar}>
            <TextInput
              style={[customStyle.storel_searchInput]}
              placeholder={ST.Searchby + ` ${ST.StoreName}, ${ST.StoreId}, ${ST.StoreCode}`}
              autoComplete='off'
              placeholderTextColor={PageTheme.$placeholder_color}
              value={searchedItem}
              onChangeText={(val) => { setSearchedItem(val); FilterStores(val) }}
            />
            <TouchableOpacity style={customStyle.storel_searchBtn} onPress={() => { FilterStores(searchedItem) }}>
              <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
            </TouchableOpacity>
          </View>

          <View style={{ backgroundColor: '#5f7ba3', margin: 10, borderRadius: 10 }}>
            <KeyboardAwareFlatList
              data={selectedStore ? [selectedStore] : storeList}
              keyExtractor={(item) => item.StoreId.toString()}
              renderItem={({ item }) => (
                <TouchableOpacity onPress={() => { setSelectedStore(item); }}>
                  <View style={styles.storeItemContainer}>
                    <Text style={styles.storeItemName}>
                      {item.StoreName} (ID: {item.StoreId})
                    </Text>
                    <Text style={styles.storeItemAddress}>
                      {item.Address}, {item.CityName}
                    </Text>
                  </View>
                </TouchableOpacity>
              )}
              ListEmptyComponent={() => null} // ✅ nothing is rendered if empty
            />
          </View>
          {_render_PresentQ()}

          {
            selectedStore != null && selectedStore != '' && (
              <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={() => { submitData() }} />
              </View>
            )
          }

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

        </View>
      </LinearGradient>
    </Container>
  );
}

const styles = StyleSheet.create({

  storeItemContainer: {
    padding: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  storeItemName: {
    color: '#fff',
    fontWeight: 'bold',
  },
  storeItemAddress: {
    color: '#eee',
    fontSize: 12,
  },
  modalBackground: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContainer: {
    paddingVertical: 16,
    paddingHorizontal: 4, // ✅ 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);



