import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles, GetPageTheme, STATUSBAR_HEIGHT } from "../styles/Global";
import { Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, FlatList, Alert, Dimensions, Animated, Easing, AppState, Keyboard, KeyboardAvoidingView } from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { getAllFolderImages, getforgotpasswordotp, getKPIFields, getmobileverifyotp, marktext1, marktext2, resizeImage, restore_ImageWithMetaData, validateNumber, verifymobileotp } from '../controller/functions';
import { db, common_ImagePath, ImageFolderPath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, FontAwesome, FontAwesome5, Fontisto, 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 { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector';
import MultiSelect from 'react-native-multiple-select';
import DateTimePicker from '@react-native-community/datetimepicker';
import DraggableFlatList, { ScaleDecorator } from 'react-native-draggable-flatlist'
import AudioRecorderPlayer, { AudioEncoderAndroidType, AudioSourceAndroidType, AVEncoderAudioQualityIOSType, AVEncodingOption, AVModeIOSOption } from 'react-native-audio-recorder-player';
import CustomCamera from '../components/Camera';
import { clear_item, get_item, set_item } from '../components/localStorage';
import CameraImg5 from '../assets/image/astrickcamera.svg';
import ImageViewer from 'react-native-image-zoom-viewer';

import OtpInputs from 'react-native-otp-inputs';
import { KeyboardAwareFlatList, KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';


const { height, width } = Dimensions.get('window');
const topbarht = STATUSBAR_HEIGHT + 50;
const actualWindowHt = parseInt((height - topbarht) + 10);


function SurveyView(props) {
    const route = useRoute();
    const ST = props.StaticText || {};
    const audioRecorderPlayer = new AudioRecorderPlayer();
    const AudioSet = {
        AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
        AudioSourceAndroid: AudioSourceAndroidType.MIC,
        AVModeIOS: AVModeIOSOption.measurement,
        AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
        AVNumberOfChannelsKeyIOS: 2,
        AVFormatIDKeyIOS: AVEncodingOption.aac,
    };
    // get all theme styles acc to current theme set 
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);

    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [showRating, setShowRating] = useState(false);
    const [RatingQtn, setRatingQtn] = useState({});
    const [RatingOrder, setRatingOrder] = useState([]);
    const [showRecorder, setShowRecorder] = useState(false);
    const [VRS, setVRS] = useState({});
    const [RecorderTimer, setRecorderTimer] = useState({});
    const [playerTimer, setPlayerTimer] = useState({});
    const [rerenderView, setRerenderView] = useState(0);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [VoiceRecorderStatus, setVoiceRecorderStatus] = useState(ST.Pressmictostartrecordingvoice);
    const [RecFilePath, setRecFilePath] = useState({});
    const [dateValue, setDateValue] = useState('');
    const [openDatePicker, setOpenDatePicker] = useState(0);
    const [storeData, setStoreData] = useState({});
    const [ShowCat, setShowCat] = useState(false);
    const [ActiveSurvey, setActiveSurvey] = useState({});
    const [ActiveCategory, setActiveCategory] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [rerenderdata, setrerenderdata] = useState(0);
    const [SurveySubCats, setSurveySubCats] = useState([]);
    const [SurveyQuestions, setSurveyQuestions] = useState([]);
    const [QuestionsData, setQuestionsData] = useState({});
    const [showAlert, setShowAlert] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps, setGetImageProps] = useState({});
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera, setShowSwitchCamera] = useState(false);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [refImageIndex, setrefImageIndex] = useState(0);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [showDatePickerId, setShowDatePickerId] = useState({});
    const zoomView = useRef(null);
    const inputRefs = useRef({});
    const otpRef = useRef();

    const animatedRipple = useRef(new Animated.Value(0)).current;
    const animatedRipple2 = useRef(new Animated.Value(0.5)).current;

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(QuestionsData);
    const SurveyQuestionsRef = React.useRef(SurveyQuestions);
    const SurveySubCatsRef = React.useRef(SurveySubCats);


    function bgSurveyQuestions(val) {
        SurveyQuestionsRef.current = val
        setSurveyQuestions(val);
    }

    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef({});
    const NavigationRef = React.useRef({});
    const CateRef = React.useRef({});

    // error field states
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = useState(false);

    const d1 = new Date();
    const d2 = moment(d1).format('MM/DD/YYYY');

    useEffect(() => {
        setLoaderTitle(ST.Loading + '...')
        let params = props.route.params ? props.route.params : {};
        let storeData1 = params.storeData || {};
        let surveydata = params.surveyData || {};
        let catData = params.catData || {};
        // console.log("surveyandcatdata1111:", JSON.stringify(surveydata) + " ", catData);
        let menu1 = params.menu || {};
        let ShowCat1 = params.ShowCat || false;
        let isAdhoc = params.isAdhocScreen || false;
        let isBeat = params.isBeat || false;
        CateRef.current = catData;
        setShowCat(ShowCat1);
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setActiveSurvey(surveydata)
        setCurrentMenu(menu1);
        setActiveCategory(catData)

        StoreIdRef.current = storeData1.StoreId
        ScreenNameRef.current = { BgscreenName: menu1.ScreenName, BgMenuId: menu1.MenuId }
        let navData = {
            'surveyData': surveydata,
            'storeData': storeData1,
            'menu': menu1,
            'isAdhocScreen': isAdhoc,
            'isBeat': isBeat,
            'ShowCat': ShowCat1
        }
        NavigationRef.current = navData
        getSurveyData(surveydata, catData, storeData1, ShowCat1, menu1);
        const AppStateSubscription = AppState.addEventListener('change', (pro) => { _handleAppStateChange(pro) });
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
        return (() => {
            audioRecorderPlayer.removePlayBackListener();
            audioRecorderPlayer.removeRecordBackListener();
            AppStateSubscription.remove();
            return unsubscribe;
        });
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        if (nextAppState == 'background' && hasUnsavedChangesRef.current == true) {
            // ✅ include this
            //console.log("Saving WindowDataRef:", WindowDataRef.current);
            console.log("Saving SurveySubCatsRef", SurveySubCatsRef.current)
            let newData = {
                storeBGData: WindowDataRef.current,
                menuName: ScreenNameRef.current && ScreenNameRef.current.BgscreenName,
                StoreId1: StoreIdRef.current,
                NavData: NavigationRef.current,
                SurveyQuestionsData: SurveyQuestionsRef.current,
                SurveySubCats: SurveySubCatsRef.current,
                BgMenuID: ScreenNameRef.current && ScreenNameRef.current.BgMenuId,
                CategoryInfo: CateRef.current,
                visiteDate: d2
            }
            let WindowsStr = JSON.stringify(newData)
            console.log("jsonnnn", WindowsStr)
            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]);

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

    function onBeforeRemove(e) {
        if (showCamera == true) {
            e.preventDefault();
            setShowCamera(false);
        }
        else if (show_zoomImage == true) {
            e.preventDefault();
            setShow_zoomImage(false);
        }
        else {
            if (hasUnsavedChanges == true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else {
                return;
            }
        }
    }

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

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

    function BgSurveySubCats(val) {
        SurveySubCatsRef.current = val
        setSurveySubCats(val);
    }

    function onRemoveScreen(e) {
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
                {
                    text: ST.Cancel,
                    onPress: () => { },
                    style: "cancel"
                },
                {
                    text: ST.OK, onPress: async () => {
                        // setHasUnsavedChanges(false);
                        BgUnsavedChanges(false)
                        await clear_item('storeData')
                        props.navigation.dispatch(e.data.action);
                    }
                }
            ]
        );
    }


    async function getSurveyData(item, catData = {}, storeData1, ShowCat1, menu1) {
        try {
            let { StoreId } = storeData1;
            let { CategoryId } = catData;
            let { SurveyId } = item;
            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')
            // console.log("windData in promooo:", windData);
            if (windData != null && windData != '') {
                let StoreJson = JSON.parse(windData)
                let { storeBGData, menuName, StoreId1, BgMenuID, visiteDate, SurveyQuestionsData, SurveySubCats } = StoreJson
                if (Object.keys(storeBGData).length > 0 && menuName == menu1.ScreenName && menu1.MenuId == BgMenuID && StoreId1 == StoreId && visiteDate == d2) {
                    isBgDataExists = true;
                    storeBGData1 = storeBGData;
                    bgStoreJson = StoreJson
                    BgUnsavedChanges(true)
                    BgSurveySubCats(SurveySubCats)
                    BgWindowData(storeBGData)
                    bgSurveyQuestions(SurveyQuestionsData)
                }
            }

            await db.transaction(async function (txn) {
                let q2 = `SELECT DISTINCT T.SubCategory,T.SubCategoryId,T.SubCategorySequence,T.RefImage FROM Master_SurveyQuestion T INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId WHERE M.StoreId='${StoreId}' and T.SurveyId='${SurveyId}' `;

                if (ShowCat1 == true) {
                    q2 += ` and T.CategoryId='${CategoryId}' `;
                }
                q2 += ` order by T.QuestionSequence`;

                // console.log("surbeysize:", q2)
                await txn.executeSql(q2, [], async function (txn2, txnres) {
                    console.log('survey subcats:', txnres.rows.length);
                    if (txnres.rows.length > 0) {
                        let arr = [], images = [], allQtns = [];
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            // console.log("dataaaa:", data)
                            let all_scat_qtns = await getSurveyQtns(item, catData, storeData1, ShowCat1, data, menu1, bgStoreJson, isBgDataExists)
                            data['Questions'] = all_scat_qtns;
                            //console.log("question,,,", data);
                            allQtns = allQtns.concat(all_scat_qtns);
                            arr.push(data);
                            if (i == txnres.rows.length - 1) {
                                // if (!isBgDataExists) {
                                BgSurveySubCats(arr)
                                bgSurveyQuestions(allQtns)
                                // }
                                setProcessing(false);
                            }
                        }
                    }

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

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

    const [verifiedOTP, setVerifiedOTP] = useState(false);

    ///jp fixed queation enable disable on app kill
    const getWindowQuestionsById = (bgJsonDta, CategoryId, SubCategoryId) => {
        const item = bgJsonDta?.SurveyQuestionsData?.find(
            i => i.CategoryId == CategoryId && i.SubCategoryId == SubCategoryId
        );

        const values = item?.WindowQuestions;

        if (Array.isArray(values) && values.length > 0) {
            return values;
        } else {
            return bgJsonDta?.SurveyQuestionsData || [];
        }
    };


    async function getSurveyQtns(item, catData, storeData1, ShowCat1, subCat, menu1, bgStoreJson = {}, isBgDataExists = false) {
        let questionsBg = []
        let { StoreId } = storeData1;
        let { CategoryId } = catData;
        let { SurveyId } = item;
        let { SubCategoryId } = subCat;
        ///jp fixed queation enable disable on app kill
        console.log("bgStoreJson_new", bgStoreJson);
        if (isBgDataExists) {
            questionsBg = getWindowQuestionsById(bgStoreJson, CategoryId, SubCategoryId);
            console.log("bgStoreJson_new", CategoryId, SubCategoryId, questionsBg);
        }

        return new Promise((resolve, reject) => {
            try {

                db.transaction(async function (txn) {
                    // get inserted audit
                    let selectlist = ` DISTINCT ifnull(T1.VerifyOTP,0)as VerifyOTP,T.MaxLength as MaxLength,T.QuestionRefImage,T.CalFormula,T.RefImage,T.MinLength as MinLength,T.CategoryId,T.Category,T.SubCategoryId,T.SubCategory, T.Image1Mandatory, T.Image2Mandatory,T.QuestionImageMandatory,T.LengthValidation as LengthValidation,T.QuestionImageAllow as QuestionImageAllow,T.DateRange as DateRange,T.QEnable,T.Question as Question,T.QuestionId as QuestionId,T.QuestionTypeNew as QuestionType,T.OTP as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.IMAGE_ALLOW2 as ImageAllow2,T1.IMAGE2 as Image2,T1.MULTI_OPTIONS_IDS as multi_op_ids,T1.IS_DISABLED as isDisabled `;
                    let join = ` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
                    let join2 = ` INNER JOIN ${AppTables.SURVEY} T1 on T.SurveyId=T1.SURVEY_ID and T.CategoryId=T1.CATEGORY_ID and T.SubCategoryId=T1.SUB_CATEGORY_ID And T.QuestionId=T1.QUESTION_ID`;
                    let q2 = `Select ${selectlist} FROM Master_SurveyQuestion T ${join} ${join2} WHERE T1.STORE_ID='${StoreId}' AND T1.MENU_ID=${menu1.MenuId} AND T1.VISIT_DATE= '${d2}' AND T1.SURVEY_ID=${SurveyId}  AND T1.SUB_CATEGORY_ID='${SubCategoryId}'  `;
                    if (ShowCat1 == true) {
                        q2 += ` AND  T1.CATEGORY_ID=${CategoryId} `;
                    }
                    q2 += ` GROUP BY T.QuestionId ORDER BY T.QuestionSequence`;


                    await txn.executeSql(q2, [], async function (txn2, txnres) {
                        console.log('getSurveyData len', txnres.rows.length);
                        if (txnres.rows.length > 0) {
                            let arr = [], images = [];
                            var QD = QuestionsData;
                            for (var i = 0; i < txnres.rows.length; i++) {
                                let data = txnres.rows.item(i);
                                ////console.log("data---------", data)
                                data.QEnable = data.QEnable == 1 || data.QEnable == 'true' ? true : false;
                                let answers = [];
                                let qtn = data;
                                // console.log("dataaaaaaaa", isBgDataExists, qtn)
                                qtn.isDisabled = qtn.isDisabled == 1 || qtn.isDisabled == '1' ? true : false
                                ///jp fixed queation enable disable on app kill
                                if (isBgDataExists) {
                                    if (questionsBg != null && questionsBg != undefined && Array.isArray(questionsBg) && questionsBg.length > 0) {
                                        const isEnabled = questionsBg.some(q =>
                                            q.QuestionId === data.QuestionId && q.isDisabled === false
                                        );
                                        if (isEnabled) {
                                            data['isDisabled'] = false;
                                            console.log("Matched Question:", data.QuestionId);
                                        } else {
                                            data['isDisabled'] = true;
                                        }
                                    }
                                }
                                if (qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Number' || qtn.QuestionType == 'Text' || qtn.QuestionType == 'OnlyText' || qtn.QuestionType == 'Image') {
                                    inputRefs.current['input1_' + qtn.QuestionId] = '';
                                }

                                if (data.QuestionType == 'Multi choice list' || data.QuestionType == 'Single choice list' || data.QuestionType == 'Rating') {
                                    let allanswers = await getAnswers(data, item.SurveyId, storeData1, true);

                                    answers = allanswers.Answers || [];
                                    if (data.QuestionType == 'Rating') {
                                        data.showRating = false;
                                    }
                                }
                                else if (data.QuestionType == 'Date') {
                                    data.showDatePicker = false;
                                }
                                data.Answers = answers;

                                let id_key = qtn.QuestionId + '_AnswerId';
                                let ans_key = qtn.QuestionId + '_Answer';
                                let multi_key = qtn.QuestionId + '_MultiOption';
                                let date_key = qtn.QuestionId + '_Date';
                                let img_key = qtn.QuestionId + '_ImagePath1';
                                let imgname_key = qtn.QuestionId + '_ImageName1';
                                let img_key2 = qtn.QuestionId + '_ImagePath2';
                                let imgname_key2 = qtn.QuestionId + '_ImageName2';
                                let rating_key = qtn.QuestionId + '_Rating';
                                let voiceClip_key = qtn.QuestionId + '_VoiceClip';

                                let showImageTag = (data.QuestionImageAllow == true || data.QuestionImageAllow == 'true' || data.QuestionImageAllow == 1);
                                let showImageTag2 = false;

                                QD[id_key] = data.AnswerId;
                                QD[ans_key] = data.Answer;


                                let selansid = data.AnswerId;
                                if (qtn.QuestionType == 'Multi choice list') {
                                    console.log("data-----", data)
                                    selansid = data.multi_op_ids ? data.multi_op_ids.split(',') : [];
                                    QD[multi_key] = data.multi_op_ids;
                                }

                                if ((qtn.QuestionType == 'Single choice list' || qtn.QuestionType == 'Multi choice list')) {
                                    if (qtn.Answers && qtn.Answers.length > 0) {
                                        for (var k = 0; k < qtn.Answers.length; k++) {
                                            let ansss = qtn.Answers[k];
                                            let isandImgAl = (ansss.ImageAllow1 == true || ansss.ImageAllow1 == 'true' || ansss.ImageAllow1 == 1);
                                            let isandImgAl2 = (ansss.ImageAllow2 == true || ansss.ImageAllow2 == 'true' || ansss.ImageAllow2 == 1);

                                            if (qtn.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                                                showImageTag = true;
                                            }
                                            else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId.toString()) >= 0)) {
                                                showImageTag = true;
                                            }

                                            if (qtn.QuestionType == 'Single choice list' && (isandImgAl2 && ansss.AnswerId == selansid)) {
                                                showImageTag2 = true;
                                            }
                                            else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId.toString()) >= 0)) {
                                                showImageTag2 = true;
                                            }

                                        }
                                    }
                                }

                                if (showImageTag) {
                                    let imgPath = data.Image1 != '' ? ((Platform.OS == 'ios' ? 'file://' : '') + `${ImageFolderPath + menu1.ScreenName}/` + data.Image1) : '';
                                    QD[imgname_key] = data.Image1;
                                    QD[img_key] = imgPath;
                                }

                                if (showImageTag2) {
                                    let imgPath = data.Image2 != '' ? ((Platform.OS == 'ios' ? 'file://' : '') + `${ImageFolderPath + menu1.ScreenName}/` + data.Image2) : '';
                                    QD[imgname_key2] = data.Image2;
                                    QD[img_key2] = imgPath;
                                }

                                if (qtn.QuestionType == 'Audio') {
                                    let voicefile_path = (Platform.OS == 'ios' ? 'file://' : '') + `${ImageFolderPath + menu1.ScreenName}/` + 'Recordings/' + data.Answer;
                                    QD[voiceClip_key] = { 'path': voicefile_path, 'filename': data.Answer };
                                }

                                if (qtn.QuestionType == 'Date') {
                                    let dayonly = moment().format('DD');
                                    let actual_date = data.Answer ? data.Answer.split('/') : [];
                                    let month = actual_date[0], year = actual_date[1];
                                    let fulldate = month + '/' + dayonly + '/' + year;
                                    QD[date_key] = fulldate;

                                }
                                arr.push(data);
                                if (i == txnres.rows.length - 1) {
                                    if (!isBgDataExists) {
                                        BgWindowData(QD)
                                    }
                                    resolve(arr);
                                }
                            }
                        }
                        else {
                            let sl = ` DISTINCT T.CategoryId,T.Category,T.CalFormula,T.RefImage,T.QuestionRefImage,T.Image1Mandatory, T.Image2Mandatory,T.QuestionImageMandatory,T.SubCategoryId,T.SubCategory,T.MaxLength,T.MinLength,T.LengthValidation,T.Question,T.QuestionId,T.QuestionTypeNew as QuestionType,T.OTP,T.QuestionImageAllow,T.DateRange,T.QEnable`;
                            let q = ` SELECT ${sl} FROM Master_SurveyQuestion T INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId WHERE M.StoreId='${StoreId}' and T.SurveyId='${SurveyId}' and T.SubCategoryId='${SubCategoryId}' `;
                            if (ShowCat1 == true) {
                                q += ` and T.CategoryId='${CategoryId}'  `;
                            }
                            q += `group by T.QuestionId  ORDER BY T.QuestionSequence`;

                            await txn.executeSql(q, [], async function (txn2, txnres2) {
                                console.log('Surveys:', txnres2.rows.length)
                                let arr = [];
                                if (txnres2.rows.length > 0) {
                                    for (var i = 0; i < txnres2.rows.length; i++) {
                                        let data = txnres2.rows.item(i);
                                        data.QEnable = data.QEnable == 1 || data.QEnable == 'true' ? true : false;
                                        data['isDisabled'] = !data.QEnable;
                                        data['VerifyOTP'] = 0
                                        let qtn = data;

                                        qtn.isDisabled = qtn.isDisabled == 1 || qtn.isDisabled == '1' ? true : false

                                        ///jp fixed queation enable disable on app kill
                                        if (isBgDataExists) {
                                            //console.log("isBgDataExists",isBgDataExists);

                                            if (questionsBg != null && questionsBg != undefined && Array.isArray(questionsBg) && questionsBg.length > 0) {
                                                const isEnabled = questionsBg.some(q =>
                                                    q.QuestionId === data.QuestionId && q.isDisabled === false
                                                );
                                                //console.log("isEnabled", isEnabled);

                                                if (isEnabled) {
                                                    data['isDisabled'] = false;
                                                    // console.log("Matched Question:", data.QuestionId);
                                                } else {
                                                    data['isDisabled'] = true;
                                                }
                                            }
                                        }

                                        if (qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Number' || qtn.QuestionType == 'Text' || qtn.QuestionType == 'OnlyText' || qtn.QuestionType == 'Image') {
                                            inputRefs.current['input1_' + qtn.QuestionId] = '';
                                        }

                                        let answers = [];
                                        if (data.QuestionType == 'Multi choice list' || data.QuestionType == 'Single choice list' || data.QuestionType == 'Rating') {
                                            let allanswers = await getAnswers(data, item.SurveyId, storeData1, false);
                                            answers = allanswers.Answers || [];
                                            if (data.QuestionType == 'Rating') {
                                                data.showRating = false;
                                            }
                                        }
                                        else if (data.QuestionType == 'Date') {
                                            data.showDatePicker = false;
                                        }

                                        data.Answers = answers;

                                        arr.push(data);
                                        //console.log("arrrrr",arr)

                                        if (i == txnres2.rows.length - 1) {
                                            resolve(arr);
                                        }
                                    }
                                }
                                else {
                                    resolve([]);
                                }

                            }, function (txnE, txnerr) { console.log(txnerr); resolve([]); },);
                        }

                    }, function (txnE, txnerr) { console.log(txnerr); resolve([]); },);

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

    async function getAnswers(qtn, SurveyId, storeData1, isInserted) {
        let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                // get inserted audit
                let selectlist = ` DISTINCT T.Answer,T.AnswerId,T.ImageAllow1,T.ImageAllow2,T.Image1Mandatory,T.Image2Mandatory,T.EnableQuestion,T.DisableQuestion`;
                let join = ` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
                let q2 = `Select ${selectlist} FROM Master_SurveyQuestion T ${join} WHERE T.QuestionId='${qtn.QuestionId}' AND M.StoreId = '${StoreId}' AND T.SurveyId==${SurveyId} AND T.SubCategoryId='${qtn.SubCategoryId}' ORDER BY T.AnswerSequence `;

                await txn.executeSql(q2, [], async function (txn2, txnres) {
                    // console.log('answers len',txnres.rows.length);
                    if (txnres.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            arr.push(data);
                            if (i == txnres.rows.length - 1) {
                                resolve(arr);
                            }
                        }
                    }
                    else {
                        resolve([]);
                    }
                }, function (txnE, txnerr) { console.log(txnerr); resolve([]); },);

            });
        }).then((val) => {
            return { 'Answers': val, 'Success': true };
        }).catch((err) => {
            console.log(err);
            return { 'Success': false, 'Error': err }
        });
    }

    async function getImage(imgdata) {
        let qtn = getImageProps.qtn || '';
        let type = getImageProps.type || '1';
        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();

            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 + '_' + ActiveSurvey.SurveyId + '_' + qtn.QuestionId + '_SurveyImg_' + 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 + ' | Survey Id:' + ActiveSurvey.SurveyId + ' | Question Id :' + qtn.QuestionId + ' | Image Type: ' + currentMenu.MenuName + ' | Date:' + calculate_tym_date_over_img;

            let qd = QuestionsData;
            let img_key = type == '1' ? qtn.QuestionId + '_ImagePath1' : qtn.QuestionId + '_ImagePath2';
            let imgname_key = type == '1' ? qtn.QuestionId + '_ImageName1' : qtn.QuestionId + '_ImageName2';
            qd[imgname_key] = filename;

            let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;
            await RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    let uri = 'file://' + imagePath;
                    console.log('image marker', uri);
                    qd[img_key] = uri;
                    if (qtn.QuestionType == "Image") {
                        //set answid - 0 and answer to filename if qtnType is Image
                        let id_key = qtn.QuestionId + '_AnswerId';
                        let ans_key = qtn.QuestionId + '_Answer';
                        qd[id_key] = 0;
                        qd[ans_key] = "";
                        // qd[ans_key]=filename;
                    }

                    // 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);
                    BgWindowData(qd)
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                })
                .catch(err => {
                    console.log('ERROR: image file write failed!!!');
                    console.log(err.message, err.code);
                });

        }
    }

    async function openCamera(qtn, type) {
        setGetImageProps({ 'qtn': qtn, 'type': type });
        setShowCamera(true);
    }


    async function disableQtns(sqtns, DQtns, data, isreturn = false) {
        if (DQtns.length === 0) return sqtns;
        const sqtnsCopy = (sqtns || []).map(q => ({ ...q }));
        for (const qid of DQtns) {
            const s_qtnindex = sqtnsCopy.findIndex(i => i.QuestionId == qid);
            if (s_qtnindex >= 0) {
                const s_qtn = sqtnsCopy[s_qtnindex];
                sqtnsCopy[s_qtnindex] = { ...s_qtn, isDisabled: true };
                const id_key = s_qtn.QuestionId + '_AnswerId';
                const ans_key = s_qtn.QuestionId + '_Answer';
                const imgname_key = s_qtn.QuestionId + '_ImageName1';
                const imgname_key2 = s_qtn.QuestionId + '_ImageName2';
                const img_key = s_qtn.QuestionId + '_ImagePath1';
                const img_key2 = s_qtn.QuestionId + '_ImagePath2';
                const multi_option = s_qtn.QuestionId + '_MultiOption';
                data[id_key] = 0;
                data[ans_key] = '';
                data[img_key] = '';
                data[img_key2] = '';
                data[imgname_key] = '';
                data[imgname_key2] = '';
                data[multi_option] = '';
            }
        }
        setSurveyQuestions(sqtnsCopy);
        BgWindowData({ ...data });
        BgUnsavedChanges(true);
        bgSurveyQuestions(sqtnsCopy);
        setrerenderdata((prev) => !prev);
        return sqtnsCopy;
    }

    async function enableQtns(sqtns, EQtns, DQtns, data) {
        const sqtnsCopy = (sqtns || []).map(q => ({ ...q }));
        for (const qid of EQtns) {
            const s_qtnindex = sqtnsCopy.findIndex(i => i.QuestionId == qid);
            if (s_qtnindex >= 0) {
                const s_qtn = sqtnsCopy[s_qtnindex];
                sqtnsCopy[s_qtnindex] = { ...s_qtn, isDisabled: false };
            }
        }
        if (DQtns.length > 0) {
            const updated = await disableQtns(sqtnsCopy, DQtns, data);
            return updated != null ? updated : sqtnsCopy;
        }
        setSurveyQuestions(sqtnsCopy);
        bgSurveyQuestions(sqtnsCopy);
        BgUnsavedChanges(true);
        setrerenderdata((prev) => !prev);
        return sqtnsCopy;
    }

    // ✅ Function to get questions by SubCategoryId
    const getQuestionsBySubCategoryId = (data, subCategoryId) => {
        if (!Array.isArray(data) || data.length === 0) {
            console.warn("Data is missing or not an array.");
            return [];
        }

        return data.filter(item => item.SubCategoryId === subCategoryId);
    };

    const getQuestions = (data, subCategoryId) => {
        const subCat = data.find(item => item.SubCategoryId === subCategoryId);
        return subCat ? subCat.Questions : [];
    };

    const updateQEnableFromFilteredData = (subCategoryId, filteredData) => {
        const updatedSubCats = SurveySubCats.map(subCat => {
            if (subCat.SubCategoryId === subCategoryId) {
                const updatedQs = subCat.Questions.map(q => {
                    // Find matching question in filteredData
                    const match = filteredData.find(uq => uq.QuestionId === q.QuestionId);
                    // If found, update QEnable, else keep existing
                    return match ? { ...q, isDisabled: match.isDisabled } : q;
                });
                return {
                    ...subCat,
                    Questions: updatedQs,
                };
            }
            return subCat;
        });

        setSurveySubCats(updatedSubCats);
    };

    // Sync enable/disable state from flat question list to ALL subcategories (so EnableQuestion in other subcats works)
    const syncAllSubCatsFromFlatQuestions = (flatQuestions) => {
        if (!flatQuestions || flatQuestions.length === 0) return;
        const updatedSubCats = SurveySubCats.map(subCat => {
            const filteredData = getQuestionsBySubCategoryId(flatQuestions, subCat.SubCategoryId);
            const updatedQs = (subCat.Questions || []).map(q => {
                const match = filteredData.find(uq => uq.QuestionId === q.QuestionId);
                return match ? { ...q, isDisabled: match.isDisabled } : q;
            });
            return { ...subCat, Questions: updatedQs };
        });
        setSurveySubCats(updatedSubCats);
        SurveySubCatsRef.current = updatedSubCats;
    };

    async function onselectionChange(option, qtn) {
        let data = QuestionsData;
        let ans_obj_byQuestionId = qtn?.Answers?.find(i => i.AnswerId == option.value) || {};
        if (ans_obj_byQuestionId != null) {
            let ImageName1 = qtn?.QuestionId + '_ImageName1';
            let ImagePath1 = qtn?.QuestionId + '_ImagePath1';
            let ImageName2 = qtn?.QuestionId + '_ImageName2';
            let ImagePath2 = qtn?.QuestionId + '_ImagePath2';
            if (ans_obj_byQuestionId?.ImageAllow1 === 'false' || ans_obj_byQuestionId?.ImageAllow1 === false) {
                data[ImageName1] = "";
                data[ImagePath1] = ""
            }
            if (ans_obj_byQuestionId?.ImageAllow2 === 'false' || ans_obj_byQuestionId?.ImageAllow2 === false) {
                data[ImageName2] = "";
                data[ImagePath2] = "";
            }

            //console.log("temp--", ans_obj_byQuestionId?.ImageAllow1 + "\n" + JSON.stringify(data));
        }

        let id_key = qtn.QuestionId + '_AnswerId';
        let ans_key = qtn.QuestionId + '_Answer';
        data[id_key] = option.value;
        data[ans_key] = option.label;
        BgWindowData(data)
        let aq_ans = qtn.Answers != null ? qtn.Answers : [];
        let ans_obj = qtn?.Answers?.find(i => i.AnswerId == option.value) || {};
        let EQtns = ans_obj.EnableQuestion != null && ans_obj.EnableQuestion != '' ? ans_obj.EnableQuestion.replace(' ', '').split(',') : [];
        let DQtns = ans_obj.DisableQuestion != null && ans_obj.DisableQuestion != '' ? ans_obj.DisableQuestion.replace(' ', '').split(',') : [];
        //console.log('EQtns:', EQtns, DQtns);
        let sqtns = SurveyQuestions;
        let updatedSqtns = null;
        if (EQtns.length > 0) {
            updatedSqtns = await enableQtns(sqtns, EQtns, DQtns, data);
        }
        else if (DQtns.length > 0) {
            //console.log("option----", option, qtn);
            let qId = qtn?.QuestionId;
            if (qId != null && qId != undefined) {
                let img_1 = qId + '_ImageName1';
                let img_2 = qId + '_ImageName2';
                let img_key1 = qId + '_ImagePath1';
                let img_key2 = qId + '_ImagePath2';
                data[img_1] = "";
                data[img_2] = "";
                data[img_key1] = "";
                data[img_key2] = "";
            }

            updatedSqtns = await disableQtns(sqtns, DQtns, data);
        } else {
            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata(!rerenderdata);
        }
        setrerenderdata(!rerenderdata);
        BgUnsavedChanges(true)
        if (updatedSqtns != null) {
            syncAllSubCatsFromFlatQuestions(updatedSqtns);
        } else if (qtn?.SubCategoryId != null && qtn?.SubCategoryId != undefined) {
            let questionsForSubCat = sqtns;
            let filteredData = getQuestionsBySubCategoryId(questionsForSubCat, qtn?.SubCategoryId);
            updateQEnableFromFilteredData(qtn?.SubCategoryId, filteredData);
        }

        setTimeout(() => {
            //console.log("final_qtn", JSON.stringify(SurveySubCats));
            SurveySubCatsRef.current = SurveySubCats;
        }, 1000);
    }

    function setTextValue(value, qtn, type = '') {
        //console.log("type0000", type)
        if (value != '') {
            let isValid = validateNumber(value, type);
            //console.log("isValid====", isValid)
            if (!isValid) {
                return;
            }
        }

        let id_key = qtn.QuestionId + '_AnswerId';
        let ans_key = qtn.QuestionId + '_Answer';

        let obj = QuestionsData;
        if (qtn.QuestionType == 'Date') {
            let date_key = qtn.QuestionId + '_Date';
            let d = value != null ? new Date(value) : new Date();
            let mfdate = moment(d).format('DD/MM/YYYY');
            //showQtnDatePicker(qtn, false);
            obj[id_key] = 0;
            obj[ans_key] = mfdate;
            obj[date_key] = moment(d).format('MM/DD/YYYY');
        } else {
            //console.log("qtn.Quest------", qtn)
            if (qtn.QuestionType == 'Decimal' && (qtn.LengthValidation == "true" || qtn.LengthValidation || qtn.LengthValidation == 1)) {
                // if(qtn.MaxLength!="0" && qtn.MinLength!="0"){
                // }
                let valSplitLen = value.split(".")[1]?.length
                if (valSplitLen == undefined || valSplitLen < 2) {
                    obj[id_key] = 0;
                    obj[ans_key] = value;
                } else if (/^\d+\.\d{2}$/.test(value)) {
                    obj[id_key] = 0;
                    obj[ans_key] = Number(value).toFixed(2);
                }

            } else {
                obj[id_key] = 0;
                obj[ans_key] = value;
            }

        }
        console.log(value, obj);
        // setQuestionsData(obj);
        BgWindowData(obj)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function setRatingValue(data) {
        setRatingOrder(data);
    }


    async function setMultiSelectValue(selectedItems = [], qtn) {
        //console.log('setMultiSelectValue', selectedItems);
        let id_key = qtn.QuestionId + '_AnswerId';
        let ans_key = qtn.QuestionId + '_Answer';
        let multi_key = qtn.QuestionId + '_MultiOption';
        let obj = QuestionsData;
        obj[id_key] = 0;
        obj[multi_key] = selectedItems.join(',');
        let anss = [];
        selectedItems.map((itemValue) => {
            let ans = qtn.Answers.find(c1 => c1.AnswerId == itemValue);
            if (ans.Answer) { anss.push(ans.Answer) }
        });
        obj[ans_key] = anss.join(',');
        console.log('obj:', obj);
        // setQuestionsData(obj);
        BgWindowData(obj)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }


    function showQtnDatePicker(qtn, show = false) {
        let newqtnIndex = SurveyQuestions?.findIndex(q => q.QuestionId == qtn.QuestionId);
        console.log('showQtnDatePicker:', newqtnIndex,);
        if (newqtnIndex >= 0) {
            let sq = SurveyQuestions;
            let newqtn = sq[newqtnIndex];
            newqtn.showDatePicker = show;
            sq[newqtnIndex] = newqtn;
            console.log("sq----------", sq)
            setSurveyQuestions(sq);
            bgSurveyQuestions(sq)
            if (show === true) {
                setrerenderdata(prev => !prev);
            }
        }
    }




    function setShowQtnKey(qtn, key, show = false) {
        if (key != null && key != '') {
            let newqtnIndex = SurveyQuestions.findIndex(q => q.QuestionId == qtn.QuestionId);
            // console.log('setShowQtnKey:', newqtnIndex);
            if (newqtnIndex >= 0) {
                let sq = SurveyQuestions;
                let newqtn = sq[newqtnIndex];
                newqtn[key] = show;
                sq[newqtnIndex] = newqtn;
                setSurveyQuestions(sq);
                bgSurveyQuestions(sq)
                if (show == true) setrerenderdata(!rerenderdata);
            }
        }
    }

    function onRatingCancel() {
        setShowRating(false);

    }

    function onRatingSave() {
        setShowRating(false);

        let qtn = RatingQtn;
        let id_key = qtn.QuestionId + '_AnswerId';
        let ans_key = qtn.QuestionId + '_Answer';
        let rating_key = qtn.QuestionId + '_Rating';
        let ids = [], anss = [];
        RatingOrder.map((item, index) => {
            ids.push(item.AnswerId);
            anss.push(item.Answer);
        })
        let obj = QuestionsData;
        obj[rating_key] = ids.join(',');
        obj[id_key] = 0;
        obj[ans_key] = anss.join(',');

        console.log(obj);
        // setQuestionsData(obj);
        BgWindowData(obj)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onRecordCancel() {
        setShowRecorder(false);
    }

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

    function onRecordSave() {
        let isRecorderPlaying = VRS.RecorderPlayStatus != null && VRS.RecorderPlayStatus == true;
        let isPlayerPlaying = VRS.PlayerPlayStatus != null && VRS.PlayerPlayStatus == true;
        if (isRecorderPlaying) {
            notify(ST.Pleasestoprecordingfirst);
            return;
        }

        else if (isPlayerPlaying) {
            stopPlayer(VRS);
        }

        setShowRecorder(false);
        let qtn = RatingQtn;
        let id_key = qtn.QuestionId + '_AnswerId';
        let ans_key = qtn.QuestionId + '_Answer';
        let voiceClip_key = qtn.QuestionId + '_VoiceClip';

        let obj = QuestionsData;
        obj[ans_key] = RecFilePath.filename || '';
        obj[id_key] = 0;
        obj[voiceClip_key] = RecFilePath;
        // setQuestionsData(obj);
        BgWindowData(obj)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    const RippleAnimation = (value, minValue, maxValue, delay) =>
        Animated.loop(
            Animated.sequence([
                Animated.timing(value, {
                    toValue: maxValue,
                    duration: 1000,
                    delay: delay,
                    useNativeDriver: (Platform.OS == 'ios' ? false : true),
                }),
                Animated.timing(value, {
                    toValue: minValue,
                    duration: 1000,
                    delay: delay,
                    useNativeDriver: (Platform.OS == 'ios' ? false : true),
                }),
            ]),

        ).start();

    const startRecorder = React.useCallback(async (storeData1, qtn, ActiveSurvey1, vrStatus) => {
        try {
            console.log('startRecorder')
            if (audioRecorderPlayer != null) {
                if (vrStatus['RecorderPlayStatus'] == true) {
                    notify(ST.AlreadyRecording + '...')
                    return;
                }
                else if (vrStatus['PlayerPlayStatus'] == true) {
                    notify(ST.Pleasestopplayerfirst)
                    return;
                }

                stopPlayer(vrStatus);

                let picture_clickedd = new Date();
                let picture_clicked_date = moment(picture_clickedd).format('YYYYMMDD');
                let picture_clicked_time = moment(picture_clickedd).format('HHmmss');
                let commname = storeData1.StoreId + '_' + ActiveSurvey1.SurveyId + '_' + qtn.QuestionId + '_SurveyRecording_' + picture_clicked_date + '_' + picture_clicked_time;
                let filename = Platform.OS == 'ios' ? commname + '.m4a' : commname + '.mp3';

                const url = Platform.OS == 'ios' ? `file://${ImageFolderPath + currentMenu.ScreenName}/` + 'Recordings/' + filename : `${ImageFolderPath + currentMenu.ScreenName}/` + 'Recordings/' + filename;
                const url_dir = `${ImageFolderPath + currentMenu.ScreenName}/` + 'Recordings/';
                console.log('write file url:', url);
                RNFS.mkdir(url_dir).then((res) => {

                    RNFS.writeFile(url, '')
                        .then(async (success) => {
                            // if(success!=null){
                            const path = Platform.select({
                                ios: url,
                                android: url,
                            });

                            const result = await audioRecorderPlayer.startRecorder(path, AudioSet);
                            if (result != null && result != '') {
                                console.log('start recording now');
                                vrStatus['RecorderPlayStatus'] = true;
                                setVRS(vrStatus);
                                setRecFilePath({ 'path': url, 'filename': filename });
                                // animate
                                RippleAnimation(animatedRipple, 0, 1, 0);
                                RippleAnimation(animatedRipple2, 0, 1, 100);

                                audioRecorderPlayer.addRecordBackListener((e) => {
                                    let recordsec = e.currentPosition;
                                    let data = { 'recordSecs': recordsec, 'recordTime': audioRecorderPlayer.mmssss(Math.floor(recordsec)) };
                                    if (vrStatus['RecorderPlayStatus'] == true) {
                                        setRecorderTimer(data);
                                        // setHasUnsavedChanges(true);
                                        BgUnsavedChanges(true)
                                        setVoiceRecorderStatus(ST.RecordingPressmictostoprecording);
                                    }

                                    console.log('recordsec:', recordsec);
                                    if (recordsec >= 60 * 1000) {
                                        stopRecorder(vrStatus);
                                        notify(ST.Maximumrecordtimelimitreached, 'LONG');
                                    }
                                    return;
                                });
                            }
                            console.log('start recorder:', result);
                        })
                        .catch((err) => {
                            console.log('eerriur1', err.message);
                            notify(ST.Somethingwentwrong + ' ' + ST.Cannotopenfileforrecording);
                        });
                })
                    .catch((err) => {
                        console.log('eerriur2', err.message);
                        notify(ST.Somethingwentwrong + ' ' + ST.Cannotopenfileforrecording);
                    });

            }
        }
        catch (e) {
            console.log('error:', e);
        }

    }, []);






    const stopRecorder = React.useCallback(async (vrStatus) => {
        try {
            console.log('stopRecorder');
            if (audioRecorderPlayer != null) {

                animatedRipple.setValue(0);
                animatedRipple2.setValue(0.5);
                const uri = await audioRecorderPlayer.stopRecorder();
                audioRecorderPlayer.removeRecordBackListener();

                vrStatus['RecorderPlayStatus'] = false;
                vrStatus['PlayerPlayStatus'] = false;
                setPlayerTimer({});
                setVRS({ ...VRS, vrStatus });
                setVoiceRecorderStatus(ST.Pressmictostartrecordingvoice);
            }
        }
        catch (e) {
            console.log('error:', e);
        }

    }, []);

    const startPlayer = React.useCallback(async (url, vrStatus1, type = '0') => {
        try {
            let vrStatus = VRS;
            let qtn = RatingQtn;
            if (audioRecorderPlayer != null) {
                console.log('startPlayer1', url);
                if (vrStatus['PlayerPlayStatus'] == true) {
                    notify(ST.AlreadyPlaying + '...')
                    return;
                }
                else if (vrStatus['RecorderPlayStatus'] == true) {
                    notify(ST.Pleasestoprecordingfirst)
                    return;
                }
                else if (url == '' || url == null) {
                    notify(ST.Filenotfound)
                    return;
                }

                const result = await audioRecorderPlayer.startPlayer(url);
                if (result != null) {
                    vrStatus['PlayerPlayStatus'] = true;
                    setVRS(vrStatus);

                    audioRecorderPlayer.addPlayBackListener((e) => {
                        let playDuration = audioRecorderPlayer.mmssss(Math.floor(e.duration));
                        let vrs = VRS;
                        let data = { 'playerSecs': e.currentPosition, 'totalDuration': e.duration, 'playDuration': playDuration, 'playTime': audioRecorderPlayer.mmssss(Math.floor(e.currentPosition),) };
                        let data2 = { 'playerSecs': '0000', 'totalDuration': e.duration, 'playDuration': playDuration, 'playTime': "00:00:00" };
                        if (vrs['PlayerPlayStatus'] == true) {
                            setPlayerTimer(e.currentPosition < 0 ? data2 : data);
                        }
                        if (e.currentPosition < 0) {
                            return;
                        }
                        let wp = e.duration != null ? Math.floor((e.currentPosition / e.duration) * 100) : 0;
                        console.log('wp:', wp);
                        if (wp >= 100 || isNaN(wp)) {
                            stopPlayer(vrs);
                        }
                        else if (type == '1' && wp < 1) {
                            pausePlayer();
                        }
                        setProcessing(false);
                        return;
                    });
                }
                else {
                    setProcessing(false);
                }
            }
        }
        catch (e) {
            console.log('error:', e);
            setProcessing(false);
        }

    }, []);

    const resumePlayer = React.useCallback(async (url) => {
        console.log('resume player')
        let vrStatus = VRS;
        const res = await audioRecorderPlayer.resumePlayer();
        console.log('res:', res);
        if (res == 'No audio playing') {
            startPlayer(url, vrStatus);
        }
        vrStatus['PlayerPlayStatus'] = true;
        setVRS({ ...VRS, vrStatus });
    }, []);


    const pausePlayer = React.useCallback(() => {
        console.log('pause player')
        let vrStatus = VRS;
        audioRecorderPlayer.pausePlayer();
        vrStatus['PlayerPlayStatus'] = false;
        setVRS({ ...VRS, vrStatus });
    }, []);

    const stopPlayer = React.useCallback(async (vrStatus) => {
        try {
            console.log('stop player now');

            if (audioRecorderPlayer != null) {
                const uri = await audioRecorderPlayer.stopPlayer();
                audioRecorderPlayer.removePlayBackListener();
                vrStatus['PlayerPlayStatus'] = false;
                setVRS({ ...VRS, vrStatus });
            }
        }
        catch (e) {
            console.log('error:', e);
        }

    }, []);

    async function show_recorder(qtn) {
        let voiceClip_key = qtn.QuestionId + '_VoiceClip';
        let url = QuestionsData[voiceClip_key] ? QuestionsData[voiceClip_key].path : '';
        setRatingQtn(qtn);
        if ((RecorderTimer == null || Object.keys(RecorderTimer).length <= 0) && (playerTimer == null || Object.keys(playerTimer).length <= 0) && url != null && url != '') {
            setLoaderTitle(ST.Loading + '...');
            setProcessing(true);
            await startPlayer(url, VRS, '1');
        }
        setRecFilePath((QuestionsData[voiceClip_key] || {}));
        setShowRecorder(true);
    }


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


    function onSaveCancel() {
        setShowAlert(false);
    }

    function openImageRefView(QuestionRefImage, windowIndex = 0) {
        //console.log("indexxxx--", windowIndex)
        setZoomImageUrl(QuestionRefImage);
        setrefImageIndex(0);
        setShow_zoomImage(true);
    }

    async function saveData() {
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData + '...');
        setProcessing(true);
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
            await db.transaction(async function (txn) {

                let { MenuId } = currentMenu;
                let q = `DELETE FROM ${AppTables.SURVEY} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and MENU_ID='${MenuId}' and SURVEY_ID='${ActiveSurvey.SurveyId}' `;
                if (ShowCat == true) {
                    q += ` and CATEGORY_ID='${ActiveCategory.CategoryId}' `;
                }

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


                var values = '';
                let { SurveyId, SurveyName } = ActiveSurvey;
                for (var i = 0; i < SurveyQuestions.length; i++) {
                    values += values != '' ? ' , ' : '';
                    let qtn = SurveyQuestions[i];
                    let id_key = qtn.QuestionId + '_AnswerId';
                    let ans_key = qtn.QuestionId + '_Answer';
                    let multi_key = qtn.QuestionId + '_MultiOption';
                    let date_key = qtn.QuestionId + '_Date';
                    let img_key1 = qtn.QuestionId + '_ImagePath1';
                    let imgname_key1 = qtn.QuestionId + '_ImageName1';
                    let img_key2 = qtn.QuestionId + '_ImagePath2';
                    let imgname_key2 = qtn.QuestionId + '_ImageName2';
                    let rating_key = qtn.QuestionId + '_Rating';
                    let voiceClip_key = qtn.QuestionId + '_VoiceClip';

                    let { CategoryId, Category, SubCategory, SubCategoryId, DateRange, LengthValidation, MaxLength, MinLength, OTP, Question, QuestionId, QuestionImageAllow, QuestionType } = qtn;

                    let selansid = QuestionsData[id_key] || 0;
                    let selans = QuestionsData[ans_key] || '';
                    let imgName1 = QuestionsData[imgname_key1] || '';
                    let imgName2 = QuestionsData[imgname_key2] || '';
                    let multiops = QuestionsData[multi_key] || '';
                    let isQtnDisabled = qtn.isDisabled != null && qtn.isDisabled != '' ? qtn.isDisabled ? 1 : 0 : 0;
                    let allanss = qtn.Answers || {};
                    let ans_obj = allanss.find(i => i.AnswerId == selansid)
                    let imgallow1 = ans_obj != null && ans_obj['ImageAllow1'] != null ? ans_obj.ImageAllow1 : false;
                    let imgallow2 = ans_obj != null && ans_obj['ImageAllow2'] != null ? ans_obj.ImageAllow2 : false;
                    let f_imgalloq1 = (QuestionImageAllow == 'true' || QuestionImageAllow == 1) || (imgallow1 == 'true' || imgallow1 == 1)
                    let VerifyOTP = qtn?.VerifyOTP;
                    values += ` ('${StoreId}','${d2}','${SurveyId}','${MenuId}','${CategoryId}','${SubCategoryId}','${Question}','${QuestionId}','${QuestionType}','${selans}','${selansid}','${f_imgalloq1}','${(imgName1 || '')}','${imgallow2}','${(imgName2 || '')}','${multiops}','${isQtnDisabled}','${d2}', ${VerifyOTP}) `;
                }
                console.log("values------------", values)
                let add_data = `INSERT INTO ${AppTables.SURVEY} (STORE_ID,VISIT_DATE,SURVEY_ID,MENU_ID,CATEGORY_ID,SUB_CATEGORY_ID,QUESTION,QUESTION_ID,QUESTION_TYPE,ANSWER,ANSWER_ID,IMAGE_ALLOW1,IMAGE1,IMAGE_ALLOW2,IMAGE2,MULTI_OPTIONS_IDS,IS_DISABLED,ADDED_DATE , VerifyOTP) VALUES ${values} `;

                await txn.executeSql(add_data, [], async function (txn2, txnres) {
                    console.log('surveys added');
                    await clear_item('storeData');
                    BgUnsavedChanges(false);
                    // props.set_autoback({'AutoGoToPrev':true});
                    notify(ST.Surveyupdatedsuccessfully, 'SHORT');
                    setProcessing(false);
                    props.navigation.goBack();

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


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


    // send otp  

    const [showotpfeild, setShowOTPFeild] = useState(false);
    const [isSendOtpEnabled, setSendOtpEnabled] = useState(false);
    const [otp, setOtp] = useState('');

    const handleVerify = async (selansid, minlen) => {
        console.log(minlen, "selansid----------", selansid)
        if (!showotpfeild) {
            notify('Please click on Send OTP Button', 'SHORT');
            return false
        }
        else if (otp.length !== 6) {
            notify('Please enter 6-digit OTP', 'SHORT');
            return false
        } else if (selansid.length == minlen) {
            return await Verify_OTP(selansid);
        }

    };

    const Send_OTP = async (value) => {
        //console.log("OTP called-------Send", value);

        const phoneNumber = `${'91'}${value}`;

        let projectCode = await get_item('projectCode');
        const projectcode = JSON.parse(projectCode);

        //console.log("projectDetails----", projectCode)

        const url = "https://api1.parinaam.in/api/generic/CheckUserAndSendOTP";
        const data = { mobileno: phoneNumber, projectcode: projectcode };

        console.log(url, data);

        await getmobileverifyotp(url, data)
            .then(async (res) => {
                console.log(res, "response...");

                if (!res[0]?.OTP) {
                    notify(res[0]?.Messages, "SHORT"); // Invalid phone
                } else if (res[0]?.OTP) {
                    notify(res[0]?.Messages, "SHORT");
                    setShowOTPFeild(true);
                    // return true;
                } else if (res.networkErr && res.error) {
                    notify("Please connect to internet - " + res.error, "SHORT");
                } else if (!res.false && res.error) {
                    notify(res.error, "SHORT");
                }
            })
            .catch((err) => {
                //console.log("onPage OTP send error1", err);
            });
    };


    const Verify_OTP = async (value) => {
        //console.log("OTP called-------verify otpppppp", value.length);

        const phoneNumber = `${'91'}${value}`;

        const url = "https://api1.parinaam.in/api/generic/otpauthentication";
        const data = {
            otp: otp,
            mobileno: phoneNumber
        };

        console.log(url, data);

        return await verifymobileotp(url, data)
            .then(async (res) => {
                console.log(res, "response..vwrify.");

                if (res[0]?.Message == 'OTP is matched') {
                    notify(res[0]?.Message, "SHORT");
                    setVerifiedOTP(true);
                    return true;
                    // setShowAlert(true); // show save alert . popup
                } else if (res[0]?.Message != 'OTP is matched') {
                    notify(res[0]?.Message, "SHORT");
                } else if (res.networkErr && res.error) {
                    notify("Please connect to internet - " + res.error, "SHORT");
                } else if (!res.false && res.error) {
                    notify(res.error, "SHORT");
                }
                return false
            })
            .catch((err) => {
                //console.log("onPage OTP send error1", err);
                return false
            });
    };


    async function validate() {
        function showError(obj, isErr) {
            setErrorField(obj);
            setError(isErr);
        }
        let Image1MandIndex = KPIFields.findIndex(i => i.KPIFieldName == 'Image1Mandatory');
        let Image1MandObj = Image1MandIndex >= 0 ? KPIFields[Image1MandIndex] : {};
        let isImage1Mand = Image1MandIndex >= 0 ? Image1MandObj['KPIFieldEnable'] : true;
        let Image2MandIndex = KPIFields.findIndex(i => i.KPIFieldName == 'Image2Mandatory');
        let Image2MandObj = Image2MandIndex >= 0 ? KPIFields[Image2MandIndex] : {};
        let isImage2Mand = Image2MandIndex >= 0 ? Image2MandObj['KPIFieldEnable'] : false;
        var isvalid = true;
        const QD = QuestionsData;
        // console.log("SurveyQuestions",JSON.stringify(QuestionsData));
        for (var i = 0; i < SurveyQuestions.length; i++) {
            let qtn = SurveyQuestions[i];
            let selansid = '', selanswer = '', selimg = '', showImageTag = false, showImageTag2 = false, isImageMandateforAns = false, isImageMandate2forAns = false, imgChild = false, imgChild2 = false;
            let id_key = qtn.QuestionId + '_AnswerId';
            let ans_key = qtn.QuestionId + '_Answer';
            let multi_key = qtn.QuestionId + '_MultiOption';
            let date_key = qtn.QuestionId + '_Date';
            let img_key = qtn.QuestionId + '_ImagePath1';
            let imgname_key = qtn.QuestionId + '_ImageName1';
            let img_key2 = qtn.QuestionId + '_ImagePath2';
            let imgname_key2 = qtn.QuestionId + '_ImageName2';
            let rating_key = qtn.QuestionId + '_Rating';
            let voiceClip_key = qtn.QuestionId + '_VoiceClip';
            let list_mcdata = [];

            let isDisabled = qtn.isDisabled != null ? qtn.isDisabled : false
            let LengthValidation = qtn.LengthValidation == 'true' || qtn.LengthValidation == 1 ? true : false;
            let isLengthValidationReq = false;
            let minL = qtn.MinLength != null && qtn.MinLength != '' ? qtn.MinLength : 0;
            let maxL = qtn.MaxLength != null && qtn.MaxLength != '' ? qtn.MaxLength : 10;
            let enableOTP = qtn.OTP != null && qtn.OTP != '' ? qtn.OTP : false;
            let verify_OTP = qtn.VerifyOTP;
            let ansVal = QD[ans_key];
            //console.log("ansVal", ansVal)
            let errorobj = { 'EF_Qtn': qtn };
            // LengthValidation is required for number type input only
            if (qtn.QuestionType == 'Number') {
                isLengthValidationReq = LengthValidation;
            }

            if (!isDisabled || isDisabled != 1) {
                let isImgAllowed = ((qtn.QuestionImageAllow == true || qtn.QuestionImageAllow == 'true' || qtn.QuestionImageAllow == 1) || (qtn.QuestionType == "Image"));
                let isImg1mandatory = (qtn.Image1Mandatory == "true") || (qtn.Image1Mandatory == true) || (qtn.Image1Mandatory == 1) || (qtn.QuestionImageMandatory == "true") || (qtn.QuestionImageMandatory == true) || (qtn.QuestionImageMandatory == 1)
                let isImg2mandatory = (qtn?.Image2Mandatory == "true" || qtn?.Image2Mandatory == '1' || qtn?.Image2Mandatory == 1);
                let isQuestionImageMandatory = qtn.QuestionType == "Image" ? (qtn?.QuestionImageMandatory == "true" || qtn?.QuestionImageMandatory == true || qtn?.QuestionImageMandatory == 1) : (qtn?.QuestionImageMandatory == "true" || qtn?.QuestionImageMandatory == true || qtn?.QuestionImageMandatory == 1) ? true : false;
                let checkForAnsKey = (qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Number' || qtn.QuestionType == 'Text' || qtn.QuestionType == 'OnlyText' || qtn.QuestionType == 'Date' || qtn.QuestionType == 'Rating');

                console.log("qtn", qtn)
                if (qtn.QuestionType == 'Single choice list') {
                    selansid = QD[id_key];
                } else if (qtn.QuestionType == 'Multi choice list') {
                    selansid = QD[multi_key] != null && QD[multi_key] != '' ? QD[multi_key].split(',') : [];
                }
                console.log("testing2-----", selansid)
                if (qtn.QuestionType == 'Multi choice list' && selansid.length <= 0 || qtn.QuestionType == 'Single choice list' && (selansid === undefined || selansid === '' || selansid == 0 || selansid == '0')) {
                    errorobj["EF_Input"] = 'Input';
                    showError(errorobj, true);
                    isvalid = false;
                    notify(ST.Pleaseselectoptionsfortherequiredfield, 'SHORT');
                    break;
                } else if (checkForAnsKey && (Object.keys(QD).indexOf(ans_key) < 0 || (Object.keys(QD).indexOf(ans_key) >= 0 && QD[ans_key] === ''))) {
                    errorobj["EF_Input"] = 'Input';
                    showError(errorobj, true);
                    isvalid = false;
                    let msg = (qtn.QuestionType == 'Date' ? ST.Pleasepickadate : (qtn.QuestionType == 'Rating' ? ST.Pleaseselectrating : ST.Pleasefillalldetails));
                    notify(msg, 'SHORT');
                    break;
                } else if (qtn.QuestionType == 'Audio' && (Object.keys(QD).indexOf(voiceClip_key) < 0 || (Object.keys(QD).indexOf(voiceClip_key) >= 0 && (QD[voiceClip_key] == null || QD[voiceClip_key].filename == null || QD[voiceClip_key].filename == '')))) {
                    errorobj["EF_Input"] = 'Input';
                    showError(errorobj, true);
                    isvalid = false;
                    notify(ST.Pleaserecordaudioclipfortherequiredfield, 'SHORT');
                    break;
                }
                else if (isQuestionImageMandatory && (QD[img_key] == undefined || QD[img_key] === '')) {
                    errorobj["EF_Input"] = 'Input';
                    showError(errorobj, true);
                    isvalid = false;
                    notify(`Please capture image ${ST.In} ${qtn.Question}`, 'SHORT');
                    break;
                }
                else if (isImgAllowed &&
                    (isImg1mandatory || imgChild || isImg2mandatory) &&
                    showImageTag &&
                    (
                        !QD.hasOwnProperty(img_key) ||
                        QD[img_key] === ''
                    )) {
                    errorobj["EF_Image"] = 'Image';
                    showError(errorobj, true);
                    isvalid = false;
                    notify(ST.Pleaseaddimages, 'SHORT');
                    break;
                } else if (isLengthValidationReq && ansVal.length < minL) {
                    errorobj["EF_Input"] = 'Input';
                    showError(errorobj, true);
                    isvalid = false;
                    notify("Minimum digits allowed is " + minL + " in " + qtn.Question, 'SHORT');
                    break;
                } else if (isLengthValidationReq && ansVal.length > maxL) {
                    errorobj["EF_Input"] = 'Input';
                    showError(errorobj, true);
                    isvalid = false;
                    notify("Maximum digits allowed is " + maxL + " in " + qtn.Question, 'SHORT');
                    break;
                } else {
                    console.log('no condition found');
                }

                if ((qtn.QuestionType == 'Single choice list' || qtn.QuestionType == 'Multi choice list')) {
                    if (qtn.Answers && qtn.Answers.length > 0) {
                        for (var j = 0; j < qtn.Answers.length; j++) {
                            let ansss = qtn.Answers[j];
                            let isandImgAl = (ansss.ImageAllow1 == true || ansss.ImageAllow1 == 'true' || ansss.ImageAllow1 == 1);
                            if (qtn.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                                showImageTag = true;
                                isImageMandateforAns = qtn.Image1Mandatory;
                                imgChild = ansss.Image1Mandatory
                            } else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId.toString()) >= 0)) {
                                showImageTag = true;
                                isImageMandateforAns = qtn.Image1Mandatory;
                                imgChild = ansss.Image1Mandatory
                            }
                            let isandImgAl2 = (ansss.ImageAllow2 == true || ansss.ImageAllow2 == 'true' || ansss.ImageAllow2 == 1);
                            if (qtn.QuestionType == 'Single choice list' && (isandImgAl2 && ansss.AnswerId == selansid)) {
                                showImageTag2 = true;
                                isImageMandate2forAns = qtn.Image2Mandatory;
                                imgChild2 = ansss.Image2Mandatory
                            }
                            else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId.toString()) >= 0)) {
                                showImageTag2 = true;
                                isImageMandate2forAns = qtn.Image2Mandatory;
                                imgChild2 = ansss.Image2Mandatory
                            }
                        }
                    }
                }

                console.log("imgChild--", imgChild)
                if ((isImg1mandatory || imgChild) && showImageTag && (Object.keys(QD).indexOf(img_key) < 0 || (Object.keys(QD).indexOf(img_key) >= 0 && QD[img_key] === ''))) {
                    errorobj["EF_Image"] = 'Image';
                    showError(errorobj, true);
                    isvalid = false;
                    notify(ST.Pleaseaddimages, 'SHORT');
                    break;
                }

                if ((isImg1mandatory || imgChild2) && showImageTag2 && (Object.keys(QD).indexOf(img_key2) < 0 || (Object.keys(QD).indexOf(img_key2) >= 0 && QD[img_key2] === ''))) {
                    errorobj["EF_Image"] = 'Image';
                    showError(errorobj, true);
                    isvalid = false;
                    notify(ST.Pleaseaddimages, 'SHORT');
                    break;
                }

                if ((enableOTP == "true" || enableOTP == true || enableOTP == 1) && verify_OTP != 1) {
                    let minlen = (qtn.LengthValidation === true || qtn.LengthValidation == 1 || qtn.LengthValidation === 'true')
                        && qtn.MinLength != null
                        && qtn.MinLength !== ''
                        ? qtn.MinLength
                        : undefined;
                    selansid = QD[ans_key];
                    let resultOTp = await handleVerify(selansid, minlen);
                    qtn.VerifyOTP = resultOTp ? 1 : 0
                    isvalid = false;
                    break;
                }

            }
        }

        return isvalid;
    }

    function render_Picker(label_key, value_key, onChange = () => { }, selected_data = {}) {
        var data = [];
        let qtn = selected_data.qtn || {};
        let EStyle_Qtn_Input = selected_data.EStyle_Qtn_Input || {};
        let isQtnDisabled = qtn.isDisabled != null && qtn.isDisabled != '' ? qtn.isDisabled : false;
        let allAnswers = qtn.Answers || [];

        allAnswers.map((item, index) => {
            let obj = { key: index, label: item[label_key], value: item[value_key] };
            if (selected_data.value == item[label_key])
                obj['component'] = <View style={customStyle.addvis_selectedOpStyle}><Text style={customStyle.addvis_selectedOpTextStyle}>{item[label_key]}</Text></View>;
            data.push(obj);
        });

        return (
            <ModalSelector
                data={data}

                touchableActiveOpacity={0.8}

                style={customStyle.addVisPickerStyle}
                onChange={(option) => { onChange(option, qtn) }}
                overlayStyle={customStyle.addVisPickerOverlay}
                cancelContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
                optionStyle={customStyle.addvis_opStyle}
                optionTextStyle={customStyle.addvis_opTextStyle}
                optionContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
                selectedKey={'1'}
                disabled={isQtnDisabled}
                cancelText={ST.Cancel}
            >
                <Text style={[customStyle.addVisPicker_InputStyle,
                (isQtnDisabled ? customStyle.addVisPicker_Dis_InputStyle : {}),
                    EStyle_Qtn_Input]}>{(selected_data.value != null && selected_data.value != '' ?
                        selected_data.value : '-select-')}</Text>
            </ModalSelector>
        )
    }

    // function renderDatePicker(qtn) {
    //     let qtnn = qtn;
    //     let DateRange = qtn.DateRange;
    //     let maxDate = moment().add(10, 'years').format('MM/DD/YYYY');
    //     let minDate = moment().subtract(10, 'years').format('MM/DD/YYYY');

    //     const currentDate = new Date();
    //     const maxDateIOS = currentDate;
    //     const minDateIOS = new Date();
    //     minDateIOS.setFullYear(minDateIOS.getFullYear() - 10);

    //     if (DateRange == 'RFD') {
    //         maxDate = moment().format('MM/DD/YYYY');
    //     }
    //     else if (DateRange == 'RPD') {
    //         minDate = moment().format('MM/DD/YYYY');
    //     }

    //     return (
    //         <DateTimePicker
    //             testID="dateTimePicker"
    //             value={Platform.OS === 'ios' ? currentDate : (dateValue != null && dateValue != '' ? new Date(dateValue) : new Date())}
    //             mode={'date'}
    //             display="default"
    //             onChange={(event, selectedDate) => { setTextValue(selectedDate, qtnn) }}
    //             maximumDate={Platform.OS === 'ios' ? new Date(maxDateIOS) : new Date(maxDate)}
    //             minimumDate={Platform.OS === 'ios' ? new Date(minDateIOS) : new Date(minDate)}
    //         />
    //     );
    // }
    function renderDatePicker(qtn) {
        let qtnn = qtn;
        let DateRange = qtn.DateRange;
        let maxDate = moment().add(10, 'years').format('MM/DD/YYYY');
        let minDate = moment().subtract(10, 'years').format('MM/DD/YYYY');

        const currentDate = new Date();
        const maxDateIOS = currentDate;
        const minDateIOS = new Date();
        minDateIOS.setFullYear(minDateIOS.getFullYear() - 10);

        if (DateRange == 'RFD') {
            maxDate = moment().format('MM/DD/YYYY');
        }
        else if (DateRange == 'RPD') {
            minDate = moment().format('MM/DD/YYYY');
        }

        const today = new Date();
        const oneMonthAgo = new Date();
        oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
        console.log("ererre", qtn)

        return (
            <DateTimePicker
                testID="dateTimePicker"
                value={Platform.OS === 'ios' ? currentDate : today}
                mode={'date'}
                display="default"
                // onChange={(event, selectedDate) => { setTextValue(selectedDate, qtnn) }}
                onChange={(event, selectedDate) => {
                    if (event.type === 'dismissed' || event.type === 'cancel') {
                        // ❌ Cancel pressed
                        setShowDatePickerId({});  // hide picker
                        return;
                    }

                    if (event.type === 'set' || event.type === 'ok') {
                        // ✅ OK pressed
                        setShowDatePickerId({});  // hide picker
                        setTextValue(selectedDate, qtnn);
                    }
                }}
                maximumDate={Platform.OS === 'ios' ? new Date(maxDateIOS) : today}
                minimumDate={Platform.OS === 'ios' ? new Date(minDateIOS) : oneMonthAgo}
            />
        );
    }

    function renderItem({ item, drag, isActive }) {
        return (
            <ScaleDecorator>
                <TouchableOpacity

                    onLongPress={drag}
                    disabled={isActive}
                    style={[customStyle.RModal_listItem, { backgroundColor: isActive ? PageTheme.$primary_color : PageTheme.$secondary_color_light },]}
                >
                    <Text style={[customStyle.RModal_listItemText, (isActive ? { color: PageTheme.$accent_color } : {})]}>{item.Answer}</Text>
                </TouchableOpacity>
            </ScaleDecorator>
        );
    };

    function renderRatingView() {
        let qtn = RatingQtn;
        let Answers = qtn.Answers;
        let id_key = qtn.QuestionId + '_AnswerId';
        let ans_key = qtn.QuestionId + '_Answer';
        let rating_key = qtn.QuestionId + '_Rating';

        let newarr = RatingOrder;
        if (RatingOrder.length <= 0) {
            newarr = Answers;
        }

        return (
            <View style={customStyle.RatingModal}>
                <View style={customStyle.RatingModalCon}>
                    <Text style={customStyle.VRModalHeding}>{ST.DragItemsInOrder}</Text>
                    <Text style={customStyle.VRSubHeding}>{ST.Pressandholdtodrag}</Text>
                    <DraggableFlatList
                        data={newarr}
                        style={customStyle.RModal_list}
                        contentContainerStyle={customStyle.RModal_listInner}
                        onDragEnd={({ data }) => { setRatingValue(data) }}
                        keyExtractor={(item) => item.AnswerId}
                        renderItem={renderItem}
                    />
                    <View style={customStyle.RModal_Btns}>
                        <TouchableOpacity style={customStyle.RModal_BtnCancel} onPress={() => { onRatingCancel() }}>
                            <Text style={customStyle.RModal_BtnTextCancel}>{ST.Cancel}</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={() => { onRatingSave() }}>
                            <Text style={customStyle.RModal_BtnTextsave}>{ST.Save}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    }

    function renderRecorderView() {

        let qtn = RatingQtn;
        let isRecorderPlaying = VRS.RecorderPlayStatus != null && VRS.RecorderPlayStatus == true;
        let isPlayerPlaying = VRS.PlayerPlayStatus != null && VRS.PlayerPlayStatus == true;
        const scale = animatedRipple.interpolate({
            inputRange: [0, 1],
            outputRange: [1, 1.3],
        });

        const borderColor = animatedRipple.interpolate({
            inputRange: [0, 1],
            outputRange: ['#f5acb4c2', '#fce6e9e3'],
        });

        const scale2 = animatedRipple2.interpolate({
            inputRange: [0, 1],
            outputRange: [1, 1.5],
        });

        const borderColor2 = animatedRipple2.interpolate({
            inputRange: [0, 1],
            outputRange: ['#f5acb4c2', '#fce6e9e3'],
        });

        let totalDuration = RecorderTimer.recordSecs != null ? RecorderTimer.recordSecs : playerTimer.totalDuration;
        let wp = totalDuration != null ? Math.floor((playerTimer.playerSecs / totalDuration) * 100) : 0;
        let width1 = wp <= 100 ? (wp > 0 ? wp + '%' : '0%') : '100%';
        if (isNaN(wp)) width1 = '0%';

        return (
            <View style={customStyle.RatingModal}>
                {rerenderView == rerenderView &&
                    <View style={customStyle.RatingModalCon}>
                        <Text style={customStyle.VRModalHeding}>{ST.RecordVoiceClip}</Text>
                        <Text style={customStyle.VRSubHeding2}>{ST.Youcanrecordmaxfor60secs}</Text>
                        <Text style={customStyle.VRSubHeding}>{VoiceRecorderStatus}</Text>

                        <View style={customStyle.VoiceRecorder}>
                            <View style={customStyle.VoiceRecorderMic}>
                                <Animated.View style={[customStyle.VRMicBgRipple2, {
                                    transform: [
                                        { scale: scale2 },
                                    ],
                                    borderColor: ('#fce6e9e3'),
                                }]}></Animated.View>
                                <Animated.View style={[customStyle.VRMicBgRipple1, {
                                    transform: [
                                        { scale: scale },
                                    ],
                                    borderColor: ('#f5acb4c2'),
                                }]}></Animated.View>
                                <TouchableOpacity activeOpacity={1} style={customStyle.VoiceRecorderMicBtn} onPress={() => { startRecorder(storeData, qtn, ActiveSurvey, VRS); }}>
                                    <FontAwesome size={30} color={PageTheme.$accent_color} name="microphone" />
                                </TouchableOpacity>
                                {isRecorderPlaying &&
                                    <TouchableOpacity activeOpacity={1} style={customStyle.VoiceRecorderStopBtn} onPress={() => { stopRecorder(VRS); }}>
                                        <FontAwesome5 size={30} color={PageTheme.$accent_color} name="microphone-alt" />
                                    </TouchableOpacity>
                                }

                            </View>
                            <View style={customStyle.VoiceRecordedView}>
                                <Text style={customStyle.VoiceRecorderTimer}>{RecorderTimer.recordTime}</Text>
                                {
                                    (!isRecorderPlaying && RecFilePath.filename != null && RecFilePath.filename != '') &&
                                    <View style={customStyle.VRPlayBack}>
                                        <View style={customStyle.VRPlayBackBarView}>
                                            <View style={customStyle.VRPlayBackBar}>
                                                <View style={customStyle.VRPlayBackBarBg}></View>
                                                <View style={[customStyle.VRPlayBackBarFilled, { width: width1 }]}></View>
                                            </View>
                                            <Text style={customStyle.VRPlayBackTimer}>{`${(playerTimer.playTime || '00:00:00')} / ${playerTimer.playDuration || RecorderTimer.recordTime}`}</Text>
                                        </View>

                                        <View style={customStyle.VRPlayBackControls}>
                                            <TouchableOpacity activeOpacity={1} style={customStyle.VRPB_Play} onPress={() => { let url = (Platform.OS == 'ios' ? 'file://' : '') + `${ImageFolderPath + currentMenu.ScreenName}/` + 'Recordings/' + RecFilePath.filename; (wp < 100 && wp > 0) ? resumePlayer(url) : startPlayer(url, VRS); }}>
                                                <Entypo size={24} color={PageTheme.$accent_color} name="controller-play" />
                                            </TouchableOpacity>
                                            {isPlayerPlaying && <TouchableOpacity activeOpacity={1} style={customStyle.VRPB_Pause} onPress={() => { wp < 100 ? pausePlayer() : stopPlayer(VRS); }}>
                                                <Entypo size={24} color={PageTheme.$accent_color} name="controller-paus" />
                                            </TouchableOpacity>}
                                        </View>
                                    </View>
                                }
                            </View>
                        </View>
                        <View style={customStyle.RModal_Btns}>
                            <TouchableOpacity style={customStyle.RModal_BtnCancel} onPress={() => { onRecordCancel() }}>
                                <Text style={customStyle.RModal_BtnTextCancel}>{ST.Cancel}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={() => { onRecordSave() }}>
                                <Text style={customStyle.RModal_BtnTextsave}>{ST.Save}</Text>
                            </TouchableOpacity>
                        </View>
                    </View>}
            </View>
        )
    }

    function _renderSurveyQtns(subcat) {
        const SurveyQuestions = subcat?.Questions;
        // console.log("FlatList Rendering:", JSON.stringify(SurveyQuestions));
        return (
            <View style={customStyle.SVn_GroupViewList}>
                {
                    SurveyQuestions != null && SurveyQuestions != undefined && SurveyQuestions?.length > 0 &&
                    SurveyQuestions?.map((item, index) => {
                        // for debugging
                        let qtn = item;
                        let selansid = '', selanswer = '', selimg = '', selimg2 = '', showImageTag = false, showImageTag2 = false, isImageMandateforAns = false, isImageMandate2forAns = false;
                        let id_key = qtn.QuestionId + '_AnswerId';
                        let ans_key = qtn.QuestionId + '_Answer';
                        let multi_key = qtn.QuestionId + '_MultiOption';
                        let date_key = qtn.QuestionId + '_Date';
                        let img_key = qtn.QuestionId + '_ImagePath1';
                        let imgname_key = qtn.QuestionId + '_ImageName1';
                        let img_key2 = qtn.QuestionId + '_ImagePath2';
                        let imgname_key2 = qtn.QuestionId + '_ImageName2';
                        let rating_key = qtn.QuestionId + '_Rating';
                        let voiceClip_key = qtn.QuestionId + '_VoiceClip';
                        let list_mcdata = [];
                        let maxlen = (qtn.LengthValidation == true || qtn.LengthValidation == 'true') && qtn.MaxLength != null && qtn.MaxLength != '' ? qtn.MaxLength : undefined;
                        let minlen = (qtn.LengthValidation == true || qtn.LengthValidation == 'true') && qtn.MinLength != null && qtn.MinLength != '' ? qtn.MinLength : undefined;

                        if (qtn.QuestionType == 'Single choice list') {
                            selansid = QuestionsData[id_key] != null ? QuestionsData[id_key] : '';
                            selanswer = QuestionsData[ans_key] != null ? QuestionsData[ans_key] : '';
                        }
                        else if (qtn.QuestionType == 'Multi choice list') {

                            if (qtn.Answers != null) {
                                console.log('qtn.Answers:', qtn.Answers.length);
                                for (var i = 0; i < qtn.Answers.length; i++) {
                                    let obj = { 'AnswerId': parseInt(qtn.Answers[i].AnswerId), 'Answer': qtn.Answers[i].Answer };
                                    list_mcdata.push(obj);
                                }
                            }
                            selansid = QuestionsData[multi_key] != null && QuestionsData[multi_key] != '' ? QuestionsData[multi_key].split(',') : [];
                            if (selansid != null && selansid.length > 0) {
                                let arr = [];
                                for (var i = 0; i < selansid.length; i++) {
                                    arr.push(parseInt(selansid[i]));
                                }
                                selansid = arr;
                            }
                        }
                        else if (qtn.QuestionType == 'Number' || qtn.QuestionType == 'Text' || qtn.QuestionType == 'OnlyText' || qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Date') {
                            selansid = QuestionsData[ans_key];
                            selanswer = (qtn.QuestionType == 'Date') ? (QuestionsData[date_key] || moment().format('MM/DD/YYYY')) : '';
                            showImageTag = (qtn.QuestionImageAllow == true || qtn.QuestionImageAllow == 'true' || qtn.QuestionImageAllow == 1);
                            showImageTag2 = false;
                        } else if (qtn.QuestionType == 'Image') {
                            selansid = QuestionsData[id_key] != null ? QuestionsData[id_key] : '';
                            selanswer = QuestionsData[ans_key] != null ? QuestionsData[ans_key] : ''; // this is the image file name
                            {/* filePath=`${ImageFolderPath+currentMenu.ScreenName}/${selanswer}`; */ }
                            showImageTag = true;
                        }
                        else if (qtn.QuestionType == 'Rating') {
                            selanswer = QuestionsData[ans_key] ? QuestionsData[ans_key] : '';
                        }
                        else if (qtn.QuestionType == 'Audio') {
                            selansid = QuestionsData[ans_key] ? QuestionsData[ans_key] : '';
                            selanswer = QuestionsData[voiceClip_key] ? (QuestionsData[voiceClip_key].filename || '') : '';
                        }

                        if ((qtn.QuestionType == 'Single choice list' || qtn.QuestionType == 'Multi choice list')) {
                            if (qtn.Answers && qtn.Answers.length > 0) {
                                for (var i = 0; i < qtn.Answers.length; i++) {
                                    let ansss = qtn.Answers[i];

                                    let isandImgAl = (ansss.ImageAllow1 == true || ansss.ImageAllow1 == 'true' || ansss.ImageAllow1 == 1);
                                    let isandImgAl2 = (ansss.ImageAllow2 == true || ansss.ImageAllow2 == 'true' || ansss.ImageAllow2 == 1);
                                    let isImage1Mand = (ansss.Image1Mandatory == true || ansss.Image1Mandatory == 'true' || ansss.Image1Mandatory == 1);
                                    let isImage2Mand = (ansss.Image2Mandatory == true || ansss.Image2Mandatory == 'true' || ansss.Image2Mandatory == 1);

                                    if (qtn.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                                        showImageTag = true;
                                        if (isImage1Mand) {
                                            isImageMandateforAns = true;
                                        }
                                    }
                                    else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId) >= 0)) {
                                        showImageTag = true;
                                        if (isImage1Mand) {
                                            isImageMandateforAns = true;
                                        }
                                    }

                                    if (qtn.QuestionType == 'Single choice list' && (isandImgAl2 && ansss.AnswerId == selansid)) {
                                        showImageTag2 = true;
                                        if (isImage2Mand) {
                                            isImageMandate2forAns = true;
                                        }
                                    }
                                    else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl2 && selansid.indexOf(ansss.AnswerId) >= 0)) {
                                        showImageTag2 = true;
                                        if (isImage2Mand) {
                                            isImageMandate2forAns = true;
                                        }
                                    }
                                }
                            }
                        }

                        if (showImageTag) {
                            selimg = QuestionsData[img_key] != null && QuestionsData[img_key] != '' ? 'file://' + QuestionsData[img_key] : '';
                        }

                        if (showImageTag2) {
                            selimg2 = QuestionsData[img_key2] != null && QuestionsData[img_key2] != '' ? 'file://' + QuestionsData[img_key2] : '';
                        }

                        let isDisabled = qtn.isDisabled != null ? qtn.isDisabled : false

                        // console.log("isDisabled---", isDisabled)

                        let rs = qtn?.CalFormula || "";

                        Object.keys(QuestionsData).forEach((item) => {
                            const regex = new RegExp(item, 'g');
                            rs = rs.replace(regex, QuestionsData[item]);
                        });

                        if (qtn.QuestionType == "Calculate") {
                            try {
                                let selansidVal = /_Anser/.test(rs) ? selansid : eval(rs)
                                selansidVal = typeof (selansidVal) == "number" ? selansidVal.toFixed(2) : selansidVal;
                                selansidVal = String(selansidVal)
                                selansid = /_Anser/.test(rs) ? selansid : String(eval(selansidVal))

                                if (QuestionsData[ans_key] != selansid) {
                                    setQuestionsData((prev) => ({
                                        ...prev,
                                        [id_key]: 0,
                                        [ans_key]: selansid,
                                    }));
                                    setrerenderdata(!rerenderdata);
                                }
                            } catch (e) {
                                //console.log("selansid------e", e)
                                selansid = /_Anser/.test(selansid) ? "" : selansid
                            }
                        }

                        // Error Field highlight styles
                        let EF_Qtn = errorfield.EF_Qtn != null ? errorfield.EF_Qtn : {};
                        let show_errorhere = error == true && EF_Qtn.QuestionId == qtn.QuestionId;

                        // this will show error field in red (if window is present and exist reason is enabled and not filled ) or (if window is not present and Not exist reason is enabled and not filled ) 
                        let EF_Input = errorfield.EF_Input || '';
                        let EF_Image = errorfield.EF_Image || '';
                        let EStyle_Qtn_Input = show_errorhere && EF_Input == 'Input' ? customStyle.stk_inptSTyle_error : {};
                        let EStyle_Qtn_MultiChoice = show_errorhere && EF_Input == 'Input' ? customStyle.stk_MultiSSTyle_error : {};
                        let EStyle_Qtn_Image = show_errorhere && EF_Image == 'Image' ? customStyle.stk_inptSTyle_error : {};
                        let Image1Mandatory = (qtn.Image1Mandatory == "true") || (qtn.Image1Mandatory == true) || (qtn.QuestionImageMandatory == "true") || (qtn.QuestionImageMandatory == true)
                        let Image2Mandatory = (qtn.Image2Mandatory == "true") || (qtn.Image2Mandatory == true)

                        let OTPVerify = qtn.OTP == 'true' || qtn.OTP == 1 ? true : false;

                        if (isDisabled == true || isDisabled == 'true') {
                            return (
                                <View></View>
                            )
                        } else {
                            return (
                                <>
                                    {index == 0 && (
                                        <LinearGradient colors={[PageTheme.$bg_color, PageTheme.$primary_color, PageTheme.$bg_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.SVn_GroupView_hdr}>
                                            <Text style={customStyle.SVn_GroupView_hdrText}>{subcat.SubCategory}</Text>
                                        </LinearGradient>
                                    )}
                                    <View style={[customStyle.sform_group2,]} key={index}>
                                        <Text style={[customStyle.sform_label3]}>{qtn.Question}</Text>
                                        {/* {//console.log("chekqtnn:", qtn.Question, "-----", qtn)} */}
                                        {qtn.QuestionRefImage != null && qtn.QuestionRefImage != "" &&
                                            <TouchableOpacity style={customStyle.WItem_RefImgBtn} onPress={() => { openImageRefView(qtn.QuestionRefImage, index) }}>
                                                <Entypo name='image-inverted' size={24} color="black" />
                                            </TouchableOpacity>
                                        }
                                        {qtn.QuestionType == 'Single choice list' && qtn.Answers &&
                                            render_Picker('Answer', 'AnswerId', onselectionChange, { value: selanswer, qtn: qtn, EStyle_Qtn_Input })
                                        }
                                        {qtn.QuestionType == 'Multi choice list' && qtn.Answers &&
                                            <MultiSelect
                                                items={list_mcdata}
                                                uniqueKey="AnswerId"
                                                onSelectedItemsChange={(selectedItems) => { console.log('onSelectedItemsChange'); setMultiSelectValue(selectedItems, qtn) }}
                                                selectedItems={selansid}
                                                selectText="Pick Items"
                                                searchInputPlaceholderText="Search Items..."
                                                // onChangeInput={ (text)=> console.log(text)}
                                                tagRemoveIconColor={PageTheme.$primary_color}
                                                tagBorderColor={PageTheme.$primary_color}
                                                tagTextColor={PageTheme.$primary_color}
                                                selectedItemTextColor={PageTheme.$primary_color}
                                                selectedItemIconColor={PageTheme.$primary_color}
                                                tagContainerStyle={{ height: 30, width: '100%', paddingVertical: 5 }}
                                                styleTextTag={{ fontSize: 14 }}
                                                itemTextColor={PageTheme.$text_color}
                                                displayKey="Answer"
                                                searchInputStyle={customStyle.wind_MultiSearchInputStyle}
                                                styleMainWrapper={EStyle_Qtn_MultiChoice}
                                                submitButtonColor={PageTheme.$primary_color}
                                                submitButtonText="Submit"
                                            />
                                        }
                                        {(qtn.QuestionType == 'Number' || qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Text' || qtn.QuestionType == 'OnlyText' || qtn.QuestionType == "Calculate") &&
                                            <>

                                                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                                                    <TextInput
                                                        ref={(reff) => { inputRefs.current['input1_' + qtn.QuestionId] = reff; }}
                                                        style={[customStyle.surveyQtn_InputStyle, OTPVerify ? { width: '65%' } : { width: '100%' }, EStyle_Qtn_Input, ((qtn.QuestionType == "Calculate") && { fontWeight: "700", })]}
                                                        placeholder=""
                                                        autoComplete='off'
                                                        // editable={qtn.QuestionType!="Calculate" && (verifiedOTP && OTPVerify) }
                                                        editable={OTPVerify ? !qtn.VerifyOTP == 1 : qtn.QuestionType != "Calculate"}
                                                        placeholderTextColor={PageTheme.$placeholder_color}
                                                        // keyboardType={'ascii-capable'}
                                                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                                        blurOnSubmit={false}
                                                        keyboardType={(qtn.QuestionType == 'Decimal' ? 'decimal-pad' : (qtn.QuestionType == 'Text' || qtn.QuestionType == 'OnlyText' ? 'default' : 'number-pad'))}
                                                        value={selansid}
                                                        minLength={minlen}
                                                        maxLength={maxlen}
                                                        onSubmitEditing={() => { focusToNext(qtn, '1') }}
                                                        // onChangeText={(val)=>{setTextValue(val,qtn,(qtn.QuestionType=='Decimal'?'decimal':(qtn.QuestionType=='Text'?'text':'numeric')))}}
                                                        onChangeText={(val) => { setTextValue(val, qtn, qtn.QuestionType == 'Decimal' ? 'decimal' : qtn.QuestionType == 'Text' ? 'text' : qtn.QuestionType == 'OnlyText' ? 'onlytext' : 'numeric') }}
                                                    />

                                                    {/* {console.log("minlen------------", String(selansid || "")?.length, minlen)} */}

                                                    {OTPVerify && String(selansid || "")?.length == minlen && <>
                                                        <TouchableOpacity activeOpacity={0.4} style={[customStyle.vlEmplSearchBtn2, { marginTop: 0, paddingVertical: 10 }]}
                                                            onPress={() => { qtn.VerifyOTP ? '' : Send_OTP(selansid) }}
                                                        >
                                                            <Text style={customStyle.vlEmplSearchBtnText}>{qtn.VerifyOTP ? "Verified" : "Send OTP"}</Text>
                                                        </TouchableOpacity>
                                                    </>}


                                                </View>
                                                {showotpfeild && OTPVerify &&
                                                    <View style={customStyle.mt40}>
                                                        <OtpInputs
                                                            ref={otpRef}
                                                            handleChange={(code) => { setOtp(code); }}
                                                            numberOfInputs={6}
                                                            secureTextEntry={true}
                                                            defaultValue=''
                                                            keyboardType={"numeric"}
                                                            // autofillFromClipboard={false}
                                                            inputStyles={customStyle.verify_otp_inputStyle}
                                                            style={customStyle.otp_field}
                                                        />
                                                    </View>
                                                }
                                            </>
                                        }



                                        {
                                            (qtn.QuestionType == 'Date') &&
                                            <View style={[customStyle.surveyQtn_datePicker_con, EStyle_Qtn_Input]}>
                                                <Text style={customStyle.surveyQtn_datePicker_text}>{selansid != '' ? selansid : 'DD/MM/YYYY'}</Text>
                                                <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={() => {
                                                    { console.log("qtn_nnnnn", qtn) }
                                                    setDateValue(selanswer);
                                                    //showQtnDatePicker(qtn, true)
                                                    setShowDatePickerId({ showDatePicker: true, QuestionId: qtn.QuestionId })
                                                }}>
                                                    <Fontisto size={20} color={PageTheme.$accent_color} name="date" />
                                                </TouchableOpacity>
                                            </View>
                                        }

                                        {(showDatePickerId && showDatePickerId?.showDatePicker == true 
                                        && showDatePickerId?.QuestionId == qtn.QuestionId
                                         && qtn.QuestionType == 'Date') 
                                         && renderDatePicker(qtn)}
                                         
                                        {
                                            (qtn.QuestionType == 'Rating') &&
                                            <View style={[customStyle.surveyQtn_datePicker_con, EStyle_Qtn_Input]}>
                                                <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={() => { setRatingQtn(qtn); setShowRating(true); }}>
                                                    <MaterialCommunityIcons size={25} color={PageTheme.$accent_color} name="drag" />
                                                </TouchableOpacity>
                                            </View>
                                        }

                                        {
                                            (qtn.QuestionType == 'Audio') &&
                                            <View style={customStyle.surveyQtn_datePicker_con}>
                                                <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={() => { show_recorder(qtn); }}>
                                                    <FontAwesome size={25} color={PageTheme.$accent_color} name="microphone" />
                                                </TouchableOpacity>
                                            </View>
                                        }

                                        {
                                            showImageTag &&
                                            <View style={[customStyle.store_audit_img_con, EStyle_Qtn_Image]}>
                                                <Image source={(selimg != '' && selimg != null) ? { uri: selimg } : require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image, ((selimg != '' && selimg != null) ? { resizeMode: 'contain' } : { width: 100, height: 150, resizeMode: 'stretch', alignSelf: 'center' })]} />
                                                {console.log("checkimgmandate:", Image1Mandatory)}
                                                {Image1Mandatory || isImageMandateforAns ?
                                                    <TouchableOpacity style={customStyle.store_audit_pickimg_btn} onPress={() => { openCamera(qtn, '1') }}>
                                                        <CameraImg5 width={50} height={50} />
                                                    </TouchableOpacity> :
                                                    <TouchableOpacity style={customStyle.store_audit_pickimg_btn} onPress={() => { openCamera(qtn, '1') }}>
                                                        <Entypo name="camera" color={PageTheme.$text_color} size={28} />
                                                    </TouchableOpacity>}
                                            </View>
                                        }

                                        {
                                            showImageTag2 &&
                                            <View style={[customStyle.store_audit_img_con, EStyle_Qtn_Image]}>
                                                <Image source={(selimg2 != '' && selimg2 != null) ? { uri: selimg2 } : require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image, ((selimg2 != '' && selimg2 != null) ? { resizeMode: 'contain' } : { width: 100, height: 150, resizeMode: 'stretch', alignSelf: 'center' })]} />
                                                {Image2Mandatory || isImageMandate2forAns ?
                                                    <TouchableOpacity style={customStyle.store_audit_pickimg_btn} onPress={() => { openCamera(qtn, '2') }}>
                                                        <CameraImg5 width={50} height={50} />
                                                    </TouchableOpacity> :
                                                    <TouchableOpacity style={customStyle.store_audit_pickimg_btn} onPress={() => { openCamera(qtn, '2') }}>
                                                        <Entypo name="camera" color={PageTheme.$text_color} size={28} />
                                                    </TouchableOpacity>}
                                            </View>
                                        }
                                    </View>
                                </>
                            )
                        }

                    })
                }
            </View>

        );
    }


    function _renderHeader(currentIndex) {
        return (
            <View style={customStyle.album_ZOOM_topBar}>
                <Text style={customStyle.album_ZOOM_indicator}>{`${(currentIndex + 1)}/${zoomImageUrl.length}`}</Text>
                <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={() => { setShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#fff'} size={24} />
                </TouchableOpacity>
            </View>
        )
    }


    function _renderSurveyView() {
        return (
            <View style={customStyle.SVn_ContentCon}>
                <KeyboardAwareFlatList
                    style={customStyle.SVn_ContentOuter}
                    extraData={rerenderdata}
                    nestedScrollEnabled={true}
                    removeClippedSubviews={false}
                    showsVerticalScrollIndicator={false}
                    contentContainerStyle={customStyle.SVn_ContentInner}
                    keyboardShouldPersistTaps="handled"
                    enableOnAndroid={true}
                    extraHeight={230} // adjust as needed for keyboard
                    data={SurveySubCats}
                    renderItem={({ item, index, separators }) => {
                        let subcat = item, s_index = index;
                        let RefImage = item.RefImage;
                        return (
                            <View style={customStyle.SVn_GroupView} key={s_index}>

                                {_renderSurveyQtns(subcat)}

                            </View>
                        )
                    }}
                >

                </KeyboardAwareFlatList>
            </View>
        );
    }



    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} pointerEvents="auto" />}

            <View style={{ zIndex: 10, elevation: 10 }}>
                <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            </View>

            {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); }} />

            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper, customStyle.roundScrollZIndex]}>

                <View style={[customStyle.pageContentWrapper, customStyle.SVn_PageWrapper]}>
                    <View style={customStyle.SVn_activeSurvey}>
                        <LinearGradient colors={[PageTheme.$primary_color, PageTheme.$gradient1]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.SVn_activeSurvey_tile}>
                            {/* <Text style={customStyle.SV_activeSurvey_name}>{(ActiveSurvey.SurveyName!=null?(ActiveSurvey.SurveyName.length>26?ActiveSurvey.SurveyName.substring(0,26)+'...':ActiveSurvey.SurveyName) : '')}</Text> */}
                            <Text style={customStyle.SV_activeSurvey_name}>{(`${(ST.SurveyId != null ? ST.SurveyId : 'Survey Id')} : ` + (ActiveSurvey.SurveyId || '') + (ShowCat == true ? '  |  ' + `${(ST.CategoryId != null ? ST.CategoryId : 'Category Id')} : ` + (ActiveCategory.CategoryId || '') : ''))}</Text>
                        </LinearGradient>
                    </View>
                    {Object.keys(ActiveSurvey).length > 0 &&
                        _renderSurveyView()
                    }
                    <View style={[customStyle.SVn_SubmitBtn]}>
                        <GradientButton {...props} title={ST.Save} onPress={() => {
                            // getAllFolderImages()
                            onSubmitData()
                        }} />
                    </View>
                </View>
            </LinearGradient>
            {showRating == true &&
                renderRatingView()
            }

            {show_zoomImage &&
                <View style={customStyle.album_ZOOM_wrap}>
                    <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={[{ url: zoomImageUrl }]} index={0}
                    // renderHeader={_renderHeader} renderIndicator={()=>null}
                    />
                </View>
            }

            {showRecorder == true &&
                renderRecorderView()
            }
        </Container>
    );
}


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