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, StyleSheet, Modal,
    FlatList, Animated, Alert, KeyboardAvoidingView, AppState, Keyboard, ActionSheetIOS
} 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, getServerDT, marktext1, marktext2,
    restore_ImageWithMetaData, validateNumber
} from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr, ImageFolderPath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, Fontisto, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import CustomModal from '../components/CustomModal';
import { ConfirmSaveAlert } from '../components/alert';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';
import CustomCamera from '../components/Camera';
import CustomImagePickerModal from '../components/CustomImagePickerModal';

function OrderDetail(props) {
    const route = useRoute();
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);
    const animatedChoice = useRef(new Animated.Value(0)).current;
    const ST = props.StaticText || {};
    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 [Orderlist, setOrderList] = useState([]);
    const [SKUStockData, setSKUStockData] = useState([]);
    const [SystemPO, setSystemPO] = useState('');
    const [StorePO, setStorePO] = useState('');
    const [ContactName, setContactName] = useState('');
    const [ContactNo, setContactNo] = useState('');
    const [PODate, setPODate] = useState('');
    const [PODate2, setPODate2] = useState(new Date());
    const [ShowDatePicker, setShowDatePicker] = useState(false);
    const [KPIFields, setKPIFields] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [IsOrderPresent, setIsOrderPresent] = useState(false);
    const [showRAllC_M, setShowRAllC_M] = useState(false);
    const [orderData, setOrderData] = useState({});
    const [SelectedOrder, setSelectedOrder] = useState([]);
    const [WindowData, setWindowData] = useState([]);
    const [DataCleanModal, setDataCleanModal] = useState(false);
    const [DataCleanAnim, setDataCleanAnim] = useState("");
    const [DataCleanItem, setDataCleanItem] = useState({});
    const [isPresentClean, setIsPresentClean] = useState(0);
    const [InputChange, setInputChange] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [showCamera, setShowCamera] = useState(false);
    const [showSwitchCamera, setShowSwitchCamera] = useState(false);
    const [getImageProps, setGetImageProps] = useState({});
    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [rerenderdata2, setrerenderdata2] = useState(0);
    const [showImagePickerModal, setShowImagePickerModal] = useState(false);

    const [showPickerModal, setShowPickerModal] = useState(false);
    const [pickerType, setPickerType] = useState(null);

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(SelectedOrder);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');
    const NavigationRef = React.useRef({});
    const VisFormDataRef = React.useRef(AddVisFormData);
    const inputRefs = useRef({});

    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 orderDetail = params.orderDetail || {};
        let menu1 = params.menu || {};
        let isAdhoc = params.isAdhoc || false;
        setOrderData(orderDetail);
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
        let SPO = storeData1.StoreId + '_' + moment().format('YYYYMMDD');
        setSystemPO(SPO);
        StoreIdRef.current = storeData1.StoreId;
        ScreenNameRef.current = menu1.ScreenName;
        let navData = {
            'storeData': storeData1,
            'orderDetail': orderDetail
        };
        NavigationRef.current = navData;
        getData(storeData1, orderDetail, 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,
                NavData: NavigationRef.current,
                visiteDate: d2,
                VisFormData: VisFormDataRef.current
            };
            let WindowsStr = JSON.stringify(newData);
            await set_item('storeData', WindowsStr);
        }
    };

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

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

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

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

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

    async function getData(storeData1, orderData, menu1) {
        try {
            console.log("checkdataas:", orderData);
            let { OrderId, MID } = orderData;
            let { StoreId } = storeData1;
            let q = ` SELECT * from PriviousVisit_Orders p Where p.OrderId ='${OrderId}' AND p.MID='${MID}'`;
            let q2 = ` SELECT STORE_ID as StoreId,INVOICE_TYPE as InvoiceType,MID as MID, ORDER_ID as OrderId ,ORDER_QTY as OrderQty,PRODUCT_ID as ProductId, PRODUCTNAME as ProductName, ISPRESENT as isPresent,p.IMAGES as imgObj  FROM ${AppTables.ORDERSTATUS} p WHERE p.ORDER_ID ='${OrderId}' and STORE_ID='${StoreId}' and MID='${MID}' and VISIT_DATE='${d2}'`;

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

            let storeBGData1 = [], bgStoreJson = {}, isBgDataExists = false;
            let windData = await get_item('storeData');
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData);
                console.log("storeDataJson", StoreJson)
                let { storeBGData, menuName, StoreId1, visiteDate, VisFormData } = StoreJson;
                if (storeBGData.length > 0 && menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                    isBgDataExists = true;
                    storeBGData1 = storeBGData;
                    bgStoreJson = StoreJson;
                    BgUnsavedChanges(true);
                    BgWindowData(storeBGData);
                    BgAddVisFormData(VisFormData);
                }
            }
            await db.transaction(async function (txn) {
                await txn.executeSql(q2, [], async function (txn2, txnres) {
                    console.log('added order found:', txnres.rows.length);
                    if (txnres.rows.length > 0) {
                        console.log('inputs found', txnres.rows.length);
                        let arr = [], arr2 = [], inputChangeFlag = [];
                        for (let i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            let isPresent = (data.isPresent == '1' || data.isPresent == 1 ? 1 : 0);
                            if (isBgDataExists) {
                                let storeBgIndex = storeBGData1.findIndex(i => i.OrderId == data.OrderId && i.ProductId == data.ProductId);
                                let storeBgObj = storeBgIndex >= 0 ? storeBGData1[storeBgIndex] : {};
                                isPresent = Number(storeBgObj.isPresent);
                            }
                            let animatedChoice = new Animated.Value(isPresent);
                            data.animatedChoice = animatedChoice;
                            data['isPresent'] = isPresent;
                            let defData = { 'OrderId': data.OrderId, 'ProductId': data.ProductId, 'StoreId': StoreId, 'OrderQty': data.OrderQty, 'ProductName': data.ProductName, 'isPresent': isPresent, 'InvoiceType': data.InvoiceType, 'MID': data.MID };
                            let changesFlag = { OrderId: data.OrderId, ProductId: data.ProductId, Flag: false };
                            inputChangeFlag.push(changesFlag);
                            arr.push(data);
                            arr2.push(defData);
                            if (i == txnres.rows.length - 1) {
                                setInputChange(inputChangeFlag);
                                setOrderList(arr);
                                let ImgObjct = data?.imgObj && JSON.parse(data.imgObj);
                                console.log("ImgObjct----", ImgObjct);
                                if (!isBgDataExists) {
                                    BgWindowData(arr);
                                    BgAddVisFormData(ImgObjct || {});
                                }
                                
                                setProcessing(false);
                            }
                        }
                    } else {
                        await txn.executeSql(q, [], async function (txn2, txnres) {
                            console.log('inputs found', txnres.rows.length);
                            if (txnres.rows.length > 0) {
                                let arr = [], arr2 = [], inputChangeFlag = [];
                                for (var i = 0; i < txnres.rows.length; i++) {
                                    let data = txnres.rows.item(i);
                                    let isPresent = 0;
                                    if (data != null && data != "") {
                                        isPresent = 1;
                                    }
                                    if (isBgDataExists) {
                                        let storeBgIndex = storeBGData1.findIndex(i => i.OrderId == data.OrderId && i.ProductId == data.ProductId);
                                        let storeBgObj = storeBgIndex >= 0 ? storeBGData1[storeBgIndex] : {};
                                        console.log("storeBgObj-------", storeBgObj);
                                        isPresent = Number(storeBgObj.isPresent);
                                    }
                                    let animatedChoice = new Animated.Value(isPresent);
                                    data.animatedChoice = animatedChoice;
                                    data['isPresent'] = isPresent;
                                    let defData = { 'OrderId': data.OrderId, 'ProductId': data.ProductId, 'StoreId': StoreId, 'OrderQty': data.OrderQty, 'ProductName': data.ProductName, 'isPresent': isPresent, 'InvoiceType': data.InvoiceType, 'MID': data.MID };
                                    let changesFlag = { OrderId: data.OrderId, ProductId: data.ProductId, Flag: false };
                                    inputChangeFlag.push(changesFlag);
                                    arr.push(data);
                                    arr2.push(defData);
                                    if (i == txnres.rows.length - 1) {
                                        let { menuName, StoreId1, visiteDate } = bgStoreJson;
                                        setInputChange(inputChangeFlag);
                                        setOrderList(arr);
                                        if (!isBgDataExists) {
                                            BgWindowData(arr);
                                        }
                                        setProcessing(false);
                                    }
                                }
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); });
                    }
                }, function (txnE, txnerr) { console.log(txnerr); });
            });
        } catch (err) {
            console.log(err);
        }
    }

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

    function _OpenCaptureImage_Modal() {
        const isImageCap = (SelectedImg !== '' && SelectedImg !== null);
        let { window, splitItem, splitItemIndex, cameraType } = reCapImgModalObj;
        let camera2Label = (window && window.PromoImage2Lable) || '';
        return (
            <CustomModal
                style={customStyle.PromoImgModal}
                title={currentMenu.MenuName + " Image"}
                message={camera2Label}
                titleStyle={customStyle.PromoImgModal_title}
                messageStyle={customStyle.PromoImgModal_subtitle}
                showModal={showModal}
            >
                {isImageCap &&
                    <View style={customStyle.PromoImgModalCon}>
                        <View style={customStyle.PromoImgModal_ImgWrap}>
                            <Image
                                style={[customStyle.PromoImgModal_Img, (Platform.OS === 'ios' ? customStyle.android_flipIMageView : {})]}
                                source={{ uri: SelectedImg }}
                            />
                        </View>
                        <TouchableOpacity
                            style={customStyle.PromoImgModal_CameraSmall}
                            onPress={() => {
                                console.log('Retake pressed with cameraType:', cameraType); // Debugging
                                // cancelImage(); // Reset image states before retake
                                setShowModal(false);
                                showImagePicker(cameraType);
                            }}
                        >
                            <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
                        </TouchableOpacity>
                        {!showImageSaveOp &&
                            <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelImage(); }}>
                                <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                            </TouchableOpacity>
                        }
                    </View>
                }
            </CustomModal>
        );
    }


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

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

    async function saveData() {
        BgUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        try {
            let { StoreId } = storeData;
            await db.transaction(async function (txn) {
                let q = `DELETE FROM ${AppTables.ORDERSTATUS} WHERE STORE_ID='${StoreId}' and ORDER_ID='${orderData.OrderId}' and VISIT_DATE='${d2}' `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('Order data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); });

                var stock_values = '';
                let imageObj = JSON.stringify(AddVisFormData);
                for (var i = 0; i < SelectedOrder.length; i++) {
                    let { OrderId, OrderQty, StoreId, ProductId, ProductName, isPresent, InvoiceType, MID } = SelectedOrder[i];
                    stock_values += stock_values != '' ? ' , ' : '';
                    stock_values += ` ('${StoreId}','${d2}','${OrderId}','${(OrderQty || 0)}','${ProductId}','${ProductName}','${isPresent}','${d2}','${imageObj}','${InvoiceType}','${MID}') `;
                }

                console.log("stock_values-----", stock_values);
                let add_Stock = `INSERT INTO ${AppTables.ORDERSTATUS} (STORE_ID ,VISIT_DATE ,ORDER_ID ,ORDER_QTY ,PRODUCT_ID, PRODUCTNAME, ISPRESENT, ADDED_DATE,IMAGES,INVOICE_TYPE,MID) VALUES ${stock_values} `;
                console.log('add_Stock:', add_Stock);
                await txn.executeSql(add_Stock, [], async function (txn2, txnres) {
                    // clear store data in local storage to avoiding re-set data for the store  
                    clear_item('storeData')
                    console.log('ORDERSTATUS added');
                    notify('Order Status updated successfully');
                    setProcessing(false);
                    props.navigation.goBack();
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot update Order Status') });
            });
        } catch (err) {
            console.log(err);
        }
    }

    async function validate() {
        let ActualQty_Index = KPIFields.findIndex(i => i.KPIFieldName == 'ActualQty');
        let ActualQty_Obj = ActualQty_Index >= 0 ? KPIFields[ActualQty_Index] : {};
        let ActualQtyAllow = ActualQty_Index >= 0 ? ActualQty_Obj['KPIFieldEnable'] : true;
        let ActualQtyDisName = ActualQty_Index >= 0 ? ActualQty_Obj['KPIFieldDisplayName'] : 'Actual Qty';

        let CompPromoShowImage1I = KPIFields.findIndex(i => i.KPIFieldName == 'Image1');
        let CompPromoShowImage1Obj = CompPromoShowImage1I >= 0 ? KPIFields[CompPromoShowImage1I] : {};
        let CompPromoShowImage1 = CompPromoShowImage1I >= 0 ? CompPromoShowImage1Obj['KPIFieldEnable'] : true;
        let KPIMandatoryImage1 = CompPromoShowImage1I >= 0 ? CompPromoShowImage1Obj['KPIMandatory'] : true;
        let CompPromoShowImage1Label = CompPromoShowImage1I >= 0 ? CompPromoShowImage1Obj['KPIFieldDisplayName'] : "Image";

        let CompPromoShowImage2I = KPIFields.findIndex(i => i.KPIFieldName == 'Image2');
        let CompPromoShowImage2Obj = CompPromoShowImage2I >= 0 ? KPIFields[CompPromoShowImage2I] : {};
        let CompPromoShowImage2 = CompPromoShowImage2I >= 0 ? CompPromoShowImage2Obj['KPIFieldEnable'] : false;
        let KPIMandatoryImage2 = CompPromoShowImage2I >= 0 ? CompPromoShowImage2Obj['KPIMandatory'] : false;
        let CompPromoShowImage2Label = CompPromoShowImage2I >= 0 ? CompPromoShowImage2Obj['KPIFieldDisplayName'] : "Image";

        let isPresentFlag = false;
        SelectedOrder?.map((itemD) => {
            let isPresent = itemD.isPresent != null && itemD.isPresent != '' ? itemD.isPresent : '0';
            if (isPresent == '1') {
                isPresentFlag = true;
            }
        });

        let isValid = true;
        console.log('validate', AddVisFormData);
        return new Promise((resolve, reject) => {
            if (isPresentFlag && CompPromoShowImage1 && KPIMandatoryImage1 && (AddVisFormData.Image1Path == "" || AddVisFormData.Image1Path == null)) {
                notify(`Please Capture ${CompPromoShowImage1Label} `, 'LONG');
                resolve(false); return;
            } else if (isPresentFlag && CompPromoShowImage2 && KPIMandatoryImage2 && (AddVisFormData.Image2Path == "" || AddVisFormData.Image2Path == null)) {
                notify(`Please Capture ${CompPromoShowImage2Label} `, 'LONG');
                resolve(false); return;
            } else if (ActualQtyAllow == true && SelectedOrder.length > 0) {
                for (let wi in SelectedOrder) {
                    console.log('wi:', wi);
                    const wind = SelectedOrder[wi];
                    let isPresent = wind.isPresent != null && wind.isPresent != '' ? wind.isPresent : '0';
                    let OrderQty = wind.OrderQty != null && wind.OrderQty != '' ? wind.OrderQty : '';
                    if (isPresent == '1') {
                        if (OrderQty == "") {
                            notify(`Please Fill ${ActualQtyDisName} for ${wind.ProductName} `, 'LONG');
                            resolve(false); return;
                        }
                    }
                    if (wi == (SelectedOrder.length - 1)) {
                        console.log('last index return true');
                        resolve(true); return;
                    }
                }
            } else {
                resolve(true); return;
            }
        }).then((val) => { return val })
            .catch((err) => { console.log(err); return false });
    }

    function onConfirmRemoveAll() {
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: 0,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        setIsOrderPresent(0);
        BgUnsavedChanges(true);
        setStorePO('');
        setContactName('');
        setContactNo('');
        setSKUStockData([]);
        setShowRAllC_M(false);
    }

    async function OpenImgModal(imgPath, window, splitItem, splitItemIndex, cameraType) {
        console.log("cameratype:", cameraType)
        setSelectedImg(imgPath);
        setShowModal(true);
        if ((imgPath != '' && imgPath != null)) {
            setShowImageSaveOp(false);
        } else {
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({ window, splitItem, splitItemIndex, cameraType });
    }

    function onChoiceSelect(item, val, key, animatedChoice) {
        let win_index = InputChange.find(i => i.OrderId == item.OrderId && i.ProductId == item.ProductId);
        let changeValue = win_index.Flag;
        if (changeValue) {
            setIsPresentClean(val);
            setDataCleanAnim(animatedChoice);
            setDataCleanItem(item);
            setDataCleanModal(true);
            return;
        }
        var val1 = val == 1 ? 1 : 0;
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        onWindowDataChange(item, val, key);
        setIsOrderPresent(val);
        BgUnsavedChanges(true);
    }

    function onWindowDataChange(item, val, key, type = "") {
        if (val != '') {
            let isValid = validateNumber(val, type);
            if (!isValid) {
                return;
            }
        }
        let allData = SelectedOrder;
        let defData = { 'OrderId': item.OrderId, 'ProductId': item.ProductId, 'StoreId': item.StoreId, 'OrderQty': item.OrderQty, 'ProductName': item.ProductName, 'InvoiceType': item.InvoiceType, 'MID': item.MID };
        const win_index = allData.findIndex(i => i.OrderId == item.OrderId && i.ProductId == item.ProductId);
        let wind = win_index >= 0 ? (allData[win_index] || defData) : defData;
        wind[key] = val;
        win_index >= 0 ? allData[win_index] = wind : allData.push(wind);
        if (key != "isPresent") {
            let objIndex = InputChange.findIndex((obj => obj.OrderId == item.OrderId && obj.ProductId == item.ProductId));
            let winArr = [...InputChange];
            winArr[objIndex].Flag = true;
            setInputChange(winArr);
        }
        BgWindowData(allData);
        setrerenderdata(!rerenderdata);
    }

    function onSaveCancel() {
        setShowAlert(false);
    }

    function onWindowDataClean() {
        console.log("datacleann:", DataCleanItem);
        if (DataCleanAnim != null) {
            let anim = isPresentClean == 1 ? 1 : '';
            Animated.timing(DataCleanAnim, {
                toValue: anim,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        let allData = SelectedOrder;
        let defData = { 'OrderId': DataCleanItem.OrderId, 'ProductId': DataCleanItem.ProductId, 'StoreId': storeData.StoreId, 'OrderQty': 0, 'ProductName': DataCleanItem.ProductName, 'isPresent': 0 };
        const win_index = allData.findIndex(i => i.OrderId == DataCleanItem.OrderId && i.ProductId == DataCleanItem.ProductId);
        allData[win_index] = defData;
        let objIndex = InputChange.findIndex((obj => obj.OrderId == DataCleanItem.OrderId && obj.ProductId == DataCleanItem.ProductId));
        let winArr = [...InputChange];
        winArr[objIndex].Flag = false;
        setInputChange(winArr);
        setDataCleanModal(false);
        BgWindowData(allData);
        BgUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    const onCancelClean = () => {
        setDataCleanModal(false);
    };

    const onclear = () => {
        onWindowDataClean(DataCleanItem);
    };

    function _render_PresentQ(item, index) {
        console.log("checkitem", item);
        const wind = SelectedOrder.findIndex(i => i.OrderId == item.OrderId && i.ProductId == item.ProductId);
        let selectedData = SelectedOrder[wind];
        let isPresent = selectedData && selectedData.isPresent != null && selectedData.isPresent != '' ? selectedData.isPresent : '0';
        let OrderQty = selectedData && selectedData.OrderQty != null && selectedData.OrderQty != '' ? selectedData.OrderQty : '';
        let ActualQty_Index = KPIFields.findIndex(i => i.KPIFieldName == 'ActualQty');
        let ActualQty_Obj = ActualQty_Index >= 0 ? KPIFields[ActualQty_Index] : {};
        let ActualQtyAllow = ActualQty_Index >= 0 ? ActualQty_Obj['KPIFieldEnable'] : true;
        let ActualQtyDisName = ActualQty_Index >= 0 ? ActualQty_Obj['KPIFieldDisplayName'] : 'Actual Qty';
        var xpos = isPresent == '1' ? -75 : 0;
        if (item.animatedChoice != null) {
            xpos = item.animatedChoice.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -75],
            });
        }
        console.log("isPresent---------1", isPresent);
        return (
            <View style={customStyle.WItem_wrap} key={index}>
                <View style={customStyle.WItem_Hdr}>
                    <View style={customStyle.WItem_Hdrbg}>
                        <Text style={customStyle.WItem_HdrText}>{item.ProductName}</Text>
                        <Text style={customStyle.WItem_HdrSubTitleText}>{"Order Qty:" + item.OrderQty}</Text>
                    </View>
                </View>
                <View style={customStyle.WForm}>
                    <View style={[customStyle.openStk_prd_cols, customStyle.mt10]}>
                        <View style={[customStyle.openStk_prd_colflex, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ST.IsPresent}</Text>
                            <View style={customStyle.openStk_prd_choiceBoxCon}>
                                <View style={customStyle.openStk_prd_choiceBox}>
                                    <Animated.View style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, (isPresent == '1' || isPresent == 1 ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red),
                                    { transform: [{ translateX: xpos }], }]}></Animated.View>
                                    <TouchableOpacity style={customStyle.openStkCh_con1} onPress={() => { onChoiceSelect(item, "1", 'isPresent', item.animatedChoice) }}>
                                        <Text style={[customStyle.openStkCh_text, (isPresent == '1' || isPresent == 1 ? customStyle.openStkCh_textactive : {})]}>{ST.Yes}</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(item, "0", 'isPresent', item.animatedChoice) }}>
                                        <Text style={[customStyle.openStkCh_text, (isPresent == '0' || isPresent == 0 ? customStyle.openStkCh_textactive : {})]}>{ST.No}</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                        {(ActualQtyAllow == true && isPresent == 1) &&
                            <View style={[customStyle.openStk_prd_colflex, customStyle.mb10]}>
                                <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ActualQtyDisName}</Text>
                                <View style={customStyle.openStk_prd_choiceBoxCon}>
                                    <TextInput
                                        style={[customStyle.WQ_InputStyle]}
                                        defaultValue={String(item.OrderQty || "")}
                                        value={OrderQty}
                                        autoComplete='off'
                                        keyboardType={'number-pad'}
                                        onChangeText={(val) => { onWindowDataChange(item, val, 'OrderQty', 'numeric') }}
                                    />
                                </View>
                            </View>
                        }
                    </View>
                </View>
            </View>
        );
    }

    let CompPromoShowImage1I = KPIFields.findIndex(i => i.KPIFieldName == 'Image1');
    let CompPromoShowImage1Obj = CompPromoShowImage1I >= 0 ? KPIFields[CompPromoShowImage1I] : {};
    let CompPromoShowImage1 = CompPromoShowImage1I >= 0 ? CompPromoShowImage1Obj['KPIFieldEnable'] : true;
    let KPIMandatoryImage1 = CompPromoShowImage1I >= 0 ? CompPromoShowImage1Obj['KPIMandatory'] : false;
    let CompPromoShowImage1Label = CompPromoShowImage1I >= 0 ? CompPromoShowImage1Obj['KPIFieldDisplayName'] : "Image";

    let CompPromoShowImage2I = KPIFields.findIndex(i => i.KPIFieldName == 'Image2');
    let CompPromoShowImage2Obj = CompPromoShowImage2I >= 0 ? KPIFields[CompPromoShowImage2I] : {};
    let CompPromoShowImage2 = CompPromoShowImage2I >= 0 ? CompPromoShowImage2Obj['KPIFieldEnable'] : false;
    let KPIMandatoryImage2 = CompPromoShowImage2I >= 0 ? CompPromoShowImage2Obj['KPIMandatory'] : false;
    let CompPromoShowImage2Label = CompPromoShowImage2I >= 0 ? CompPromoShowImage2Obj['KPIFieldDisplayName'] : "Image";


    //for new

    async function showImagePicker(type) {
        setGetImageProps({ type });
        setShowModal(false);
        setShowCamera(false);

        console.log('[Image Picker] User initiated image selection for type:', type);

        if (Platform.OS === 'ios') {
            ActionSheetIOS.showActionSheetWithOptions(
                {
                    options: ['Cancel', '📷 Take Photo', '🖼️ Choose from Gallery'],
                    cancelButtonIndex: 0,
                    title: 'Select Image Source',
                },
                (buttonIndex) => {
                    if (buttonIndex === 1) openCamera(type);
                    else if (buttonIndex === 2) openGallery(type);
                }
            );
        } else {
            setPickerType(type);
            setShowPickerModal(true); // ✅ Show custom modal
        }
    }


    async function openCamera(type = '1') {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.CAMERA,
                {
                    title: 'Camera Permission',
                    message: 'App needs access to your camera to take photos.',
                    buttonNeutral: 'Ask Me Later',
                    buttonNegative: 'Cancel',
                    buttonPositive: 'OK',
                }
            );
            if (granted === PermissionsAndroid.RESULTS.GRANTED || Platform.OS === 'ios') {
                setShowCamera(true);
                setGetImageProps({ type }); // Ensure type is set
                console.log('Camera opened with type:', type); // Debugging
            } else {
                notify('Camera permission denied', 'LONG');
            }
        } catch (err) {
            console.warn('Camera permission error:', err);
        }
    }

    async function openGallery(type = '1') {
        try {
            let permissionsToRequest = [];

            if (Platform.OS === 'android') {
                if (Platform.Version >= 33) {
                    permissionsToRequest = [
                        PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES,
                    ];
                } else {
                    permissionsToRequest = [
                        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                    ];
                }

                const granted = await PermissionsAndroid.requestMultiple(permissionsToRequest);

                const hasGalleryPermission = Object.values(granted).every(
                    status => status === PermissionsAndroid.RESULTS.GRANTED
                );

                if (!hasGalleryPermission) {
                    notify('Gallery permission denied', 'LONG');
                    return;
                }
            }

            const options = {
                mediaType: 'photo',
                includeBase64: false,
                quality: 1,
            };

            launchImageLibrary(options, (response) => {
                if (response.didCancel) {
                    console.log('User cancelled image picker');
                } else if (response.errorCode) {
                    notify(`Error: ${response.errorMessage}`, 'LONG');
                } else if (response.assets && response.assets.length > 0) {
                    const imgdata = {
                        uri: response.assets[0].uri,
                        width: response.assets[0].width,
                        height: response.assets[0].height,
                        fromGallery: true,
                        datetime: new Date(),
                        type, // Include type
                    };
                    console.log('Gallery image selected:', imgdata);
                    getImage(imgdata);
                }
            });

        } catch (err) {
            console.warn('Gallery permission error:', err);
            notify('Failed to access gallery', 'LONG');
        }
    }



    async function getImage(imgdata) {
        console.log('getImage called with data:', imgdata); // Debugging
        // let type = getImageProps.type || '';
        let type = imgdata.type || getImageProps.type || '1';
        if (!type) {
            console.warn('Image type not set in getImageProps');
            return;
        }
        if (typeof imgdata === 'object' && imgdata.errorCode === 'camera_unavailable') {
            notify('Camera unavailable', 'LONG');
            return;
        } else if (typeof imgdata === 'object' && imgdata.uri != null) {
            const img = imgdata;
            const imgurl = img.uri, imgWidth = img.width, imgHeight = img.height;
            let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
            let picture_clickedd = isImgFromGallery ? img.datetime : new Date();

            let picture_clicked_time = moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name = moment(picture_clickedd).format('MMDDYYYY_HHmmss')

            console.log("time", picture_clicked_time);
            console.log("time1", picture_clicked_time_for_pic_name);
            let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
            let calculate_tym_date_over_img = picture_clicked_time;

            let filename = storeData.StoreId + '_' + (props.UserId || '') + '_orderImg-' + calculate_tym_date_for_filename + '.jpg';
            const mark_text1 = calculate_tym_date_over_img;
            const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: OrderDetails' + ' | Date:' + calculate_tym_date_over_img;
            let addvisdata = { ...AddVisFormData };
            let image_key = `Image${type}`;
            let image_path_key = `Image${type}Path`;
            addvisdata[image_key] = filename;
            let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;

            try {
                // Ensure the directory exists
                await RNFS.mkdir(`${ImageFolderPath + currentMenu.ScreenName}`);
                await RNFS.copyFile(imgurl, imagePath);
                let uri = 'file://' + imagePath;
                addvisdata[image_path_key] = uri;
                console.log('Image saved, updating AddVisFormData:', addvisdata); // Debugging
                BgAddVisFormData(addvisdata);
                BgUnsavedChanges(true);
                setrerenderdata2(prev => prev + 1);
                setShowCamera(false);
                setShowModal(false);
                setSelectedImg(uri);
                setReCapImgModalObj({ cameraType: type });
                setShowImageSaveOp(false);
                //setShowModal(true); // Re-open modal to show new image
                let restore_data = { "destFilePath": imagePath, "imgurl": imgurl, imgWidth, imgHeight, mark_text1, mark_text2 };
                let is_restored = await restore_ImageWithMetaData(restore_data, imgdata);
                console.log('Image restored:', is_restored);
            } catch (err) {
                console.error('Image file write failed:', err.message, err.code);
                notify('Failed to save image', 'LONG');
            }
        }
    }

    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName || "Order Detail"} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            <CustomCamera cameraType={'back'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: ' + currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData) => { setShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { setShowCamera(false); }} />

            {_OpenCaptureImage_Modal()}
            {ConfirmSaveAlert(props, DataCleanModal, onCancelClean, onclear, 'Your data will be clean')}
            {ConfirmSaveAlert(props, showRAllC_M, () => { setShowRAllC_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, { marginHorizontal: 10 }]}>
                        <View style={customStyle.storel_card_outer}>
                            <View style={customStyle.storel_details}>
                                <View style={customStyle.storel_code}>
                                    <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                                        <Text style={customStyle.storel_codeLbl}>{'Order Id:'}</Text>
                                        <Text style={customStyle.storel_codeText}>{orderData.OrderId}</Text>
                                    </View>
                                </View>
                            </View>
                            <View style={{ flexDirection: "row", justifyContent: "center" }}>
                                {CompPromoShowImage1 && (
  <View style={customStyle.openStkCameraCon2}>
    {!AddVisFormData.Image1Path ? (
      KPIMandatoryImage1 ? (
        <TouchableOpacity onPress={() => showImagePicker('1')}>
          <CameraImg5 width={50} height={50}  />
        </TouchableOpacity>
      ) : (
        <TouchableOpacity onPress={() => showImagePicker('1')}>
          <CameraImg2 width={50} height={50} />
        </TouchableOpacity>
      )
    ) : (
      <TouchableOpacity
        onPress={() =>
          OpenImgModal(AddVisFormData.Image1Path, '1', '', '', '1')
        }>
        <CameraImg3 width={50} height={50} />
      </TouchableOpacity>
    )}
    <Text style={customStyle.WSCameraLabel}>{CompPromoShowImage1Label}</Text>
  </View>
)}


                                {CompPromoShowImage2 && (
                                    <View style={customStyle.openStkCameraCon2}>
                                        {!AddVisFormData.Image2Path ? (
                                            KPIMandatoryImage2 ? (
                                                <TouchableOpacity onPress={() => showImagePicker('2')}>
                                                    <CameraImg5 width={50} height={50}  />
                                                </TouchableOpacity>
                                            ) : (
                                                <TouchableOpacity onPress={() => showImagePicker('2')}>
                                                    <CameraImg2 width={50} height={50} />
                                                </TouchableOpacity>
                                            )
                                        ) : (
                                            <TouchableOpacity
                                                onPress={() =>
                                                    OpenImgModal(AddVisFormData.Image2Path, '2', '', '', '2')
                                                }>
                                                <CameraImg3 width={50} height={50} />
                                            </TouchableOpacity>
                                        )}
                                        <Text style={customStyle.WSCameraLabel}>{CompPromoShowImage2Label}</Text>
                                    </View>
                                )}

                            </View>
                        </View>
                    </View>
                    {Object.keys(storeData).length > 0 &&
                        <ScrollView contentContainerStyle={[customStyle.orderDetails_scroll]} style={{}}>
                            {rerenderdata == rerenderdata &&
                                Orderlist.map((item, index) => {
                                    return _render_PresentQ(item, index);
                                })}
                        </ScrollView>
                    }
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                        <GradientButton {...props} title={'Save'} onPress={() => { submitData() }} />
                    </View>
                </View>
            </LinearGradient>

            <CustomImagePickerModal
                visible={showPickerModal}
                onClose={() => setShowPickerModal(false)}
                onCamera={() => openCamera(pickerType)}
                onGallery={() => openGallery(pickerType)}
            />

        </Container>
    );
}

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