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} from 'react-native';
import { connect  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {marktext1,marktext2} from '../controller/functions';
import {db, common_ImagePath, ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, FontAwesome, FontAwesome5, Fontisto, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector';
import MultiSelect from 'react-native-multiple-select';
import { 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';

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

function Feedback(props) { 
    const route = useRoute();
    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('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [showRating, setShowRating] = useState(false);
    const [RatingQtn, setRatingQtn] = useState({});
    const [RatingOrder, setRatingOrder] = useState([]);
    const [showRecorder, setShowRecorder] = useState(false);
    const [VRS, setVRS] = useState({});
    const [RecorderTimer, setRecorderTimer] = useState({});
    const [playerTimer, setPlayerTimer] = useState({});
    const [rerenderView, setRerenderView] = useState(0);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [VoiceRecorderStatus, setVoiceRecorderStatus] = useState('Press mic to start recording voice');
    const [RecFilePath, setRecFilePath] = useState({});
    const [dateValue, setDateValue] = useState('');
    const [openDatePicker, setOpenDatePicker]= useState(0);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [rerenderdata, setrerenderdata]= useState(0);
    const [SurveySubCats, setSurveySubCats]= useState([]);
    const [SurveyQuestions, setSurveyQuestions]= useState([]);
    const [QuestionsData,setQuestionsData]=useState({});
    const [showAlert, setShowAlert] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    
    const animatedRipple=useRef(new Animated.Value(0)).current;
    const animatedRipple2=useRef(new Animated.Value(0.5)).current;

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
       let params=props.route.params? props.route.params:{};
       let storeData1=params.storeData || {};

       let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
       setStoreCameraAllow(cameraAllow);

       let menu1=params.menu || {};
       let isAdhoc=params.isAdhocScreen || false;
       setStoreData(storeData1);
       setCurrentMenu(menu1);
       setIsAdhocScreen(isAdhoc);
      
       
       getSurveyData(storeData1,menu1);
       const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
       return (()=>{
            audioRecorderPlayer.removePlayBackListener();
            audioRecorderPlayer.removeRecordBackListener();
            return unsubscribe;
       });
    }, []);

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]);   
    
    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }

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

    async function getSurveyData(storeData1,menu1){ 
        try {   ;
            
            await db.transaction(async function (txn) { 

              let q2=`SELECT DISTINCT FeedbackCategory as Category,FeedbackCategoryId as CategoryId FROM Master_FeedbackQuestion order by FeedbackQuestionSequence `;
              await txn.executeSql(q2,[],async function (txn2, txnres) { 
                  console.log('feedback cats:',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(storeData1,data,menu1)
                          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(storeData1,cat,menu1){
        
        return new Promise((resolve,reject)=>{
            try {   
                let {StoreId}=storeData1;
                
                db.transaction(async function (txn) {  
                  
                  // get inserted audit
                  let selectlist=` DISTINCT T.FeedbackCategoryId as CategoryId,T.FeedbackCategory as Category,T.FeedbackQuestionId as QuestionId,T.FeedbackQuestionCode as QuestionCode,T.FeedbackQuestionName as Question,T.QuestionType,T.FQShowCamera,T.FQCameraMandatory,T.FQLengthValidationRequired,T.FQMinimumChar,T.FQMaximumChar,T.FQDecimalPoint,T.FQDateRangeMin,T.FQDateRangeMax,T.FQVoiceLengthInMinutes,T.FQDefaultQuestionEnable,T.FeedbackQuestionSequence,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.MULTI_OPTIONS_IDS as multi_op_ids,T1.IS_DISABLED as isDisabled `;
                  let join=` INNER JOIN ${AppTables.FEEDBACK_DATA} T1 on T.FeedbackQuestionId=T1.QUESTION_ID and T.FeedbackCategoryId=T1.CATEGORY_ID`;
                  let q2=`Select ${selectlist} FROM Master_FeedbackQuestion T ${join} WHERE T1.STORE_ID='${StoreId}' AND T1.VISIT_DATE= '${d2}' and T.FeedbackCategoryId='${cat.CategoryId}'  ORDER BY T.FeedbackQuestionSequence  `;
                 
      
                  await txn.executeSql(q2,[],async function (txn2, txnres) { 
                      console.log('fb data len',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);
                              let answers=[];
                              let qtn=data;
                              qtn.isDisabled=qtn.isDisabled==1 || qtn.isDisabled=='1'?true:false
                            //   qtn.FQShowCamera='true';
                              
                              if(data.QuestionType=='Multi choice list' || data.QuestionType=='Single choice list' || data.QuestionType=='Rating'){
                                  let allanswers=await getAnswers(data,storeData1);
                                  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.FQShowCamera==true || data.FQShowCamera=='true' || data.FQShowCamera==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=(Platform.OS=='ios'?'file://':'')+`${ImageFolderPath+menu1.ScreenName}/`+data.Image1;
                                  QD[imgname_key]=data.Image1;
                                  QD[img_key]=imgPath;
                              }

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

                              
      
                              if(qtn.QuestionType=='Audio'){
                                  let voicefile_path=(Platform.OS=='ios'?'file://':'')+`${ImageFolderPath+menu1.ScreenName}/`+'Recordings/'+data.Answer;
                                  QD[voiceClip_key]={'path':voicefile_path,'filename':data.Answer};
                              }
      
                              if(qtn.QuestionType=='Date'){
                                  let dayonly=moment().format('DD');
                                  let actual_date=data.Answer?data.Answer.split('/'):[];
                                  let month=actual_date[0],year=actual_date[1];
                                  let fulldate=month+'/'+dayonly+'/'+year;
                                  QD[date_key]=fulldate;
                                  
                              }
                              arr.push(data);  
                              if(i==txnres.rows.length-1){
                                  setQuestionsData(QD);
                                  resolve(arr);
                              }
                          }
                      }
                      else{
                        let sl=` DISTINCT T.FeedbackCategoryId as CategoryId,T.FeedbackCategory as Category,T.FeedbackQuestionId as QuestionId,T.FeedbackQuestionCode as QuestionCode,T.FeedbackQuestionName as Question,T.QuestionType,T.FQShowCamera,T.FQCameraMandatory,T.FQLengthValidationRequired,T.FQMinimumChar,T.FQMaximumChar,T.FQDecimalPoint,T.FQDateRangeMin,T.FQDateRangeMax,T.FQVoiceLengthInMinutes,T.FQDefaultQuestionEnable,T.FeedbackQuestionSequence`;
                        let q=` SELECT ${sl} FROM Master_FeedbackQuestion T WHERE T.FeedbackCategoryId='${cat.CategoryId}' order by T.FeedbackQuestionSequence  `; 
                        await txn.executeSql(q,[],async function (txn2, txnres2) { 
                              console.log('fb qtns:',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);
                                      let answers=[];
                                    //   data.FQShowCamera='true';
                                      if(data.QuestionType=='Multi choice list' || data.QuestionType=='Single choice list' || data.QuestionType=='Rating'){
                                          let allanswers=await getAnswers(data,storeData1);
                                          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){
       
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {   
                // get inserted audit
                let selectlist=` DISTINCT T.FeedbackAnswerId as AnswerId,T.FeedbackAnswerCode as AnswerCode,T.FeedbackAnswerName as Answer,T.FAShowCamera as ImageAllow1,T.FAQuestionEnable as EnableQuestion,T.FAQuestionDisable as DisableQuestion`;
                let q2=`Select ${selectlist} FROM Master_FeedbackQuestion T WHERE T.FeedbackQuestionId='${qtn.QuestionId}' ORDER BY T.FASequence `;
                
                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);
                            // if(data.AnswerId=='1' || data.AnswerId=='4'){
                                // data.ImageAllow1='true';
                            // }
                            
                            arr.push(data);
                            if(i==txnres.rows.length-1){
                                resolve(arr);
                            }
                        }
                    }
                    else{
                        resolve([]);
                    }
                },function (txnE,txnerr) { console.log(txnerr);resolve([]); },);
               
              });    
        }).then((val)=>{
            return {'Answers':val,'Success':true};
        }).catch((err)=>{
            console.log(err);
            return {'Success':false,'Error':err}
        });
    }

    async function getImage(imgdata){
        let qtn=getImageProps.qtn || '';
        let type=getImageProps.type || '1';
        if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
            notify('Camera unavailable');
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl=img.uri, imgWidth=img.width, imgHeight=img.height;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==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;
            
            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | Question Id :'+qtn.QuestionId+' | Image Type: Feedback'+' | Date:'+calculate_tym_date_over_img;
        
            await marktext1(mark_text1,imgurl)
            .then((res)=>{
                if(res.success){
                    let uri=res.uri;
                    marktext2(mark_text2,uri,imgWidth,imgHeight)
                    .then((res)=>{
                        if(res.success){
                            let filename=storeData.StoreId+'_'+qtn.QuestionId+'_FeedbackImg_'+calculate_tym_date_for_filename+'.jpg';
                            let qd=QuestionsData;
                            let img_key=type=='1'?qtn.QuestionId+'_ImagePath1':qtn.QuestionId+'_ImagePath2';
                            let imgname_key=type=='1'?qtn.QuestionId+'_ImageName1':qtn.QuestionId+'_ImageName2';
                            qd[imgname_key]=filename;
                            
                            // renamefile
                            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri='file://'+imagePath;
                                console.log('image marker',uri);
                                qd[img_key]=uri; 

                                setQuestionsData(qd);
                                setHasUnsavedChanges(true);
                                setrerenderdata(!rerenderdata);
                            })
                            .catch(err => {
                                console.log('ERROR: image file write failed!!!');
                                console.log(err.message, err.code);
                            });                           
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify('Please capture a image');
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify('Please capture a image');
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }
  
    async function openCamera(qtn,type){  
        setGetImageProps({'qtn':qtn,'type':type}); 
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

    async function disableQtns(sqtns,DQtns,data,isreturn=false){
        if(DQtns.length>0){
            new Promise.all(
                DQtns.map((qid,q_index)=>{
                    let s_qtnindex=sqtns.findIndex(i=>i.QuestionId==qid) || {};
                    let s_qtn=sqtns[s_qtnindex];
                    if(s_qtn!=null){
                        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
                    }else{
                        return false
                    }
                })
            ).then(async (val)=>{
                setSurveyQuestions(sqtns);
                setQuestionsData(data);
                setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);
            })
        }
    }

    async function enableQtns(sqtns,EQtns,DQtns,data){
        new Promise.all(
            EQtns.map((qid,q_index)=>{
                let s_qtnindex=sqtns.findIndex(i=>i.QuestionId==qid) || {};
                let s_qtn=sqtns[s_qtnindex];
                if(s_qtn!=null){
                    s_qtn['isDisabled']=false
                    sqtns[s_qtnindex]=s_qtn;
                    return false
                }else{
                    return false
                }
            })
        ).then(async (val)=>{
            if(DQtns.length>0){
                disableQtns(sqtns,DQtns,data)
            }
            else{
                setSurveyQuestions(sqtns);
                setHasUnsavedChanges(true);
                setrerenderdata(!rerenderdata);
            }
        })
    }
   
    function onselectionChange(option,qtn){
        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);

        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(','):[];
      
        let sqtns=SurveyQuestions
        if(EQtns.length>0){
            enableQtns(sqtns,EQtns,DQtns,data)
        }
        else if(DQtns.length>0){
            disableQtns(sqtns,DQtns,data)
        }
        else{
            setHasUnsavedChanges(true);
            setrerenderdata(!rerenderdata);
        }
       
        
        
    }

    function setTextValue(value,qtn) {        
        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);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function setRatingValue(data){
        // let ids=[];
        // data.map((item,index)=>{
        //     ids.push(item.AnswerId);
        // })
        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);
        setHasUnsavedChanges(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);
            if(show==true) setrerenderdata(!rerenderdata);
        }
    }

    
    function setShowQtnKey(qtn,key,show=false){
        if(key!=null && key!=''){
            let newqtnIndex=SurveyQuestions.findIndex(q=>q.QuestionId==qtn.QuestionId);
            console.log('setShowQtnKey:',newqtnIndex);
            if(newqtnIndex>=0){
                let sq=SurveyQuestions;
                let newqtn=sq[newqtnIndex];
                newqtn[key]=show;
                sq[newqtnIndex]=newqtn;
                setSurveyQuestions(sq);
                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);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function onRecordCancel(){
        setShowRecorder(false);
    }
    
    function onRecordSave(){

        let isRecorderPlaying=VRS.RecorderPlayStatus!=null && VRS.RecorderPlayStatus==true;
        let isPlayerPlaying=VRS.PlayerPlayStatus!=null && VRS.PlayerPlayStatus==true;

        if(isRecorderPlaying){
            notify('Please stop recording first');
            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);
        setHasUnsavedChanges(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,vrStatus) => {
        try{
            console.log('startRecorder')
            if(audioRecorderPlayer!=null){

                if(vrStatus['RecorderPlayStatus']==true){
                    notify('Already Recording...')
                    return;
                }
                else if(vrStatus['PlayerPlayStatus']==true){
                    notify('Please stop player first!')
                    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+'_'+qtn.QuestionId+'_FeedbackRecording_'+picture_clicked_date+'_'+picture_clicked_time;
                let filename=Platform.OS=='ios'?commname+'.m4a':commname+'.mp3';
                            
                const url=Platform.OS=='ios'?'file://'+`${ImageFolderPath+currentMenu.ScreenName}/`+'Recordings/'+filename:`${ImageFolderPath+currentMenu.ScreenName}/`+'Recordings/'+filename;
                const url_dir=`${ImageFolderPath+currentMenu.ScreenName}/`+'Recordings/';
                console.log('write file url:',url);
                RNFS.mkdir(url_dir).then((res)=>{
                   
                    RNFS.writeFile(url, '')
                    .then(async (success) => {
                        // if(success!=null){
                            const path = Platform.select({
                                ios: url,
                                android: url,
                            });
        
                            const result = await audioRecorderPlayer.startRecorder(path,AudioSet);
                        
                            if(result!=null && result!=''){
                                console.log('start recording now');
                                vrStatus['RecorderPlayStatus']=true;
                                setVRS(vrStatus);
                                setRecFilePath({'path':url,'filename':filename});
                                // animate
                                RippleAnimation(animatedRipple,0,1,0);
                                RippleAnimation(animatedRipple2,0,1,100);
                                
                                audioRecorderPlayer.addRecordBackListener((e) => {
                                    let recordsec=e.currentPosition;
                                    let data={'recordSecs':recordsec,'recordTime':audioRecorderPlayer.mmssss(Math.floor(recordsec))};
                                    if(vrStatus['RecorderPlayStatus']==true)
                                    {
                                        setRecorderTimer(data);
                                        setHasUnsavedChanges(true);
                                        setVoiceRecorderStatus('Recording... ! Press mic to stop recording');
                                    }
                                    
                                    console.log('recordsec:',recordsec);
                                    if(recordsec>=60*1000){
                                        stopRecorder(vrStatus);
                                        notify('Maximum record time limit reached.','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('Something Went Wrong! Cannot open file for recording!');
                    });
                })
                .catch((err) => {
                    console.log('eerriur2',err.message);
                    notify('Something Went Wrong! Cannot open file for recording!');
                });   
                
            }
        }
        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('Press mic to start recording voice');
            }
        }
        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('Already Playing...')
                    return;
                }
                else if(vrStatus['RecorderPlayStatus']==true){
                    notify('Please stop recording first!')
                    return;
                }
                else if(url=='' || url==null){
                    notify('File not found!')
                    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('Loading...');
            setProcessing(true);
            await startPlayer(url,VRS,'1');
        }
        setRecFilePath((QuestionsData[voiceClip_key] || {}));
        setShowRecorder(true);
    }

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

    function onSaveCancel(){
        setShowAlert(false);
    }

    async function saveData(){
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            await db.transaction(async function (txn) {   
            
                //  remove old data
                let q=`DELETE FROM ${AppTables.FEEDBACK_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    console.log('fb data deleted');
                },function (txnE,txnerr) { console.log(txnerr); },);

              
                var values='';
                for(var i=0;i<SurveyQuestions.length;i++){
                    values+=values!=''?' , ':'';

                    let qtn=SurveyQuestions[i];
                    
                    let id_key=qtn.QuestionId+'_AnswerId'; 
                    let ans_key=qtn.QuestionId+'_Answer'; 
                    let multi_key=qtn.QuestionId+'_MultiOption';
                    let date_key=qtn.QuestionId+'_Date';
                    let img_key1=qtn.QuestionId+'_ImagePath1';
                    let imgname_key1=qtn.QuestionId+'_ImageName1';
                    let rating_key=qtn.QuestionId+'_Rating'; 
                    let voiceClip_key=qtn.QuestionId+'_VoiceClip'; 

                    let {CategoryId,QuestionCode,Question,QuestionId,QuestionType,FQShowCamera}=qtn;
                    
                    let selansid=QuestionsData[id_key] || 0;
                    let selans=QuestionsData[ans_key] || '';
                    let imgName1=QuestionsData[imgname_key1] || '';
                    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 showImageTag=false;

                    let imgallow1=ans_obj!=null && ans_obj['ImageAllow1']!=null?ans_obj.ImageAllow1:false;
                    let f_imgalloq1=(FQShowCamera=='true' || FQShowCamera==1) || (imgallow1=='true' || imgallow1==1)
                    
                    values+=` ('${StoreId}','${d2}','${CategoryId}','${QuestionCode}','${QuestionId}','${QuestionType}','${selans}','${selansid}','${f_imgalloq1}','${imgName1}','${multiops}','${isQtnDisabled}','${d2}') `;
                }
                
              
                let add_data=`INSERT INTO ${AppTables.FEEDBACK_DATA} (STORE_ID,VISIT_DATE,CATEGORY_ID,QUESTION_CODE,QUESTION_ID,QUESTION_TYPE,ANSWER,ANSWER_ID,IMAGE_ALLOW1,IMAGE1,MULTI_OPTIONS_IDS,IS_DISABLED,ADDED_DATE) VALUES ${values} `;
             
                await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                    console.log('surveys added');
                    // props.set_autoback({'AutoGoToPrev':true});
                    notify('Survey updated successfully','SHORT');
                    setProcessing(false);
                    props.navigation.goBack();
                
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot update survey') },);
              
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function validate(){  
        var isvalid=true;
        const QD=QuestionsData;
        console.log(SurveyQuestions.length);
        for(var i=0;i<SurveyQuestions.length;i++){
            let qtn=SurveyQuestions[i];
            let selansid='',selanswer='',selimg='',showImageTag=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 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=='Number' || qtn.QuestionType=='Text' || qtn.QuestionType=='Decimal' || qtn.QuestionType=='Date')
            {
                showImageTag=(qtn.FQShowCamera=='true' || qtn.FQShowCamera==1);
            }
            else 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==1);
                        
                        if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                            showImageTag=true;
                        }
                        else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && selansid.findIndex(i=> i==ansss.AnswerId)>=0)){
                            showImageTag=true;
                        } 
                    }
                }
            }
              
            console.log('showImageTag',showImageTag,QD[img_key]);
           
            if(qtn.QuestionType=='Multi choice list' && selansid.length<=0){
                isvalid=false;
                notify('Please select options for the required field','SHORT');
                break;
            }
            else if( checkForAnsKey && (Object.keys(QD).indexOf(ans_key)<0 || (Object.keys(QD).indexOf(ans_key)>=0 && QD[ans_key]===''))){
                console.log('test1');
                isvalid=false;
                let msg=( qtn.QuestionType=='Date'?'Please pick a date':(qtn.QuestionType=='Rating'?'Please select rating':'Please fill all details'));
                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=='')))){
                isvalid=false;
                notify('Please record audio clip for the required field','SHORT');
                break;
            }
            else if(Object.keys(QD).indexOf(id_key)<0 || (Object.keys(QD).indexOf(id_key)>=0 && (QD[id_key]==='' || (QD[id_key]===0 && qtn.isDisabled===true) ))){
               
                isvalid=false;
                notify('Please fill all details','SHORT');
                break;
            }
            else if( StoreCameraAllow &&  showImageTag && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                isvalid=false;
                notify('Please add images','SHORT');
                break;
            }else{
                console.log('no condition found');
            }
            
        } 
        
        return isvalid;
    }
   
    function render_Picker(label_key,value_key,onChange=()=>{},selected_data={}){
        var data=[];
        let qtn=selected_data.qtn || {};
        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}
            >
            <Text style={[customStyle.addVisPicker_InputStyle,(isQtnDisabled?customStyle.addVisPicker_Dis_InputStyle:{})]}>{(selected_data.value!=null && selected_data.value!=''?selected_data.value: '-select-')}</Text>
            </ModalSelector>
        )
    }

    function renderDatePicker(qtn){
        let qtnn=qtn;
        let DateRange=qtn.DateRange;
        let maxDate=moment().add(10,'years').format('MM/DD/YYYY');
        let minDate=moment().subtract(10,'years').format('MM/DD/YYYY');
        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 ratings=QuestionsData[rating_key]!=null?QuestionsData[rating_key].split(','):[];
        
        let newarr=RatingOrder;
        if(RatingOrder.length<=0){
            newarr=Answers;
        }

        return (
        <View style={customStyle.RatingModal}>
            <View style={customStyle.RatingModalCon}>
                <Text style={customStyle.VRModalHeding}>Drag Items In Order</Text>
                <Text style={customStyle.VRSubHeding}>Press and hold to drag</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}>Cancel</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={()=>{onRatingSave()}}>
                        <Text style={customStyle.RModal_BtnTextsave}>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}>Record Voice Clip</Text>
                <Text style={customStyle.VRSubHeding2}>You can record max for 60 secs</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,VRS);  }}>
                            <FontAwesome size={30} color={PageTheme.$accent_color} name="microphone"/>
                        </TouchableOpacity>
                        {isRecorderPlaying && 
                        <TouchableOpacity activeOpacity={1} style={customStyle.VoiceRecorderStopBtn} onPress={()=>{stopRecorder(VRS);  }}>
                            <FontAwesome5 size={30} color={PageTheme.$accent_color} name="microphone-alt"/>
                        </TouchableOpacity>
                        }
                        
                    </View>
                    <View style={customStyle.VoiceRecordedView}>
                            <Text style={customStyle.VoiceRecorderTimer}>{RecorderTimer.recordTime}</Text>
                            {
                                (!isRecorderPlaying && RecFilePath.filename!=null && RecFilePath.filename!='') &&
                                <View style={customStyle.VRPlayBack}>
                                    <View style={customStyle.VRPlayBackBarView}>
                                        <View style={customStyle.VRPlayBackBar}>
                                            <View style={customStyle.VRPlayBackBarBg}></View>
                                            <View style={[customStyle.VRPlayBackBarFilled,{width:width1}]}></View>
                                        </View>
                                        <Text style={customStyle.VRPlayBackTimer}>{`${(playerTimer.playTime || '00:00:00')} / ${playerTimer.playDuration || RecorderTimer.recordTime}`}</Text>
                                    </View>
                                    
                                    <View style={customStyle.VRPlayBackControls}>
                                        <TouchableOpacity activeOpacity={1} style={customStyle.VRPB_Play} onPress={()=>{let url=(Platform.OS=='ios'?'file://':'')+`${ImageFolderPath+currentMenu.ScreenName}/`+'Recordings/'+RecFilePath.filename; (wp<100 && wp>0)? resumePlayer(url):startPlayer(url,VRS); }}>
                                            <Entypo size={24} color={PageTheme.$accent_color} name="controller-play"/>
                                        </TouchableOpacity>
                                        {isPlayerPlaying && <TouchableOpacity activeOpacity={1} style={customStyle.VRPB_Pause} onPress={()=>{ wp<100?pausePlayer():stopPlayer(VRS); }}>
                                            <Entypo size={24} color={PageTheme.$accent_color} name="controller-paus"/>
                                        </TouchableOpacity>}
                                    </View>
                                </View>
                            }
                        </View>
                </View>
                <View style={customStyle.RModal_Btns}>
                    <TouchableOpacity style={customStyle.RModal_BtnCancel} onPress={()=>{onRecordCancel()}}>
                        <Text style={customStyle.RModal_BtnTextCancel}>Cancel</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={()=>{onRecordSave()}}>
                        <Text style={customStyle.RModal_BtnTextsave}>Save</Text>
                    </TouchableOpacity>
                </View>
            </View>}
        </View>
        )
    }
    
    function _renderSurveyQtns(cat){
        const SurveyQuestions=cat.Questions;
        return (
        <View style={customStyle.SVn_GroupViewList}>
            {
                SurveyQuestions.length>0 && 
                SurveyQuestions.map((item,index)=>{
                    
                    let qtn=item;  
                    let selansid='',selanswer='',selimg='',showImageTag=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.FQShowCamera=='true' || qtn.FQShowCamera==1);
                    }
                    else if(qtn.QuestionType=='Rating'){
                        selanswer=QuestionsData[ans_key]?QuestionsData[ans_key]:'';
                    }
                    else if(qtn.QuestionType=='Audio'){
                        selansid=QuestionsData[ans_key]?QuestionsData[ans_key]:'';
                        selanswer=QuestionsData[voiceClip_key]?(QuestionsData[voiceClip_key].filename || ''):'';
                    }

                    if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                        if (qtn.Answers && qtn.Answers.length>0){
                            for(var i=0;i<qtn.Answers.length;i++){
                                let ansss=qtn.Answers[i];
                                let isandImgAl=(ansss.ImageAllow1=='true' || ansss.ImageAllow1==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(showImageTag){
                        selimg=QuestionsData[img_key]!=null && QuestionsData[img_key]!=''?'file://'+QuestionsData[img_key]:'';                    
                    }
                    
                    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})
                        }
                        {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}
                                itemTextColor={PageTheme.$text_color}
                                displayKey="Answer"
                                searchInputStyle={{ color: '#CCC' }}
                                submitButtonColor={PageTheme.$primary_color}
                                submitButtonText="Submit"
                            />
                        }
                        { (qtn.QuestionType=='Number' || qtn.QuestionType=='Decimal'  || qtn.QuestionType=='Text') &&  
                            <TextInput 
                                style={[customStyle.surveyQtn_InputStyle]}
                                placeholder=""
                                autoComplete='off'
                                placeholderTextColor={PageTheme.$placeholder_color} 
                                // keyboardType={'ascii-capable'}
                                keyboardType={(qtn.QuestionType=='Decimal'?'decimal-pad':(qtn.QuestionType=='Text'?'default':'number-pad'))}
                                value={selansid}
                                onChangeText={(val)=>{setTextValue(val,qtn)}}
                            />
                        }
                        {
                            (qtn.QuestionType=='Date') && 
                            <View style={customStyle.surveyQtn_datePicker_con}>
                                <Text style={customStyle.surveyQtn_datePicker_text}>{selansid!=''?selansid:'MM/YYYY'}</Text>
                                <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={()=>{setDateValue(selanswer);showQtnDatePicker(qtn,true)}}>
                                    <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,]}>                    
                                <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>
                        }

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

   
    function _renderSurveyView(){
        return (
            <View style={customStyle.SVn_ContentCon}>
            <FlatList 
            style={customStyle.SVn_ContentOuter} 
            extraData={rerenderdata}
            nestedScrollEnabled={true}
            removeClippedSubviews={false}
            showsVerticalScrollIndicator={false}     
            contentContainerStyle={customStyle.SVn_ContentInner}
            data={SurveySubCats}
            renderItem={({ item, index, separators }) =>{  
                let cat=item,s_index=index;
                
                return (
                    <View style={customStyle.FeedbVn_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}>{cat.Category}</Text>
                        </LinearGradient>
                        { _renderSurveyQtns(cat)}
                    </View>
                )
            }}
            >
                
            </FlatList>
            </View>
        );
    }

    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props}showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <CustomCamera cameraType={'back'} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper,customStyle.roundScrollZIndex]}>
            <View style={[customStyle.pageContentWrapper]}>
                {     
                    _renderSurveyView()
                }
                <View style={[customStyle.SVn_SubmitBtn]}>
                    <GradientButton {...props} title={'Save'} onPress={()=>{onSubmitData()}}/> 
                </View> 
            </View>  
        </LinearGradient> 
        {   showRating==true && 
            renderRatingView()
        }
        { showRecorder==true && 
            renderRecorderView()
        }
      </Container>   
    ); 
  }
  

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