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 } from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { UploadData2, getAllFileForAFolder, getAllFolderImages, marktext1, marktext2, resizeImage, restore_ImageWithMetaData, validateNumber } from '../controller/functions';
import { db, common_ImagePath, ImageFolderPath, ContractFormImagePath } 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 { PageTheme } from '../styles/Themes';
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 { CustomPicker2 } from '../components/CustomPicker';
import { METHODS, getMethodName } from '../constants/methodNames';
import { URL_IMAGE } from '../constants/constants';
import { UploadImagesWithoutWait } from '../constants/uploadData';
import DateTimePickerModal from "react-native-modal-datetime-picker";


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


function ContractForm(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 [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 [storeData, setStoreData] = useState({});
    const [ShowCat, setShowCat] = useState(false);
    const [ActiveProgram, setActiveProgram] = useState({});
    const [ActiveCategory, setActiveCategory] = 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 showCameraRef = useRef(null);
    const [getImageProps, setGetImageProps] = useState({});
    const [reasons_list, setReasons_list] = useState([]);
    const [IsContractSigned, setIsContractSigned] = useState(0);
    const [NoContrRsn, setNoContrRsn] = useState({});
    const animatedChoice = useRef(new Animated.Value(0)).current;

    const inputRefs = 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 [selectedDate, setSelectedDate] = useState(moment().startOf('month'));
    const [DateValueObj, setDateValueObj] = useState({});



    // 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 programdata = params.program || {};


        setStoreData(storeData1);
        setActiveProgram(programdata)

        getData(storeData1, programdata);

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

    const [isDatePickerVisible, setDatePickerVisibility] = useState(false);

    const showDatePicker = () => {
        setDatePickerVisibility(true);
    };

    const hideDatePicker = () => {
        setDatePickerVisibility(false);
    };

    const handleConfirm = (date) => {
        console.warn("A date has been picked: ", date);
        setTextValue(date, DateValueObj?.qtn)
        hideDatePicker();
    };



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

    function onBeforeRemove(e) {
        if (showCameraRef.current == true) {
            e.preventDefault();
            BgShowCamera(false);
        }
        else {
            if (hasUnsavedChangesRef.current == 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 BgShowCamera(val) {
        showCameraRef.current = val
        setShowCamera(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 getData(storeData1, program = {}) {
        try {
            let { StoreId } = storeData1;
            let { ProgramId, ProgramDefinitionId } = program;

            await db.transaction(async function (txn) {


                let q = `select * from Master_NonContractFromReason `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    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) {
                                setReasons_list(arr);
                            }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);


                // get contract data
                let q3 = `select * from ${AppTables.CONTRACT_FORM} where PROGRAM_ID=${ProgramId} and PROGRAM_DEFINITION_ID='${ProgramDefinitionId}' and STORE_ID='${StoreId}' `;

                await txn.executeSql(q3, [], async function (txn2, txnres) {
                    if (txnres.rows.length > 0) {
                        let data = txnres.rows.item(0);
                        let { IS_CONTRACT_SIGNED, REASON_ID, REASON } = data;
                        setIsContractSigned(IS_CONTRACT_SIGNED);
                        let obj = { "ReasonId": REASON_ID, "Reason": REASON }
                        setNoContrRsn(obj);
                        if (IS_CONTRACT_SIGNED != null && animatedChoice != null) {
                            Animated.timing(animatedChoice, {
                                toValue: IS_CONTRACT_SIGNED,
                                duration: 400,
                                useNativeDriver: false,
                            }).start();
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);



                // get qtns data 
                let q2 = `SELECT DISTINCT T.CategoryId,T.Category,T.CategorySequence FROM Master_ContractFormQuestion T `;

                await txn.executeSql(q2, [], async function (txn2, txnres) {
                    console.log('contract form cat count:', txnres.rows.length);
                    if (txnres.rows.length > 0) {
                        let arr = [], allQtns = [];

                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            let all_scat_qtns = await getSurveyQtns(data, storeData1, program)
                            console.log('all_scat_qtns:', all_scat_qtns.length)
                            data['Questions'] = all_scat_qtns;
                            allQtns = allQtns.concat(all_scat_qtns);
                            arr.push(data);
                            if (i == txnres.rows.length - 1) {
                                setSurveySubCats(arr);
                                setSurveyQuestions(allQtns);
                                setProcessing(false);
                            }
                        }
                    }

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

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


    async function getSurveyQtns(item, storeData1, program) {
        return new Promise((resolve, reject) => {
            try {
                let { StoreId } = storeData1;
                let { ProgramId, ProgramDefinitionId } = program;
                let { CategoryId } = item;

                db.transaction(async function (txn) {

                    // get inserted audit
                    let selectlist = ` DISTINCT T.CategoryId,T.Category,T.Question as Question,T.QuestionId as QuestionId,T.QuestionType as QuestionType,T.ShowContractNotSigned,T.QEnable,T.LengthValidation as LengthValidation,T.QuestionImageAllow,T.DateRange as DateRange,T.MaxLength as MaxLength,T.MinLength as MinLength,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 ${AppTables.CONTRACT_FORM_DATA} T1 on T.CategoryId=T1.CATEGORY_ID and T.QuestionId=T1.QUESTION_ID`;
                    let q2 = `Select ${selectlist} FROM Master_ContractFormQuestion T ${join} WHERE T1.STORE_ID='${StoreId}' AND T1.VISIT_DATE= '${d2}' AND T1.PROGRAM_ID=${ProgramId} AND PROGRAM_DEFINITION_ID='${ProgramDefinitionId}' AND T1.CATEGORY_ID='${CategoryId}'  `;
                    q2 += ` ORDER BY T.CategorySequence,T.QuestionSequence `;

                    // q2=`select * from ${AppTables.CONTRACT_FORM_DATA} `;
                    console.log("added qtns q:", q2);
                    await txn.executeSql(q2, [], async function (txn2, txnres) {
                        console.log('program qtns added:', txnres.rows.length);
                        if (txnres.rows.length > 0) {
                            let arr = [];
                            var QD = QuestionsData;
                            for (var i = 0; i < txnres.rows.length; i++) {
                                let data = txnres.rows.item(i);
                                if (i == 0) {
                                    console.log("added qtns data:", data);
                                }

                                data.QEnable = data.QEnable == 1 || data.QEnable == 'true' ? true : false;

                                let answers = [];
                                let qtn = data;
                                qtn.isDisabled = qtn.isDisabled == 1 || qtn.isDisabled == '1' ? true : false

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

                                if (data.QuestionType == 'Multi choice list' || data.QuestionType == 'Single choice list' || data.QuestionType == 'Rating') {
                                    let allanswers = await getAnswers(data, storeData1, program, 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') {
                                    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) >= 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) >= 0)) {
                                                showImageTag2 = true;
                                            }

                                        }
                                    }
                                }

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

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

                                if (qtn.QuestionType == 'Audio') {
                                    let voicefile_path = (Platform.OS == 'ios' ? 'file://' : '') + `${ContractFormImagePath}/` + '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) {
                                    resolve(arr);
                                }
                            }
                        }
                        else {
                            let selectlist = ` DISTINCT T.CategoryId,T.Category,T.Question as Question,T.QuestionId as QuestionId,T.QuestionType as QuestionType,T.ShowContractNotSigned,T.QEnable,T.LengthValidation as LengthValidation,T.QuestionImageAllow,T.DateRange as DateRange,T.MaxLength as MaxLength,T.MinLength as MinLength,T.OTP as OTP`;
                            let q = `Select ${selectlist} FROM Master_ContractFormQuestion T WHERE   T.CategoryId='${CategoryId}'  `;
                            q += ` ORDER BY T.CategorySequence,T.QuestionSequence `;


                            await txn.executeSql(q, [], async function (txn2, txnres2) {
                                console.log('program qtns loaded:', 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;
                                        let answers = [];
                                        if (data.QuestionType == 'Multi choice list' || data.QuestionType == 'Single choice list' || data.QuestionType == 'Rating') {
                                            let allanswers = await getAnswers(data, storeData1, program, 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);

                                        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, storeData1, program, isInserted) {
        let { StoreId } = storeData1;
        let { ProgramId } = program;
        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.EnableQuestion,T.DisableQuestion`;
                let q2 = `Select ${selectlist} FROM Master_ContractFormQuestion T WHERE T.QuestionId='${qtn.QuestionId}'  ORDER BY T.AnswerSequence `;

                await txn.executeSql(q2, [], async function (txn2, txnres) {
                    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) {
        setErrorField({});
        setError(false);
        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 + '_' + ActiveProgram.ProgramId + '_' + 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:' + ActiveProgram.ProgramId + ' | Question Id :' + qtn.QuestionId + ' | Image Type: Contract Form' + ' | 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';
            let id_key = qtn.QuestionId + '_AnswerId';
            let ans_key = qtn.QuestionId + '_Answer';
            qd[imgname_key] = filename;
            if (qtn.QuestionType == 'Image') {
                qd[id_key] = "0";
                qd[ans_key] = filename;
            }

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

        }
    }

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

    async function disableQtns(sqtns, DQtns, data, isreturn = false) {
        console.log('disableQtns');
        if (DQtns.length > 0) {
            new Promise.all(
                DQtns.map((qid, q_index) => {
                    let s_qtnindex = sqtns.findIndex(i => i.QuestionId == qid) || {};
                    console.log('sqtns qid', qid, s_qtnindex)
                    let s_qtn = s_qtnindex >= 0 ? sqtns[s_qtnindex] : {};
                    if (s_qtnindex >= 0) {
                        console.log('sqtns not found', s_qtnindex)
                        s_qtn['isDisabled'] = true
                        sqtns[s_qtnindex] = s_qtn;
                        let id_key = s_qtn.QuestionId + '_AnswerId';
                        let ans_key = s_qtn.QuestionId + '_Answer';
                        data[id_key] = 0;
                        data[ans_key] = '';
                    }
                    return false
                })
            ).then(async (val) => {
                setSurveyQuestions(sqtns);
                // setQuestionsData(data);
                BgWindowData(data)
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);
            })
        }
    }

    async function enableQtns(sqtns, EQtns, DQtns, data) {
        console.log('enableQtns');
        new Promise.all(
            EQtns.map((qid, q_index) => {
                let s_qtnindex = sqtns.findIndex(i => i.QuestionId == qid) || {};
                let s_qtn = s_qtnindex >= 0 ? sqtns[s_qtnindex] : {};
                if (s_qtnindex >= 0) {
                    s_qtn['isDisabled'] = false
                    sqtns[s_qtnindex] = s_qtn;
                }
                return false
            })
        ).then(async (val) => {
            if (DQtns.length > 0) {
                disableQtns(sqtns, DQtns, data)
            }
            else {
                setSurveyQuestions(sqtns);
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true)
                setrerenderdata(!rerenderdata);
            }
        })
    }

    function onselectionChange(option, qtn) {
        setErrorField({});
        setError(false);

        let data = QuestionsData;
        let id_key = qtn.QuestionId + '_AnswerId';
        let ans_key = qtn.QuestionId + '_Answer';
        data[id_key] = option.value;
        data[ans_key] = option.label;

        // setQuestionsData(data);
        BgWindowData(data)

        let aq_ans = qtn.Answers != null ? qtn.Answers : [];
        let ans_obj = aq_ans.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
        if (EQtns.length > 0) {
            enableQtns(sqtns, EQtns, DQtns, data)
        }
        else if (DQtns.length > 0) {
            disableQtns(sqtns, DQtns, data)
        }
        else {
            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata(!rerenderdata);
        }



    }

    function setTextValue(value, qtn, type = '') {
        setErrorField({});
        setError(false);
        if (value != '') {
            let isValid = validateNumber(value, type);
            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('MM/YYYY');
            showQtnDatePicker(qtn, false);
            obj[id_key] = 0;
            obj[ans_key] = mfdate;
            obj[date_key] = moment(d).format('MM/DD/YYYY');
        }
        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;
            setSurveyQuestions(sq);
            setDatePickerVisibility(true)
            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];
            console.log("nextKey", nextKey, 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);
            // notify('Please stop playing audio first');
            // return;
        }

        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, ActiveProgram1, 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 + '_' + ActiveProgram1.ProgramId + '_' + qtn.QuestionId + '_SurveyRecording_' + picture_clicked_date + '_' + picture_clicked_time;
                let filename = Platform.OS == 'ios' ? commname + '.m4a' : commname + '.mp3';

                const url = Platform.OS == 'ios' ? `file://${ContractFormImagePath}/` + 'Recordings/' + filename : `${ContractFormImagePath}/` + 'Recordings/' + filename;
                const url_dir = `${ContractFormImagePath}/` + '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);
                            // }
                            // else{
                            //     notify('Something Went Wrong! Cannot open file for recording!');
                            // }

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

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

            let isRemoved = await removeOldData();

            await db.transaction(async function (txn) {


                var values = '';
                let qtnsToUpload = [];
                let { ProgramId, ProgramDefinitionId } = ActiveProgram;
                for (var i = 0; i < SurveyQuestions.length; i++) {


                    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, ShowContractNotSigned, 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 showQtn = (IsContractSigned || (IsContractSigned != '1' && ShowContractNotSigned == '1'))
                    if (showQtn) {
                        values += values != '' ? ' , ' : '';
                        values += ` ('${StoreId}','${d2}','${ProgramDefinitionId}','${ProgramId}','${CategoryId}','${Question}','${QuestionId}','${QuestionType}','${selans}','${selansid}','${f_imgalloq1}','${(imgName1 || '')}','${imgallow2}','${(imgName2 || '')}','${multiops}','${isQtnDisabled}','${d2}') `;


                        let ReasonId = IsContractSigned == 1 ? (NoContrRsn.ReasonId != null ? NoContrRsn.ReasonId : '0') : '0';
                        let Reason = IsContractSigned == 1 ? (NoContrRsn.Reason != null ? NoContrRsn.Reason : '') : '';

                        let dataToUpload = {}
                        dataToUpload['UserId'] = props.UserId;
                        dataToUpload['Store_Id'] = StoreId;
                        dataToUpload['ProgramDefinitionId'] = ProgramDefinitionId;
                        dataToUpload['ProgramId'] = ProgramId;
                        dataToUpload['CategoryId'] = CategoryId;
                        dataToUpload['QuestionId'] = QuestionId;
                        dataToUpload['QuestionType'] = QuestionType;
                        dataToUpload['Answer'] = selans;
                        dataToUpload['AnswerId'] = selansid;
                        dataToUpload['MultiAnswerId'] = multiops != null && multiops != 'undefined' ? multiops : '';
                        dataToUpload['AnswerImage1'] = (imgName1 || '');
                        dataToUpload['AnswerImage2'] = (imgName2 || '');
                        dataToUpload['VisitDate'] = d2;

                        qtnsToUpload.push(dataToUpload);
                    }
                }


                // let ReasonId=IsContractSigned==1?(NoContrRsn.ReasonId!=null?NoContrRsn.ReasonId:''):'';
                // let Reason=IsContractSigned==1?(NoContrRsn.Reason!=null?NoContrRsn.Reason:''):'';

                let ReasonId = IsContractSigned != 1 ? (NoContrRsn.ReasonId != null ? NoContrRsn.ReasonId : '') : '';
                let Reason = IsContractSigned != 1 ? (NoContrRsn.Reason != null ? NoContrRsn.Reason : '') : '';

                let UploadData = {}
                UploadData['UserId'] = props.UserId;
                UploadData['Store_Id'] = StoreId;
                UploadData['ProgramDefinitionId'] = ProgramDefinitionId;
                UploadData['ProgramId'] = ProgramId;
                UploadData['IsContractSigned'] = IsContractSigned;
                UploadData['ReasonId'] = ReasonId != '' ? ReasonId : '0';
                UploadData['Reason'] = Reason;
                UploadData['ContractQtns'] = qtnsToUpload;
                UploadData['VisitDate'] = d2;


                let hdrValues = `('${StoreId}','${d2}','${ProgramDefinitionId}','${ProgramId}','${IsContractSigned}','${ReasonId}','${Reason}','${d2}') `;

                let add_hdr_data = `INSERT INTO ${AppTables.CONTRACT_FORM} (STORE_ID,VISIT_DATE,PROGRAM_DEFINITION_ID,PROGRAM_ID,IS_CONTRACT_SIGNED,REASON_ID,REASON,ADDED_DATE) VALUES ${hdrValues} `;
                let add_data = `INSERT INTO ${AppTables.CONTRACT_FORM_DATA} (STORE_ID,VISIT_DATE,PROGRAM_DEFINITION_ID,PROGRAM_ID,CATEGORY_ID,QUESTION,QUESTION_ID,QUESTION_TYPE,ANSWER,ANSWER_ID,IMAGE_ALLOW1,IMAGE1,IMAGE_ALLOW2,IMAGE2,MULTI_OPTIONS_IDS,IS_DISABLED,ADDED_DATE) VALUES ${values} `;

                // console.log("hdrValues:",hdrValues);
                // console.log("values:",values);
                await txn.executeSql(add_hdr_data, [], async function (txn2, txnres) {
                    await txn.executeSql(add_data, [], async function (txn2, txnres) {
                        console.log('surveys added');
                        BgUnsavedChanges(false);
                        notify('Contract form successfully updated!', 'SHORT');
                        setLoaderTitle("Uploading Data...")
                        UploadContractForm(UploadData);
                    }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot update contract form!') },);
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify("Cannot update contract form!") },);


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

    async function removeOldData() {
        let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {
                //  remove old data
                let q = `DELETE FROM ${AppTables.CONTRACT_FORM} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PROGRAM_ID='${ActiveProgram.ProgramId}' `;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('contract from hdr data deleted');
                    let q2 = `DELETE FROM ${AppTables.CONTRACT_FORM_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PROGRAM_ID='${ActiveProgram.ProgramId}' `;
                    await txn.executeSql(q2, [], async function (txn2, txnres) {
                        console.log('contract form data deleted');
                        resolve(true);
                    }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
                }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);

            });
        }).catch((err) => {
            console.log(err);
            return false;
        })

    }

    async function UploadContractForm(UploadData) {
        const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);

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

        let allFilesToUpload = getAllFileForAFolder(ContractFormImagePath, "ContractFormImages");
        console.log("url:", url);
        console.log("postData:", postData);

        await UploadData2(url, postData)
            .then(async (res) => {
                console.log('res:', res);
                if (res.UploadJsonResult != null && res.UploadJsonResult == 'Success') {
                    const url2 = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);
                    let allImageUploaded = true;
                    if (allFilesToUpload.length > 0) {
                        allImageUploaded = await uploadContractFormFiles(allFilesToUpload);
                    }
                    if (allImageUploaded == true) {
                        console.log('all Visitor image uploaded');
                        let isupdated = await updateCFStatus();
                        if (isupdated == true) {
                            setProcessing(false);
                            notify("Contract form uploaded!");
                            props.navigation.goBack();
                        }
                        else {
                            setProcessing(false);
                            notify("Cannot update contract form status");
                        }
                    }
                    else {
                        setProcessing(false);
                        notify("Cannot upload contract form images and files!");
                    }

                } else {
                    setProcessing(false);
                    notify(ST.Cannotuploadvisitordata);
                }
            })
            .catch((err) => {
                console.log(err);
                setProcessing(false);
                notify(ST.Cannotuploadvisitordata);
            });

    }

    async function uploadContractFormFiles(allfiles = []) {
        let d1 = new Date();
        let d2 = moment(d1).format('MM/DD/YYYY');
        let uploadCount = 0;
        const url = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);

        var isAllUploaded = false;
        return await Promise.all(
            allfiles.map(async (file, i) => {
                let index = i;
                let actualfilepath = 'file://' + file.uri;
                let isExists = await RNFS.exists(actualfilepath).then((res) => { return res; });
                console.log('isExists file', isExists, file.uri);
                let isImageUploaded = false;
                if (isExists == false) {

                    let postData = new FormData();
                    postData.append('file', {
                        uri: actualfilepath,
                        // type: mime?.getType(actualfilepath) || file.type,
                        type: file.type,
                        name: file.name,
                    });

                    postData.append('Foldername', file.folderName);
                    postData.append('Path', d2);

                    isImageUploaded = await UploadImagesWithoutWait(postData, url);
                    if (isImageUploaded == true) {
                        console.log('isExists file uploaded', isExists, uploadCount, index, allfiles.length - 1);
                        await RNFS.unlink(actualfilepath);
                        uploadCount++;
                        // UpdateUploadCountLocal(uploadCount);
                        if (uploadCount == allfiles.length) {
                            isAllUploaded = true;
                        }

                    } else {
                        console.log('file not uploaded:', isExists, actualfilepath);
                    }

                }
                else {//file does not exists 
                    uploadCount++;
                    if (uploadCount == allfiles.length) {
                        isAllUploaded = true;
                    }
                }

                return isImageUploaded;
            })
        ).then((val) => {
            console.log(val);
            return isAllUploaded;
        })
            .catch((err) => {
                console.log(err);
                return false;
            })
    }

    async function updateCFStatus() {
        return new Promise((resolve, reject) => {
            db.transaction(async function (txn) {

                let q = `Update Mapping_ContractForm SET ContractFormStatus='1' WHERE ProgramId='${ActiveProgram.ProgramId}' and ProgramDefinitionId='${ActiveProgram.ProgramDefinitionId}' and StoreId='${storeData.StoreId}'`;
                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('CF status Updated to 1');
                    resolve(true);
                }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);

            });
        }).then((val) => {
            return val;
        }).catch((err) => {
            console.log(err);
            return false;
        });
    }


    async function validate() {

        var isvalid = true;
        const QD = QuestionsData;
        console.log(SurveyQuestions.length);

        function showError(obj, isErr) {
            setErrorField(obj);
            setError(isErr);
        }

        let errorobj = {};
        if (IsContractSigned != '1' && (NoContrRsn.ReasonId == null || NoContrRsn.ReasonId == "")) {
            errorobj['EF_NExistReason'] = "NExistReason";
            showError(errorobj, true);
            isvalid = false;
            notify("Please select reason for not signing the contract", 'SHORT');
        }
        else {
            for (var i = 0; i < SurveyQuestions.length; i++) {
                let qtn = SurveyQuestions[i];
                let selansid = '', selanswer = '', selimg = '', showImageTag = false, showImageTag2 = 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 showqtn = ((IsContractSigned) || (IsContractSigned != '1' && qtn.ShowContractNotSigned == '1')) ? true : false;

                let isLengthValidationReq = false;
                let LengthValidation = qtn.LengthValidation == 'true' || qtn.LengthValidation == 1 ? true : false;
                let minL = qtn.MinLength != null && qtn.MinLength != '' ? qtn.MinLength : 0;
                let maxL = qtn.MaxLength != null && qtn.MaxLength != '' ? qtn.MaxLength : 10;
                let ansVal = QD[ans_key];

                // LengthValidation is required for number type input only
                if (qtn.QuestionType == 'Number') {
                    isLengthValidationReq = LengthValidation;
                }
                errorobj['EF_qtn'] = qtn;

                console.log("isDisabled in validate:", isDisabled, showqtn, qtn.QuestionType, qtn.QuestionId, qtn.ShowContractNotSigned)
                if (isDisabled == false && showqtn == true) {
                    let isImgAllowed = (qtn.QuestionImageAllow == true || qtn.QuestionImageAllow == 'true' || qtn.QuestionImageAllow == 1);
                    let checkForAnsKey = (qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Number' || qtn.QuestionType == 'Text' || qtn.QuestionType == 'Date' || qtn.QuestionType == 'Rating');
                    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(',') : [];
                    }


                    if (qtn.QuestionType == 'Multi choice list' && selansid.length <= 0) {
                        errorobj['EF_Qtn_MultiChoice'] = 'Qtn_MultiChoice';
                        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_Qtn_Input'] = 'Qtn_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_Qtn_Input'] = 'Qtn_Input';
                        showError(errorobj, true);
                        isvalid = false;
                        notify(ST.Pleaserecordaudioclipfortherequiredfield, 'SHORT');
                        break;
                    }
                    else if (qtn.QuestionType == 'Image' && (Object.keys(QD).indexOf(img_key) < 0 || (Object.keys(QD).indexOf(img_key) >= 0 && QD[img_key] === ''))) {
                        errorobj['EF_Qtn_Image'] = 'Qtn_Image';
                        showError(errorobj, true);
                        isvalid = false;
                        notify(ST.Pleaseaddimages, 'SHORT');
                        break;
                    }
                    else if (Object.keys(QD).indexOf(id_key) < 0 || (Object.keys(QD).indexOf(id_key) >= 0 && (QD[id_key] === ''))) {
                        errorobj['EF_Qtn_Input'] = 'Qtn_Input';
                        showError(errorobj, true);
                        isvalid = false;
                        notify(ST.Pleasefillalldetails, 'SHORT');
                        console.log(QD[id_key], QD, id_key)
                        break;
                    }
                    else if (isImgAllowed && (Object.keys(QD).indexOf(img_key) < 0 || (Object.keys(QD).indexOf(img_key) >= 0 && QD[img_key] === ''))) {
                        errorobj['EF_Qtn_Image'] = 'Qtn_Image';
                        showError(errorobj, true);
                        isvalid = false;
                        notify(ST.Pleaseaddimages, 'SHORT');
                        break;
                    } else if (isLengthValidationReq && ansVal.length < minL) {
                        errorobj['EF_Qtn_Input'] = 'Qtn_Input';
                        showError(errorobj, true);
                        isvalid = false;
                        notify("Minimum digits allowed is " + minL, 'SHORT');
                        break;
                    } else if (isLengthValidationReq && ansVal.length > maxL) {
                        errorobj['EF_Qtn_Input'] = 'Qtn_Input';
                        showError(errorobj, true);
                        isvalid = false;
                        notify("Maximum digits allowed is " + maxL, '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;
                                }
                                else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId) >= 0)) {
                                    showImageTag = true;
                                }

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

                    console.log("showImageTag in validate:", QD[img_key], img_key)
                    if (showImageTag && (Object.keys(QD).indexOf(img_key) < 0 || (Object.keys(QD).indexOf(img_key) >= 0 && QD[img_key] === ''))) {
                        errorobj['EF_Qtn_Image'] = 'Qtn_Image';
                        showError(errorobj, true);
                        isvalid = false;
                        notify(ST.Pleaseaddimages, 'SHORT');
                        break;
                    }

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

                }
            }
        }

        return isvalid;
    }

    function onselectionChange3(option, keyLbl, keyVal) {
        setErrorField({});
        setError(false);
        let allData = NoContrRsn;
        allData[keyVal] = option.value;
        allData[keyLbl] = option.label;
        setNoContrRsn(allData);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

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

        setIsContractSigned(val);
        BgUnsavedChanges(true);
        if (val == 0) {

        }
    }


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

    const setDatePickerValue = (qtn, selanswer) => {
        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');
        if (DateRange == 'RFD') {
            maxDate = moment().format('MM/DD/YYYY');
        }
        else if (DateRange == 'RPD') {
            minDate = moment().format('MM/DD/YYYY');
        }

        setDateValueObj({ minDate, maxDate, selanswer, qtn })
    }


    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');
        if (DateRange == 'RFD') {
            maxDate = moment().format('MM/DD/YYYY');
        }
        else if (DateRange == 'RPD') {
            minDate = moment().format('MM/DD/YYYY');
        }

        // return (
        //     <DateTimePicker
        //     testID="dateTimePicker"
        //     value={(dateValue!=null && dateValue!=''?new Date(dateValue):new Date())}
        //     mode={'date'}
        //     display="default"  
        //     onChange={(event, selectedDate)=>{setTextValue(selectedDate,qtnn)}}
        //     maximumDate={new Date(maxDate)}
        //     minimumDate={new Date(minDate)}
        //     />    
        // );
    }

    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, ActiveProgram, 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://' : '') + `${ContractFormImagePath}/` + '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;
        return (
            <View style={customStyle.SVn_GroupViewList}>
                {
                    SurveyQuestions.length > 0 &&
                    SurveyQuestions.map((item, index) => {

                        let qtn = item;
                        let selansid = '', selanswer = '', selimg = '', selimg2 = '', showImageTag = false, showImageTag2 = 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 = [];

                        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 == '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 == '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 || '') : '';
                        }
                        else if (qtn.QuestionType == 'Image') {
                            showImageTag = true;
                        }


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

                                    if (qtn.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                                        showImageTag = true;
                                    }
                                    else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId) >= 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) >= 0)) {
                                        showImageTag2 = 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 showQtn = ((IsContractSigned == 1) || (IsContractSigned != '1' && qtn.ShowContractNotSigned == '1'))
                        let isDisabled = qtn.isDisabled != null ? qtn.isDisabled : false


                        let EF_qtn = errorfield.EF_qtn != null ? errorfield.EF_qtn : {};
                        let showQtnErrHere = EF_qtn.QuestionId == qtn.QuestionId;

                        let EF_Qtn_MultiChoice = errorfield.EF_Qtn_MultiChoice || '';
                        let EStyle_Qtn_MultiChoice = showQtnErrHere && EF_Qtn_MultiChoice == 'Qtn_MultiChoice' ? customStyle.stk_MultiSSTyle_error : customStyle.wind_MultiSearchInputStyle;


                        let EF_Qtn_Input = errorfield.EF_Qtn_Input || '';
                        let EStyle_Qtn_Input = showQtnErrHere && EF_Qtn_Input == 'Qtn_Input' ? customStyle.stk_inptSTyle_error : {};

                        let EF_Qtn_Image = errorfield.EF_Qtn_Image || '';
                        let EStyle_Qtn_Image = showQtnErrHere && EF_Qtn_Image == 'Qtn_Image' ? customStyle.stk_inptSTyle_error : {};

                        let EF_Qtn_Image2 = errorfield.EF_Qtn_Image2 || '';
                        let EStyle_Qtn_Image2 = showQtnErrHere && EF_Qtn_Image2 == 'Qtn_Image2' ? customStyle.stk_inptSTyle_error : {};



                        if (isDisabled == true || showQtn == false) {
                            return (
                                <View></View>
                            )
                        }
                        else {
                            return (
                                <View style={[customStyle.sform_group2,]} key={index}>
                                    <Text style={[customStyle.sform_label3]}>{qtn.Question}</Text>
                                    {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={EStyle_Qtn_MultiChoice}
                                            submitButtonColor={PageTheme.$primary_color}
                                            submitButtonText="Submit"
                                        />
                                    }
                                    {(qtn.QuestionType == 'Number' || qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Text') &&
                                        <TextInput
                                            ref={(reff) => { inputRefs.current['input1_' + qtn.QuestionId] = reff; }}
                                            style={[customStyle.surveyQtn_InputStyle, EStyle_Qtn_Input]}
                                            placeholder=""
                                            autoComplete='off'
                                            placeholderTextColor={PageTheme.$placeholder_color}
                                            // keyboardType={'ascii-capable'}
                                            returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                                            blurOnSubmit={false}
                                            keyboardType={(qtn.QuestionType == 'Decimal' ? 'decimal-pad' : (qtn.QuestionType == 'Text' ? 'default' : 'number-pad'))}
                                            value={selansid}
                                            onSubmitEditing={() => { focusToNext(qtn, '1') }}
                                            onChangeText={(val) => { setTextValue(val, qtn, (qtn.QuestionType == 'Decimal' ? 'decimal' : (qtn.QuestionType == 'Text' ? 'text' : 'numeric'))) }}
                                        />
                                    }
                                    {
                                        (qtn.QuestionType == 'Date') &&
                                        <View style={[customStyle.surveyQtn_datePicker_con, EStyle_Qtn_Input]}>
                                            <Text style={customStyle.surveyQtn_datePicker_text}>{selansid != '' ? selansid : 'MM/YYYY'}</Text>
                                            <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={() => { setDateValue(selanswer); showQtnDatePicker(qtn, true); setDatePickerValue(qtn, selanswer) }}>
                                                <Fontisto size={20} color={PageTheme.$accent_color} name="date" />
                                            </TouchableOpacity>
                                        </View>
                                    }
                                    {((qtn.showDatePicker == true || qtn.showDatePicker == 'true') && (qtn.QuestionType == 'Date')) &&
                                        renderDatePicker(qtn)
                                    }
                                    {
                                        (qtn.QuestionType == 'Rating') &&
                                        <View style={customStyle.surveyQtn_datePicker_con}>
                                            <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' })]} />
                                            <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_Image2]}>
                                            <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' })]} />
                                            <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 _renderSurveyView() {
        var xpos = IsContractSigned == '1' || IsContractSigned == 1 ? -75 : 0;
        if (animatedChoice != null) {
            xpos = animatedChoice.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -75],
            });
        }

        // 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_NExistReason = errorfield.EF_NExistReason || '';
        let EStyle_NExistReason = EF_NExistReason == 'NExistReason' ? customStyle.stk_inptSTyle_error : {};


        return (
            <View style={customStyle.ContrFormWrap}>
                <View style={[customStyle.openStk_prd_cols, customStyle.mt10]}>
                    <View style={[customStyle.openStk_prd_colflex, customStyle.mb10]}>
                        <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{"Contract Signed?"}</Text>
                        <View style={customStyle.openStk_prd_choiceBoxCon}>
                            <View style={[customStyle.openStk_prd_choiceBox, customStyle.ContrForm_choiceBox]}>
                                <Animated.View style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, (IsContractSigned == '1' || IsContractSigned == 1 ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red),
                                { transform: [{ translateX: xpos }], }]}></Animated.View>
                                <TouchableOpacity style={customStyle.openStkCh_con1} onPress={() => { onChoiceSelect(1) }}>
                                    <Text style={[customStyle.openStkCh_text, (IsContractSigned == '1' || IsContractSigned == 1 ? customStyle.openStkCh_textactive : {})]}>{ST.Yes}</Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(0) }}>
                                    <Text style={[customStyle.openStkCh_text, (IsContractSigned == '0' || IsContractSigned == 0 ? customStyle.openStkCh_textactive : {})]}>{ST.No}</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                    {IsContractSigned != '1' && rerenderdata == rerenderdata &&
                        <View style={[customStyle.openStk_prd_colflex, customStyle.openStk_prd_borderT, customStyle.pt10, customStyle.mb10]}>
                            <Text style={[customStyle.openStk_prd_label, customStyle.openStk_prd_flexlabel]}>{ST.SelectReason}</Text>

                            {<CustomPicker2 {...props} Pickerdata={reasons_list} label_key={'Reason'} value_key={'ReasonId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'} onChange={onselectionChange3} selected_data={{ value: NoContrRsn.Reason }} selectStyle={customStyle.PV_selectStyle} ErrorStyle={EStyle_NExistReason} ShowError={error} />}

                        </View>
                    }
                    {<FlatList
                        style={customStyle.ContrForm_ContentOuter}
                        extraData={rerenderdata}
                        nestedScrollEnabled={true}
                        removeClippedSubviews={false}
                        showsVerticalScrollIndicator={false}
                        contentContainerStyle={customStyle.ContrForm_ContentCon}
                        data={SurveySubCats}
                        renderItem={({ item, index, separators }) => {
                            let subcat = item, s_index = index;

                            return (
                                <View style={customStyle.ContrForm_GroupView} key={s_index}>
                                    <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.Category}</Text>
                                    </LinearGradient>
                                    {_renderSurveyQtns(subcat)}
                                </View>
                            )
                        }}
                    />
                    }
                </View>
            </View>

        );
    }



    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title={"Contract Form"} projectCode={`ST: ${storeData.StoreId}: PROGDef: ${ActiveProgram.ProgramDefinitionId}`} />
            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            <DateTimePickerModal
                isVisible={isDatePickerVisible}
                mode="month"
                display="spinner"
                // date={new Date()}
                date={(DateValueObj?.selanswer != null ? new Date(DateValueObj?.selanswer) : new Date())}
                maximumDate={new Date(DateValueObj?.maxDate)}
                minimumDate={new Date(DateValueObj?.minDate)}
                onConfirm={handleConfirm}
                onCancel={hideDatePicker}
            />
            <CustomCamera cameraType={'back'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | Program Id:' + ActiveProgram.ProgramId + ' | Image Type: Contract Form'} onImageCaptured={(imgData) => { BgShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { BgShowCamera(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.ContrForm_PageWrapper]}>
                    {/* <View style={customStyle.ContrForm_activeP}>
                    <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$gradient1]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.ContrForm_activeP_tile}>
                        <Text style={customStyle.ContrForm_activeP_name}>{`Program : ${ActiveProgram.ProgramName} `}</Text>
                    </LinearGradient>
                </View> */}
                    <View style={customStyle.ContrForm_Hdr}>
                        <Text style={customStyle.ContrForm_HdrText}>{`Program : ${ActiveProgram.ProgramName} `}</Text>
                    </View>
                    {Object.keys(ActiveProgram).length > 0 && rerenderdata == rerenderdata &&
                        _renderSurveyView()
                    }
                    <View style={[customStyle.SVn_SubmitBtn]}>
                        <GradientButton {...props} title={'Save & Upload'} onPress={() => { onSubmitData() }} />
                    </View>
                </View>
            </LinearGradient>
            {showRating == true &&
                renderRatingView()
            }
            {showRecorder == true &&
                renderRecorderView()
            }
        </Container>
    );
}


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