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 { Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, Alert, Animated, AppState, Keyboard } from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from "dayjs";
import { getKPIFields, restore_ImageWithMetaData, validateNumber } from '../controller/functions';
import { CustomPicker2 } from '../components/CustomPicker';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { db, ImageFolderPath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { FontAwesome, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import CustomModal from '../components/CustomModal';
import { ConfirmSaveAlert } from '../components/alert';
import { CustomPicker } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';

function OrderSimplify(props) {
    const route = useRoute();
    const ST = props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);
    const animatedChoice = useRef(new Animated.Value(0)).current;

    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    const [currentMenu, setCurrentMenu] = useState({});
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);
    const [AddVisibility, setAddVisibility] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [isAddVisPresent, setIsAddVisPresent] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [Categories, setCategories] = useState([]);
    const [SubCategories, setSubCategories] = useState([]);
    const [Brands, setBrands] = useState([]);
    const [ProductsList, setProductsList] = useState([]);
    const [PackTypeList, setPackTypeList] = useState([]);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [clickImageType, setClickImageType] = useState('1');
    const [toRemoveId, setToRemoveId] = useState('');
    const [toRemoveItem, setToRemoveItem] = useState({});
    const [showRemoveConfirm_M, setshowRemoveConfirm_M] = useState(false);
    const [showRAllC_M, setShowRAllC_M] = useState(false);
    const [KPIFields, setKPIFields] = useState([]);
    const [reason, setReason] = useState({});
    const [reasons_list, setReasons_list] = useState([]);
    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(AddVisibility);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');
    const [showSwitchCamera, setShowSwitchCamera] = useState(false);
    const VisFormDataRef = React.useRef(AddVisFormData);
    const isAddVisPresentRef = React.useRef(isAddVisPresent);
    const d2 = moment().format('MM/DD/YYYY');

    useEffect(() => {
        setLoaderTitle(ST.Loading + '...')
        let params = props.route.params ? props.route.params : {};
        let storeData1 = params.storeData || {};
        let menu1 = params.menu || {};
        let cameraAllow = storeData1.CameraAllow == 'true' || storeData1.CameraAllow == 1 ? true : false;
        setStoreCameraAllow(cameraAllow);
        let isAdhoc = params.isAdhoc || false;
        StoreIdRef.current = storeData1.StoreId
        ScreenNameRef.current = menu1.ScreenName
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
        getData(storeData1, menu1);

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

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



    const _handleAppStateChange = async (nextAppState) => {
        if (nextAppState == 'background' && hasUnsavedChangesRef.current == true) {
            let newData = {
                storeBGData: WindowDataRef.current,
                menuName: ScreenNameRef.current,
                StoreId1: StoreIdRef.current,
                AddFormData: VisFormDataRef.current,
                isVisPresent: isAddVisPresentRef.current,
                visiteDate: d2
            }

            let WindowsStr = JSON.stringify(newData)
            await set_item('storeData', WindowsStr);
        }
    }

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

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

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

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

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

    function BgIsAddVisPresent(val) {
        isAddVisPresentRef.current = val
        setIsAddVisPresent(val);
    }


    function onBeforeRemove(e) {
        if (showCamera == true) {
            e.preventDefault();
            setShowCamera(false);
        }
        else {
            if (hasUnsavedChanges == true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else {
                return;
            }
        }
    }
    function onRemoveScreen(e) {
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
                {
                    text: ST.Cancel,
                    onPress: () => { },
                    style: "cancel"
                },
                {
                    text: ST.OK, onPress: async () => {
                        BgUnsavedChanges(false)
                        await clear_item('storeData')
                        // setHasUnsavedChanges(false);
                        props.navigation.dispatch(e.data.action);
                    }
                }
            ]
        );
    }

    async function getData(storeData1, menu1) {
        try {
            let { StoreId } = storeData1;
            let AllKPIFields = await getKPIFields(menu1);
            setKPIFields(AllKPIFields);
            // set switch camera flag as defined in mapping menu flag (if exists)
            let SwitchingCameraI = AllKPIFields.findIndex(i => i.KPIFieldName == 'SwitchingCamera');
            let SwitchingCameraObj = SwitchingCameraI >= 0 ? AllKPIFields[SwitchingCameraI] : {};
            let SwitchingCamera = SwitchingCameraI >= 0 ? SwitchingCameraObj.KPIFieldEnable : false;
            setShowSwitchCamera(SwitchingCamera);

            let storeBGData1 = [], bgStoreJson = {}, isBgDataExists = false;
            let windData = await get_item('storeData')
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData)
                let { storeBGData, menuName, StoreId1, AddFormData, visiteDate } = StoreJson
                if (menuName == menu1.ScreenName && StoreId1 == StoreId && visiteDate == d2) {
                    isBgDataExists = true;
                    bgStoreJson = StoreJson
                    if (storeBGData.length > 0) {
                        storeBGData1 = storeBGData;
                        BgWindowData(storeBGData)
                    }

                    if (AddFormData != null && Object.keys(AddFormData).length > 0) {
                        let { CategoryId, SubCategoryId, BrandId, ProductId } = AddFormData;
                        console.log("AddFormData---------", JSON.stringify(AddFormData))
                        // load subcategories if category exists 
                        if (CategoryId != null && CategoryId != '') {
                            loadData(CategoryId, 'SubCategories');
                        }
                        if (SubCategoryId != null && CategoryId != '') {
                            loadData(SubCategoryId, 'Brands');
                        }

                        if (BrandId != null && ProductId != '') {
                            loadData(BrandId, 'Product');
                        }

                        BgAddVisFormData(AddFormData)
                    }
                    BgUnsavedChanges(true)
                }
            }
            await db.transaction(async function (txn) {
                let q = `Select Distinct p.CategoryId,p.CategoryName from Product_Master p where p.IsCompetitor= 0 order by p.CategorySequence`;
                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) { setCategories(arr); }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);


                let qr = `Select OrderReasonId as ReasonId, OrderReason as Reason From Master_NonOrderReason`;
                await txn.executeSql(qr, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            console.log("Reson_data", data)
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                setReasons_list(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);


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

                let q2 = `Select Distinct PackType,ImageAllow,RemarkAllow from Master_ProductPackType order by PackType`;
                await txn.executeSql(q2, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            arr.push(data);

                            if (i == txnres2.rows.length - 1) {
                                console.log("PackTypeList", arr)
                                setPackTypeList(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);


                let q3 = `Select * from ${AppTables.ORDER_SIMPLIFY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                console.log("arr---", q3);

                await txn.executeSql(q3, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let { JSON_DATA, PRESENT } = data;
                            let obj = JSON.parse(JSON_DATA)
                            console.log("obj---------",obj)

                            let isPresent = PRESENT;
                            if (i == txnres2.rows.length - 1) {
                                let {isVisPresent } = bgStoreJson

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


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

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

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

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


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

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

    async function getImage(imgdata) {
        setShowModal(true);
        if (typeof imgdata === 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify(ST.Cameraunavailable);
        }
        else if (typeof imgdata === 'object' && imgdata.uri != null) {
            const img = imgdata;
            const imgurl = img.uri, imgWidth = img.width, imgHeight = img.ExtendedHeight;
            let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
            let picture_clickedd = isImgFromGallery == true ? img.datetime : new Date();

            ////change by jeevanp
            let picture_clicked_time = moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name = moment(picture_clickedd).format('MMDDYYYY_HHmmss')
            console.log("time", picture_clicked_time);
            console.log("time1", picture_clicked_time_for_pic_name);
            ////change by jeevanp
            let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
            let calculate_tym_date_over_img = picture_clicked_time;

            let filename = storeData.StoreId + '_' + (props.UserId || '') + '_ORDERSIMPLIFYImg-' + calculate_tym_date_for_filename + '.jpg';
            ////change by jeevanp
            console.log("filename=>", filename)
            const mark_text1 = calculate_tym_date_over_img;
            const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: Order Simplify' + ' | Date:' + calculate_tym_date_over_img;

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

            let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    // render data with clicked image
                    let uri = 'file://' + imagePath;
                    addvisdata[image_path_key] = uri;
                    setSelectedImg(uri)
                    BgAddVisFormData(addvisdata)
                    BgUnsavedChanges(true)
                    setrerenderdata2(!rerenderdata2);
                    // add metdata then resize image and restored back to the imagePath
                    let restore_data = { "destFilePath": imagePath, "imgurl": imgurl, imgWidth, imgHeight, mark_text1, mark_text2 }
                    let is_restored = await restore_ImageWithMetaData(restore_data, imgdata);
                    console.log("image restored:", is_restored);
                })
                .catch(err => {
                    console.log('ERROR: image file write failed!!!');
                    console.log(err.message, err.code);
                });
        }
    }

    function _OpenCaptureImage_Modal(img) {
        const isImageCap = (img != '' || img != null) ? true : false;
        // console.log("imag pop is trigger",isImageCap,showModal,img)
        let { window, splitItem, splitItemIndex, cameraType } = reCapImgModalObj
        let camera2Label = (window && window.PromoImage2Lable) || '';
        return (
            <CustomModal
                style={customStyle.PromoImgModal}
                title={"Order 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={() => { setShowModal(false); openCamera('1') }}>
                            <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
                        </TouchableOpacity>
                        {
                            <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelImage() }}>
                                <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                            </TouchableOpacity>
                        }
                    </View>
                }
            </CustomModal>
        )
    }

    async function openCamera(type = '1') {
        console.log('openCamera');
        setClickImageType(type);
        setShowCamera(true);
    }

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

    async function saveData() {
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData + '...');
        setProcessing(true);
        try {
            let { StoreId } = storeData;
            let ReasonId = reason?.value != null ? reason?.value : 0;
            let Reason = reason?.label != null ? reason?.label : '';
            await db.transaction(async function (txn) {

                let q = `DELETE FROM ${AppTables.ORDER_SIMPLIFY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;

                //  remove old data
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('av data deleted');
                }, function (txnE, txnerr) { console.log(txnerr); },);



                let JsonStr = JSON.stringify(AddVisibility)
                let values = ` ('${StoreId}','${d2}', ${isAddVisPresent},${ReasonId},'${Reason}', '${JsonStr}','1','${d2}') `;

                console.log('values ORDER_SIMPLIFY:', values);
                let add_data = `INSERT INTO ${AppTables.ORDER_SIMPLIFY} (STORE_ID,VISIT_DATE,PRESENT,REASON_ID,REASON,JSON_DATA,IS_UPDATED,ADDED_DATE) VALUES ${values} `;

                console.log("add_data---", add_data)
                await txn.executeSql(add_data, [], async function (txn2, txnres) {
                    console.log('av added');
                    notify("Order added successfully", 'SHORT');
                    setProcessing(false);
                    // clear store data in local storage to avoiding re-set data for the store  
                    clear_item('storeData')
                    props.navigation.goBack();
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify("Cannot addad Return Stock") },);
            });
        } catch (err) {
            console.log(err);
        }
    }




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

        if (isAddVisPresent == 1 && AddVisibility.length <= 0) {
            isValid = false;
            notify(ST.Pleaseaddfirst, 'SHORT');
        } else if (isAddVisPresent != 1 && ShowReasonEnable == true && (reason?.value == null || reason?.value == '' || reason?.value == 0)) {
            notify('Please select reason', 'SHORT');
            isValid = false;
        }
        console.log('isValid:', isValid);
        return isValid;
    }

    async function validateForm() {
        let isValid = true;
        let { CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, ProductName, ProductId, Quantity, PackType, RemarkAllow, ImageAllow, Remark, Image1 } = AddVisFormData;
        if ((CategoryName == '' || CategoryName == null) || (CategoryId == '' || CategoryId == null)) {
            isValid = false;
            notify(ST.PleaseSelectCategory, 'SHORT');
        } else if ((SubCategoryName == '' || SubCategoryName == null) || (SubCategoryId == '' || SubCategoryId == null)) {
            isValid = false;
            notify(ST.Pleaseselectsubcategory, 'SHORT');
        } else if ((BrandName == '' || BrandName == null) || (BrandId == '' || BrandId == null)) {
            isValid = false;
            notify(ST.Pleaseselectbrand, 'SHORT');
        } else if (!(ProductName && ProductId)) {
            isValid = false;
            notify("Please select Product Name", 'SHORT');
        } else if (!Quantity) {
            isValid = false;
            notify("Please fill Order Quantity", 'SHORT');
        } else if (!(PackType)) {
            isValid = false;
            notify('Please select Pack Type', 'SHORT');
        } else if ((RemarkAllow || RemarkAllow == 1) && (Remark == '' || Remark == null)) {
            isValid = false;
            notify('Please enter remark', 'SHORT');
        } else if (StoreCameraAllow == true && (ImageAllow || ImageAllow == 1) && (Image1 == '' || Image1 == null)) {
            isValid = false;
            notify(ST.Pleaseclickimage, 'SHORT');
        }

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

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

        let data = AddVisFormData;
        data[key] = val;
        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onselectionChange(option, keyLbl, keyVal, otherData) {
        let data = AddVisFormData;
        console.log("option-------", option)
        data[keyVal] = option.value;
        data[keyLbl] = option.label;
        if (keyLbl == "PackType") {
            data = { ...data, ...option?.item }
        }
        console.log("data------", JSON.stringify(data))

        CleanSelector(option, keyLbl, data)
        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);

    }

    function CleanSelector(option, keyLbl = '', data = {}) {
        if (keyLbl == 'CategoryName') {
            loadData(option.value, 'SubCategories');
            data.SubCategoryId = '';
            data.SubCategoryName = '';
            data.BrandId = '';
            data.BrandName = '';
            data.Remark = ''
            data.Image1Path = ''
        }
        else if (keyLbl == 'SubCategoryName') {
            loadData(option.value, 'Brands');
            data.BrandId = '';
            data.BrandName = '';
            data.Image1Path = ''
            data.Remark = ''
        } else if (keyLbl == 'BrandName') {
            loadData(option.value, 'Product');
            data.Image1Path = ''
            data.Remark = ''
        } else if (keyLbl == 'DisplayName') {
            data.Image1Path = ''
            data.Remark = ''
        }

    }

    function CleanSelectorYes() {
        let data = AddVisFormData;

        data.SubCategoryId = '';
        data.SubCategoryName = '';
        data.BrandId = '';
        data.BrandName = '';

        data.Remark = ''
        data.Image1Path = ''

        BgAddVisFormData(data)
    }
    async function loadData(qId, type) {
        try {
            await db.transaction(async function (txn) {
                let q = '';
                if (type == 'SubCategories') q = `Select Distinct p.SubCategoryId,p.SubCategoryName from Product_Master p where p.CategoryId=${qId} and p.IsCompetitor=0 order by p.SubCategorySequence`;
                else if (type == 'Brands') q = `Select Distinct p.BrandName,p.BrandId from Product_Master p Where p.SubCategoryId=${qId} and p.IsCompetitor=0 order by p.BrandSequence`;
                else if (type == 'Product') q = `Select Distinct p.ProductId,p.ProductName from Product_Master p Where p.BrandId=${qId} and p.IsCompetitor=0 order by p.BrandSequence`;

                await txn.executeSql(q, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            arr.push(data);
                            if (i == txnres2.rows.length - 1) {
                                if (type == 'SubCategories') setSubCategories(arr);
                                else if (type == 'Brands') setBrands(arr);
                                else if (type == 'Product') setProductsList(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

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



    function onChoiceSelect(val, key) {
        if (val == 0 && AddVisibility.length > 0) {
            setShowRAllC_M(true);
            return;
        }
        var val1 = val == 1 ? 1 : 0;
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }

        if (val == 0) {
            CleanSelectorYes()
        }
        BgIsAddVisPresent(val);
        BgUnsavedChanges(true)
        if (val == 0) {
            BgWindowData([])
            BgAddVisFormData({})
        }
    }

    function onConfirmRemoveAll() {
        // Remove all data 
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: 0,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        BgIsAddVisPresent(0);
        BgUnsavedChanges(true)
        BgWindowData([])
        BgAddVisFormData({})
        setShowRAllC_M(false);
    }

    function onSaveCancel() {
        setShowAlert(false);
    }

    async function Add_AddVis() {
        let isValid = await validateForm();
        console.log('isValid add:', isValid);
        if (isValid) {
            let arr = AddVisibility;
            arr.push(AddVisFormData);
            BgWindowData(arr)
            BgUnsavedChanges(true)
            notify("Order added successfully", 'LONG');
            setrerenderdata(!rerenderdata);
            setAddVisFormData({})
        }
    }

    function showRemoveConfirm(item, index) {
        if (item.keyId > 0) {
            setToRemoveId(item.keyId);
            setToRemoveItem(item);
            setshowRemoveConfirm_M(true);
        }
        else {
            setToRemoveId(index);
            setToRemoveItem(item);
            setshowRemoveConfirm_M(true);
        }
    }

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

        db.transaction(async function (txn) {
            let index = toRemoveId;
            let item = toRemoveItem;
            let arr = AddVisibility;
            if (item.keyId != null && item.keyId != 'undefined' && index > 0) {
                let deleteQuery = `DELETE FROM ${AppTables.ORDER_SIMPLIFY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' AND KEY_ID='${index}' `;

                txn.executeSql(deleteQuery, [], function (txn3, txnres) {
                    console.log('Order data deleted', item.keyId, +"" + index);
                    let updatedVisibility = AddVisibility.filter(item => item.keyId !== index);
                    setAddVisibility(updatedVisibility);
                    setHasUnsavedChanges(true);
                    notify('Order removed successfully', 'LONG');
                    setrerenderdata(!rerenderdata);
                    setToRemoveId('');
                    setToRemoveItem({});
                    setshowRemoveConfirm_M(false);
                }, function (txnE, txnerr) {
                    console.log('Error deleting survey data:', txnerr);
                });
            }
            else {
                let index = toRemoveId
                let item = toRemoveItem;
                let arr = AddVisibility;
                console.log('toRemoveId:', index);
                if (index >= 0 && index < arr.length) {
                    arr.splice(index, 1);
                    setAddVisibility(arr);
                    setHasUnsavedChanges(true);
                    notify('Order removed successfully', 'LONG')
                    setrerenderdata(!rerenderdata);
                }
                else {
                    notify('Cannot remove! Order not found', 'LONG')
                }
                setToRemoveId('');
                setToRemoveItem({});
                setshowRemoveConfirm_M(false);
            }

        });
    }

    function onselectionChange3(option, keyLbl, keyVal, otherData) {
        console.log("option",option)
        setReason(option);
    }

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

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

        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.addvisCon]}>

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

                    <View style={[customStyle.addvis_pChoiceBoxCon, { flex: 2 }, isAddVisPresent == 1 ? { alignItems: 'center' } : {}]}>
                        <View style={[customStyle.openStk_prd_choiceBox, customStyle.addvis_pChoiceBoxbg]}>
                            <Animated.View style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, (isAddVisPresent == '1' ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red),
                            {
                                transform: [{
                                    translateX: xpos
                                }],
                            }
                            ]}></Animated.View>
                            <TouchableOpacity style={customStyle.openStkCh_con1} onPress={() => { onChoiceSelect(1, 'isPresent') }}>
                                <Text style={[customStyle.openStkCh_text, (isAddVisPresent == 1 ? customStyle.openStkCh_textactive : {})]}>Yes</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(0, 'isPresent') }}>
                                <Text style={[customStyle.openStkCh_text, (isAddVisPresent == 0 ? customStyle.openStkCh_textactive : {})]}>No</Text>
                            </TouchableOpacity>
                        </View>
                    </View>

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

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

                {
                    isAddVisPresent == 1 && (rerenderdata == rerenderdata) &&
                    <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.addVisScroll}>
                        <View style={customStyle.addVisForm}>
                            <View style={customStyle.addVisRow}>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{ST.Category}</Text>
                                        {CustomPicker(props, Categories, 'CategoryName', 'CategoryId', 'CategoryName', 'CategoryId', onselectionChange, { value: AddVisFormData.CategoryName })}

                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol2]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{'Sub Category'}</Text>
                                        {CustomPicker(props, SubCategories, 'SubCategoryName', 'SubCategoryId', 'SubCategoryName', 'SubCategoryId', onselectionChange, { value: AddVisFormData.SubCategoryName })}
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{ST.Brands}</Text>
                                        {CustomPicker(props, Brands, 'BrandName', 'BrandId', 'BrandName', 'BrandId', onselectionChange, { value: AddVisFormData.BrandName })}
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol2]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{"Product"}</Text>
                                        {CustomPicker(props, ProductsList, 'ProductName', 'ProductId', 'ProductName', 'ProductId', onselectionChange, { value: AddVisFormData.ProductName })}
                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{"Order Quantity"}</Text>
                                        <TextInput
                                            style={customStyle.addVisInputStyle}
                                            autoComplete='off'
                                            value={(AddVisFormData.Quantity || '')}
                                            onChangeText={(val) => {
                                                // ✅ Only allow digits (no decimal point, no letters)
                                                const numericVal = val.replace(/[^0-9]/g, "").slice(0, 3);
                                                onFormDataChange(numericVal, 'Quantity', 'text');
                                            }
                                            }
                                            keyboardType="numeric"   // ✅ opens numeric keyboard
                                            maxLength={3}
                                        />
                                    </View>
                                </View>

                                <View style={[customStyle.addVisCol50, customStyle.addVisCol2]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{"Pack Type"}</Text>
                                        {CustomPicker(props, PackTypeList, 'PackType', 0, 'PackType', 0, onselectionChange, { value: AddVisFormData.PackType })}
                                    </View>
                                </View>
                                {(AddVisFormData?.RemarkAllow || AddVisFormData?.RemarkAllow == 1) && <View style={[customStyle.addVisCol100, customStyle.addVisCol1]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{"Remark"}</Text>
                                        <TextInput
                                            style={customStyle.addVisInputStyle}
                                            autoComplete='off'
                                            value={(AddVisFormData.Remark || '')}
                                            onChangeText={(val) => { onFormDataChange(val, 'Remark', 'text'); }}
                                        />
                                    </View>
                                </View>}
                                {
                                    (AddVisFormData?.ImageAllow || AddVisFormData?.ImageAllow == 1) &&
                                    <View style={[customStyle.addVisCol100]}>
                                        <View style={customStyle.addVisFormGrp}>
                                            <Text style={customStyle.addVisLabel}>{ST.Image}</Text>
                                            <View style={customStyle.addVisCameras}>
                                                <View style={customStyle.openStkCameraCon}>
                                                    {(AddVisFormData.Image1Path == '' || AddVisFormData.Image1Path == null) ?
                                                        <TouchableOpacity onPress={() => { openCamera('1') }}>
                                                            <CameraImg5 width={50} height={50} />
                                                        </TouchableOpacity> : (AddVisFormData.Image1Path != '' && AddVisFormData.Image1Path != null) ?
                                                            <TouchableOpacity onPress={() => { OpenImgModal(AddVisFormData.Image1Path, '1') }}>
                                                                <CameraImg3 width={50} height={50} />
                                                            </TouchableOpacity> : null
                                                    }
                                                </View>

                                            </View>
                                        </View>
                                    </View>
                                }
                                <View style={customStyle.addVis_btnWrap}>
                                    <TouchableOpacity style={customStyle.addVis_btn} onPress={() => { Add_AddVis() }}>
                                        <Text style={customStyle.addVisBtnText}>{ST.Add}</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>

                        {AddVisibility.length > 0 && <View style={customStyle.addVis_list}>
                            <Text style={customStyle.addVis_listhdrText}>{"Added Orders"}</Text>
                            <View style={customStyle.addVis_listInner}>
                                {
                                    AddVisibility.length > 0 &&
                                    AddVisibility.map((item, index) => {
                                        console.log(item);
                                        return (
                                            <View key={index} style={customStyle.addVis_listItem}>
                                                <View style={customStyle.addVis_listI_row2}>
                                                    <View style={[(AddVisCameraReq && item.Image1Path) ? customStyle.addVis_listIcol1 : customStyle.addVis_listIcol100]}>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>{ST.Category + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item?.CategoryName}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>{ST.SubCategory + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item?.SubCategoryName}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>{ST.Brands + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item?.BrandName}</Text>
                                                        </View>
                                                        <View style={customStyle.addVis_listI_row}>
                                                            <Text style={customStyle.addVis_listI_Label}>{"Product" + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item?.ProductName}</Text>
                                                        </View>
                                                        <View style={[customStyle.addVis_listI_row]}>
                                                            <Text style={customStyle.addVis_listI_Label}>{'Order Quantity :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item?.Quantity}</Text>
                                                        </View>
                                                        <View style={[customStyle.addVis_listI_row]}>
                                                            <Text style={customStyle.addVis_listI_Label}>{'Pack Type :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item?.PackType}</Text>
                                                        </View>
                                                        {item?.Remark && <View style={[customStyle.addVis_listI_row]}>
                                                            <Text style={customStyle.addVis_listI_Label}>{ST.Remark + ' :'}</Text>
                                                            <Text style={customStyle.addVis_listI_Val}>{item?.Remark}</Text>
                                                        </View>}
                                                    </View>
                                                    {AddVisCameraReq && item.Image1Path &&
                                                        <View style={customStyle.addVis_listIcol2}>
                                                            <Text style={[customStyle.addVis_listI_Label2, customStyle.mb20]}>{ST.Image}</Text>
                                                            {(item.Image1Path != null && item.Image1Path != '') && <Image style={customStyle.addVis_listI_Image} source={{ uri: item.Image1Path }} />}
                                                        </View>}
                                                    <TouchableOpacity style={customStyle.addVis_btnRemove} onPress={() => { showRemoveConfirm(item, index) }}>
                                                        <FontAwesome name='trash' size={20} color={'red'} />
                                                    </TouchableOpacity>
                                                </View>


                                            </View>
                                        );
                                    })
                                }
                            </View>
                        </View>}

                    </ScrollView>
                }
            </View>
        )
    }



    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <View style={{ zIndex: 10 }}>
                <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            </View>
            {_OpenCaptureImage_Modal()}

            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            {ConfirmSaveAlert(props, showRemoveConfirm_M, () => { setshowRemoveConfirm_M(false) }, Remove_AddVis, "Do you really want to remove this Order ?")}
            {ConfirmSaveAlert(props, showRAllC_M, () => { setShowRAllC_M(false) }, onConfirmRemoveAll, "Do you really want to remove all Order data?")}
            <CustomCamera cameraType={'back'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: ' + currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData) => { setShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { setShowCamera(false); }} />

            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper, customStyle.zIndex0]}>
                <View style={[customStyle.pageContentWrapper]}>
                    {Object.keys(storeData).length > 0 &&
                        <View style={customStyle.addVis_Wrapper}>
                            {_render_addVisFormTop()}
                        </View>
                    }
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                        <GradientButton {...props} title={ST.Save} onPress={() => { onSubmitData() }} />
                    </View>
                </View>

            </LinearGradient>

        </Container>
    );
}


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