import React, { useState, useEffect, memo, useRef, useCallback, useMemo } from 'react';
import { useRoute } from '@react-navigation/native';
import { View, Text, TouchableOpacity, Image, FlatList, Platform, ScrollView, TextInput } from 'react-native';
import { connect } from 'react-redux';
import moment from 'moment';
import Container from '../components/container';
import CustomLoader from '../components/CustomLoader';
import CustomHeader from '../components/customHeader';
import NoDataComponent from '../components/NoDataComponent';
import LinearGradient from 'react-native-linear-gradient';
import { get_item } from '../components/localStorage';
import { notify } from '../components/notify';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { getDownloadJson1, UploadData } from '../controller/functions';
import { METHODS, getMethodName } from '../constants/methodNames';
import { SvgXml } from 'react-native-svg';
import { AppTables } from '../constants/tableConstants';
import CheckBox from '@react-native-community/checkbox';
import { mapDispatchToProps, mapStateToProps } from '../reducers/contextProvider';
import { db } from '../constants/constants';
import Animated from 'react-native-reanimated';
import ImageViewer from 'react-native-image-zoom-viewer';
import { Entypo, Fontisto, MaterialCommunityIcons } from '../components/icons';
import MultiSelect from 'react-native-multiple-select';
import ModalSelector from 'react-native-modal-selector';
import { PrimaryTheme } from '../styles/Themes';
import GradientButton from '../components/gradientButton';
import { ConfirmSaveAlert } from '../components/alert';


const ImageAudit = (props) => {
  const route = useRoute();
  const { DarkMode, baseurl, StaticText: ST = {} } = props;
  const PageTheme = GetPageTheme(DarkMode, route.name);
  const customStyle = customStyles(DarkMode, route.name);

  const timerRef = useRef(null);

  const [processing, setProcessing] = useState(false);
  const [loaderTitle, setLoaderTitle] = useState();
  const [isDataFound, setIsDataFound] = useState(false);
  const [rerenderdata, setrerenderdata]= useState(0);
  const [rerenderdata1, setrerenderdata1]= useState(true);

  const storeData = route?.params?.imageauditstoreData;
  let selectedDate =  route?.params?.selectedDate ;
  selectedDate = moment(selectedDate).format('MM/DD/YYYY');

  console.log("selectedDate", selectedDate) ;

  // console.log(storeData?.MID, "MIDDD")

  const [dataInfo , setDataInfo] = useState([]);

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

  const [SurveyQuestions, setSurveyQuestions]= useState([]);
  const [QuestionsData,setQuestionsData]=useState({});
  const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
  const [showAlert, setShowAlert] = useState(false);



  // zoom image 

  const zoomView=useRef(null);
  const Show_zoomImageRef=useRef(false);
  const [show_zoomImage, setShow_zoomImage] = useState(false);
  const [zoomImageUrl, setZoomImageUrl] = useState([]);
  const [refImageIndex, setrefImageIndex] = useState(0);


  function UpdateShow_zoomImageRef(val) {
    Show_zoomImageRef.current = val;
    setShow_zoomImage(val);
  }


  useEffect(() => {
    let params=props.route.params? props.route.params:{};
    let storeData1=params.storeData || {};
    // setStoreData(storeData1);

    setLoaderTitle(ST.Loading +'...');
    if(selectedDate != null &&  selectedDate != undefined){
      console.log("Anitaaa")
      getDataselectedDate();
    } else {
     get_data();
    }
 }, []);

 const _renderHeader = useCallback((currentIndex) => {
  return (
    <View style={customStyle.album_ZOOM_topBar}>
      <Text style={customStyle.album_ZOOM_indicator}>{`${(currentIndex + 1)}/${zoomImageUrl.length}`}</Text>
      <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={() => UpdateShow_zoomImageRef(false)}>
        <Entypo name='chevron-left' color={'#000'} size={24} />
      </TouchableOpacity>
    </View>
  );
}, [zoomImageUrl.length, customStyle.album_ZOOM_topBar, customStyle.album_ZOOM_indicator, customStyle.album_ZOOM_backBtn]);


// date wise
  // async function getDataselectedDate(){ 
  //   setProcessing(true)   
  //   try {
      
  //     let allImageAuditStoreImageData= await DownloadImageAuditImageList();
  //     console.log('allImageAuditStoreImageData-------------------',allImageAuditStoreImageData);
  //     if(allImageAuditStoreImageData?.length>0){
  //         console.log("allImageAuditStoreImageData--",allImageAuditStoreImageData)
  //         setProcessing(false);
  //     }
  //     else{
  //         notify(ST.Nodatafound);
  //         setProcessing(false);
  //     }

  //   } catch (err) {
  //     setProcessing(false);
  //     console.log(err);          
  //   }        
  // }

  async function getDataselectedDate() { 

    setProcessing(true);   
    try {
        let allImageAuditStoreImageData = await DownloadImageAuditImageList();
        console.log('allImageAuditStoreImageData:', allImageAuditStoreImageData);

        if (allImageAuditStoreImageData?.length > 0) {
            await InsertDownloadImageKPIData(allImageAuditStoreImageData);
            // Fetch the updated local data
            get_data();
        } else {
            notify(ST.Nodatafound);
        }
    } catch (err) {
        console.log(err);
    } finally {
        setProcessing(false);
    }
}

  async function InsertDownloadImageKPIData(imageKPIArr){
        console.log("insert download posSale called");
        return new Promise((resolve,reject)=>{
          
          var values=[],sql_stmnt='',all_vals='';
          let d1=new Date();
          let tbname='Sup_ImageAuditKPIImages';
          let storeId = storeData.StoreId;
          let MID = storeData.MID;
          let q=`Delete from ${tbname} where MID='${MID}' `;

          imageKPIArr = imageKPIArr ? imageKPIArr : [];

          console.log("imageKPIArr", imageKPIArr)
          
          imageKPIArr?.map((data_obj)=>{  
            let {MID ,MenuId,Menu,KPIImageId,QuestionImageId,DefId,DefName,BaseUrl,ImageName,Image1,Image2}=data_obj;
            values.push(` ('${MID || ''}', '${MenuId || ''}', '${Menu || ''}', '${KPIImageId || ''}','${QuestionImageId || ''}', '${DefId || ''}', '${DefName || ''}', '${BaseUrl || ''}','${ImageName || ''}', '${Image1 || ''}', '${Image2 || ''}')`);
          });
          all_vals=values.join(',');
          sql_stmnt=`INSERT INTO ${tbname}(MID,MenuId,Menu,KPIImageId,QuestionImageId,DefId,DefName,BaseUrl,ImageName,Image1,Image2) 
          values ${all_vals}`;
  
          db.transaction(async function (txn) { 
            await txn.executeSql(q,[],async function (txn2, txnres4) {
              console.log('removeddata'); 
              await txn.executeSql(sql_stmnt,[],async function (txn2, txnres2) { 
                resolve(true);
              },function(txn2,txnerr){ console.log(txnerr);resolve(false);});
            },function(txn2,txnerr){console.log(txnerr);resolve(false);});
          })
      }).catch((err)=>{
          console.log(err);
          return false;
        })
      
      }

  
  async function DownloadImageAuditImageList(){
      let downloadKey="Sup_ImageAuditKPIImages";
      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      const url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
      let data={
        Downloadtype:downloadKey,
        Username: loginDetails.UserId,
        Param1: selectedDate,
        Param2: '',
      };

      console.log(url,data);
      return await getDownloadJson1(url,data)
      .then(async(res)=>{  
        if (res[downloadKey]) {
          let data_arr = res[downloadKey] || []; 
          return data_arr;
        }
        else{
          return [];
        }        
      })
      .catch((err)=>{
        console.log('onPage Image Audit error',err);
        return [];
      }); 
  }

// end 

async function get_data() {
  setProcessing(true);

  let mainQuery = `SELECT DISTINCT MenuId, MID, Menu FROM Sup_ImageAuditKPIImages WHERE MID = '${storeData?.MID}'`;
  console.log("mainQuery", mainQuery);

  let fetchedData = []; // Declare fetchedData outside the loop

  try {
      db.transaction(async tx => {
          tx.executeSql(
              mainQuery,
              [],
              (tx, results) => {
                  let rows = results.rows;

                  // Loop through the results of the main query
                  let promises = [];
                  for (let i = 0; i < rows.length; i++) {
                      let item = rows.item(i);

                      // Define the defQuery based on MenuId
                      let defQuery = `SELECT DISTINCT DefName, DefId, MID ,MenuId  FROM Sup_ImageAuditKPIImages WHERE MID = '${item.MID}' AND MenuId = '${item.MenuId}'`;
                      console.log("defQuery---", defQuery);

                      // Execute the defQuery within the loop
                      promises.push(new Promise((resolve, reject) => {
                          tx.executeSql(
                              defQuery,
                              [],
                              (tx, defResults) => {
                                  let defRows = defResults.rows;
                                  let defArray = [];

                                  // Loop through the results of the defQuery
                                  let defPromises = [];
                                  for (let j = 0; j < defRows.length; j++) {
                                      let defItem = defRows.item(j);

                                      console.log("defItem---------", defItem);

                                      // Define the imageQuery based on DefId


                                     let selectlist = ` DISTINCT S.KPIImageId, S.QuestionImageId, S.DefId, S.DefName, S.BaseUrl, S.ImageName, S.Image1, S.Image2, IFNULL(T.pictureokay, 0) AS pictureokay, IFNULL(T.pictureokay2, 0) AS pictureokay2`;

                                    let join2 = ` LEFT JOIN (SELECT * FROM IMAGE_AUDIT_HDR_DATA WHERE DefId = '${defItem.DefId}' AND MID = '${defItem.MID}' AND MenuId = '${defItem.MenuId}') AS T ON T.DefId = S.DefId and T.QuestionImageId = S.QuestionImageId`;

                                    let imageQuery = `SELECT ${selectlist} FROM Sup_ImageAuditKPIImages S ${join2} WHERE S.DefId = '${defItem.DefId}' AND S.MID = '${defItem.MID}' `;

                                      // let imageQuery = `SELECT DISTINCT KPIImageId, QuestionImageId, DefId, DefName, BaseUrl, ImageName, Image1, Image2 FROM Sup_ImageAuditKPIImages WHERE DefId = '${defItem.DefId}' AND MID = '${defItem.MID}'`;
                                     
                                      console.log("imageQuery---", imageQuery);

                                      // Execute the imageQuery within the loop
                                      defPromises.push(new Promise((resolve, reject) => {
                                          tx.executeSql(
                                              imageQuery,
                                              [],
                                              async (tx, imageResults) => {
                                                  let imageRows = imageResults.rows;
                                                  let images1Array = [];
                                                  let images2Array = [];

                                                  // Loop through the results of the imageQuery
                                                  for (let k = 0; k < imageRows.length; k++) {
                                                      let imageItem = imageRows.item(k);

                                                      // console.log(imageItem,"imageItemimageItem--------")

                                                      let all_scat_qtns =[] ; //await getSurveyQtns(item);
                                                      // console.log('all_scat_qtns:', all_scat_qtns.length);
                                                      imageItem['Questions'] = all_scat_qtns;

                                                      let pictureOkayValue = imageItem.pictureokay;
                                                      let pictureOkayValue2 = imageItem.pictureokay2;

                                                      let statusValue = imageItem.STATUS;

                                                      images1Array.push({
                                                          KPIImageId: imageItem.KPIImageId,
                                                          QuestionImageId: imageItem.QuestionImageId,
                                                          BaseUrl: imageItem.BaseUrl,
                                                          ImageName: imageItem.ImageName,
                                                          pictureokay : pictureOkayValue,
                                                          pictureokay2 : pictureOkayValue2,
                                                          // STATUS: statusValue,
                                                          Image1: imageItem.Image1,
                                                          Image2: imageItem.Image2,
                                                          Questions1: all_scat_qtns,
                                                          Questions2: all_scat_qtns
                                                      });

                                                      // if (imageItem.Image2) { // Check if Image2 is not an empty string
                                                      //     images2Array.push({
                                                      //         KPIImageId: imageItem.KPIImageId,
                                                      //         QuestionImageId: imageItem.QuestionImageId,
                                                      //         BaseUrl: imageItem.BaseUrl,
                                                      //         ImageName: imageItem.ImageName,
                                                      //         pictureokay2 : pictureOkayValue2,
                                                      //         STATUS: statusValue,
                                                      //         Image2: imageItem.Image2,
                                                      //         Questions: all_scat_qtns
                                                      //     });
                                                      // }
                                                  }

                                                  // Add imagesArray to the corresponding defItem
                                                  defArray.push({
                                                      DefName: defItem.DefName,
                                                      DefId: defItem.DefId,
                                                      Images: images1Array
                                                  });

                                                  resolve();
                                              },
                                              (tx, error) => {
                                                  console.error("Failed to execute imageQuery", error);
                                                  reject(error);
                                              }
                                          );
                                      }));
                                  }

                                  // Wait for all image queries to resolve
                                  Promise.all(defPromises).then(() => {
                                      fetchedData.push({
                                          MenuId: item.MenuId,
                                          MID: item.MID,
                                          Menu: item.Menu,
                                          DefData: defArray,
                                      });
                                      resolve();
                                  }).catch(reject);
                              },
                              (tx, error) => {
                                  console.error("Failed to execute defQuery", error);
                                  reject(error);
                              }
                          );
                      }));
                  }

                  // Wait for all def queries to resolve
                  Promise.all(promises).then(() => {
                      // Update the state with the fetched data
                      setDataInfo(fetchedData);
                      setProcessing(false);
                      // console.log('Updated Data with Images:', JSON.stringify(fetchedData));
                  }).catch(error => {
                      setProcessing(false);
                      console.error("An error occurred while fetching data:", error);
                  });
              },
              (tx, error) => {
                  setProcessing(false);
                  console.error("Failed to execute main query", error);
              }
          );
      });
  } catch (error) {
      setProcessing(false);
      console.error("An error occurred while fetching data:", error);
  }
}


async function getAnswers(qtn,storeData){
// console.log(qtn , "Questiondata---------");

        let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {   
                // get inserted audit
                let selectlist=` DISTINCT T.AIAnswerName,T.AIAnswerId`;
                
                let q2=`Select ${selectlist} FROM Sup_ImageAuditKPIQuestion T  WHERE T.AIQuestionId='${qtn.AIQuestionId}' ORDER BY T.AIASequence `;
                
                await txn.executeSql(q2,[],async function (txn2, txnres) { 
                    // console.log('answers len',txnres.rows.length);
                    if(txnres.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            arr.push(data);
                            if(i==txnres.rows.length-1){

                            // console.log(arr, "Array of answerss-----");
                                // setSurveyQuestions(arr);
                                resolve(arr);
                            }
                        }
                    }
                    else{
                        resolve([]);
                    }
                },function (txn2, txnerr) { console.log(txnerr);resolve([]); },);
               
              });    
        }).then((val)=>{
            return {'Answers':val,'Success':true};
        }).catch((err)=>{
            console.log(err);
            return {'Success':false,'Error':err}
        });
    }



  async function getSurveyQtns(item){

        return new Promise((resolve,reject)=>{
            try {   
                let {StoreId,MerchandiserId}=storeData;
 
                let {MID}= item;
                
                db.transaction(async function (txn) {  
                  
                  // get inserted audit
                  let selectlist=` DISTINCT T.AIMaximumChar as MaxLength,T.AIMinimumChar as MinLength,T.AILengthValidationRequired as LengthValidation,T.AIDateRangeMax as DateRangeMax,T.AIDateRangeMin as DateRangeMin,T.AIDefaultQuestionEnable as QEnable,T.AIQuestionName as Question,T.AIQuestionId as QuestionId, T.QuestionType as QuestionType,T1.ANSWER As AIAnswerName, T1.ANSWER_ID as AIAnswerId,T1.MULTI_OPTIONS_IDS as multi_op_ids,T1.IS_DISABLED as isDisabled `;
               
                  let join2=` Left outer join ${AppTables.IMAGE_AUDIT_QUESTION} T1 on T1.MID=${MID} And T.AIQuestionId=T1.QUESTION_ID`;
                  let q2=`Select ${selectlist} FROM Sup_ImageAuditKPIQuestion T  ${join2} WHERE T1.STORE_ID='${StoreId}' AND T1.VISIT_DATE= '${d2}'   `;
                  q2+=` ORDER BY T.AIQuestionSequence `;

                  console.log(q2, "QueryQuestiondata")
      
                  await txn.executeSql(q2,[],async function (txn2, txnres) { 
                      console.log('getSurveyData 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);
                              data.QEnable=data.QEnable==1 || data.QEnable=='true'?true:false;
                              
                              let answers=[];
                              let qtn=data;
                              console.log(qtn , "qtn---")
                              qtn.isDisabled=qtn.isDisabled==1 || qtn.isDisabled=='1'?true:false ;

                             
                              if(data.QuestionType=='Multi choice list' || data.QuestionType=='Single choice list' || data.QuestionType=='Rating'){
                                  let allanswers=await getAnswers(data,item.MID,storeData,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.AIQuestionId+'_AnswerId'; 
                              let ans_key=qtn.AIQuestionId+'_Answer'; 
                              let multi_key=qtn.AIQuestionId+'_MultiOption';
                              let date_key=qtn.AIQuestionId+'_Date';
                              let img_key=qtn.AIQuestionId+'_ImagePath1';
                              let imgname_key=qtn.AIQuestionId+'_ImageName1';
                              let img_key2=qtn.AIQuestionId+'_ImagePath2';
                              let imgname_key2=qtn.AIQuestionId+'_ImageName2';
                              let rating_key=qtn.AIQuestionId+'_Rating'; 
                              let voiceClip_key=qtn.AIQuestionId+'_VoiceClip'; 
      
                              let showImageTag=(data.QuestionImageAllow==true || data.QuestionImageAllow=='true' || data.QuestionImageAllow==1) ;
                              let showImageTag2=false;
      
                              QD[id_key]=data.AIAnswerId;
                              QD[ans_key]=data.AIAnswerName;

                              
                              let selansid=data.AIAnswerId;
                              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.AIAnswerId==selansid)){
                                              showImageTag=true;
                                          }
                                          else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AIAnswerId)>=0)){
                                              showImageTag=true;
                                          }

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

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

                              if(showImageTag2){
                                let imgPath=data.Image2!=''?((Platform.OS=='ios'?'file://':'')+common_ImagePath+data.Image2):'';
                                QD[imgname_key2]=data.Image2;
                                QD[img_key2]=imgPath;
                              }
      
                              if(qtn.QuestionType=='Audio'){
                                  let voicefile_path=(Platform.OS=='ios'?'file://':'')+common_ImagePath+'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);
                                  // setSurveyQuestions(arr);
                                  // setProcessing(false);
                              }
                          }
                      }
                      else{
                          let sl=` DISTINCT T.AIMaximumChar,T.AIMinimumChar,T.AILengthValidationRequired,T.AIQuestionName,T.AIQuestionId,T.QuestionType,T.AIDateRangeMax,T.AIDateRangeMin,T.AIDefaultQuestionEnable as QEnable`;
                          let q=` SELECT ${sl} FROM Sup_ImageAuditKPIQuestion T `; 
                          q+=` order by T.AIQuestionSequence `;

                          //  WHERE T.SurveyId='${SurveyId}' and T.SubCategoryId='${SubCategoryId}'
                          
                           await txn.executeSql(q,[],async function (txn2, txnres2) { 
                              console.log('Surveys:',txnres2.rows.length)
                              let arr=[];
                              if(txnres2.rows.length>0){
                                  for(var i=0;i<txnres2.rows.length;i++){
                                      let data =txnres2.rows.item(i);

                                      // console.log(data, "Dataaa-----" , data.QEnable );

                                      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=='Number'){
                                          let allanswers=await getAnswers(data,item.MID,storeData,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 (txn2, txnerr) { console.log(txnerr);resolve([]); },);
                      }
                      
                  },function (txn2, txnerr) { console.log(txnerr);resolve([]); },);
                 
                });          
              } catch (err) {
                console.log(err);          
              }  
        })
    }



const RenderImageItem = React.memo(({ image, pictureokay, onPictureOkayChange }) => {

  const handleCheckBoxChange = (newValue) => {
    onPictureOkayChange(newValue ? 1 : 0);
  };


  return (
    <View>
      <Text style={[customStyle.storel_card_title, { fontWeight: '400', marginBottom: 10 }]}>
        {image.ImageName}
      </Text>
      
      <View>
        <TouchableOpacity onPress={() => {
          setZoomImageUrl([{ url: image.BaseUrl + '/' + image.Image1 }]);
          setrefImageIndex(0);
          UpdateShow_zoomImageRef(true);
        }}>
          <Animated.View
            style={{
              backgroundColor: "#fff",
              width: "100%",
              height: window.animatedHeight,
              paddingBottom: 0,
            }}
          >
            <Image
              source={{ uri: image.BaseUrl + '/' + image.Image1 }}
              style={{
                width: '100%',
                height: 150,
                resizeMode: 'stretch',
                alignSelf: 'center',
              }}
            />
          </Animated.View>
        </TouchableOpacity>
    
        <View style={[customStyle.WStkHdr_checkboxWrap, { paddingLeft: 0, marginVertical: 10 }]}>
          <View style={[customStyle.WStkHdr_checkboxCon, { paddingLeft: 5 }]}>
            <CheckBox
              boxType="square"
              style={[
                customStyle.WStkHdr_checkbox,
                Platform.OS === 'ios' ? { height: 20, width: 20, marginTop: 5, marginLeft: 5 } : {}
              ]}
              tintColors={{ true: PageTheme.$primary_color, false: PageTheme.$text_color_light }}
              value={pictureokay === 1}
              onValueChange={handleCheckBoxChange}
            />
          </View>
          <Text style={[customStyle.WStkHdrText2, customStyle.WStkHdr_checkboxpName]}>
            Picture OK
          </Text>
        </View>
      </View>

      <RenderSurveyQtns image={image} QuestionsData={QuestionsData} />
    </View>
  );
});

const RenderImageItem2 = React.memo(({ image, pictureokay, onPictureOkayChange }) => { 

  // console.log("pictureokay2",pictureokay)

  const handleCheckBoxChange = (newValue) => {
    onPictureOkayChange(newValue ? 1 : 0);
  };

  return (
    <View>
      <Text style={[customStyle.storel_card_title, { fontWeight: '400', marginBottom: 10 }]}>
        {image.ImageName}
      </Text>

       <TouchableOpacity onPress={() => {
          setZoomImageUrl([{ url: image.BaseUrl + '/' + image.Image2 }]);
          setrefImageIndex(0);
          UpdateShow_zoomImageRef(true);
        }}>
        <Animated.View
          style={{
            backgroundColor: "#fff",
            width: "100%",
            height: window.animatedHeight,
            paddingBottom: 0,
          }}
        >
          <Image
            source={{ uri: image.BaseUrl + '/' + image.Image2 }}
            style={{
              width: '100%',
              height: 150,
              resizeMode: 'stretch',
              alignSelf: 'center',
            }}
          />
        </Animated.View>
        
        </TouchableOpacity>

      <View style={[customStyle.WStkHdr_checkboxWrap, { paddingLeft: 0, marginVertical: 10 }]}>
        <View style={[customStyle.WStkHdr_checkboxCon, { paddingLeft: 5 }]}>
          <CheckBox
            boxType='square'
            style={[
              customStyle.WStkHdr_checkbox,
              Platform.OS === 'ios'
                ? { height: 20, width: 20, marginTop: 5, marginLeft: 5 }
                : {},
            ]}
            tintColors={{
              true: PageTheme.$primary_color,
              false: PageTheme.$text_color_light,
            }}
            value={pictureokay === 1}
            onValueChange={handleCheckBoxChange}
          />
        </View>
        <Text style={[customStyle.WStkHdrText2, customStyle.WStkHdr_checkboxpName]}>
          Picture OK
        </Text>
      </View>
      <RenderSurveyQtns image={image} QuestionsData={QuestionsData} />
    </View>
  );
});

const ImageAuditItem = React.memo(({ item }) => {

const imageKeys = item?.DefData?.[0]?.Images?.[0] || {};

  // Filter keys that start with 'Image'
  const dynamicImageKeys = Object.keys(imageKeys).filter(key => key.startsWith('Image'));

  // Use the first and second dynamic image keys if they exist, otherwise use defaults
  const imageKey1 = dynamicImageKeys[1] || 'IMAGE 1';
  const imageKey2 = dynamicImageKeys[2] || 'IMAGE 2';

const handleSetPictureOkay = (defId, imagePath, imageId, kpiId, value, imageType) => {
  console.log("Received update for:", { defId, imagePath, imageId, kpiId, value, imageType });

  let uniqueId = "";
  if (imagePath != null && imagePath != '') {
    uniqueId = `${imageId}${kpiId}${imagePath}`;
  }

  console.log(uniqueId, "uniqueId====");

  setDataInfo(prevState => {
    const newState = JSON.parse(JSON.stringify(prevState));
    
    const defDataIndex = newState.findIndex(item =>
      item.DefData.some(def => def.DefId === defId)
    );

    if (defDataIndex !== -1) {
      const defData = newState[defDataIndex].DefData;
      const defIndex = defData.findIndex(def => def.DefId === defId);

      if (defIndex !== -1) {
        const images = defData[defIndex].Images;
        console.log("images------", images);
        
        // Handle Image1 or Image2 based on the imageType parameter
        if (imageType === "Image1") {
          const imageIndex = images.findIndex(image => `${image.QuestionImageId}${image.KPIImageId}${image.Image1}` == uniqueId);
          if (imageIndex !== -1) {
            console.log(`Updating Image1 for ${uniqueId} with value ${value}`);
            images[imageIndex].pictureokay = value;
          } else {
            console.log(`No matching image in Image1 for ${uniqueId}`);
          }
        } else if (imageType === "Image2") {
          const imageIndex = images.findIndex(image => `${image.QuestionImageId}${image.KPIImageId}${image.Image2}` == uniqueId);
          if (imageIndex !== -1) {
            console.log(`Updating Image2 for ${uniqueId} with value ${value}`);
            images[imageIndex].pictureokay2 = value;
          } else {
            console.log(`No matching image in Image2 for ${uniqueId}`);
          }
        }
      }
    }
    
    return newState;
  });
};


  return (
    <View style={[customStyle.storel, customStyle.storeInfo_wrap, { marginTop: 10 }]}>
      <View style={customStyle.storel_card_outer}>
        <View style={[customStyle.storel_card, { width: '100%' }]}>
          <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, { width: '100%' }]}
          >
            <Text style={[customStyle.storel_card_title, { fontWeight: '600', color: '#fff' }]}>
              {item?.Menu || 'No Menu'}
            </Text>
          </LinearGradient>
        </View>

        <FlatList
          data={item?.DefData || []}
          // keyExtractor={(def) => def.DefId.toString()}
           keyExtractor={(_, index) => index.toString()} 
          ItemSeparatorComponent={<View style={{ paddingVertical: 10 }} />}
          renderItem={({ item: def }) => (
            <>
              <View style={{ height: 1, backgroundColor: '#888888', marginBottom: 15 }} />

              <View style={customStyle.storel_card}>
                <View style={[customStyle.storel_card_content, { paddingBottom: 10 , marginHorizontal:0 }]}>
                  <Text style={[customStyle.storel_card_title, { fontWeight: '700' }]}>{def.DefName || 'No DefName'}</Text>
                </View>
              </View>

              <FlatList
                data={def?.Images || []}
                renderItem={({ item: image }) => (
                  <View>
                    {/* Render Image1 View */}
                    {image.Image1 && (
                      <>
                        <View style={[customStyle.storel_card_content, { paddingBottom: 10 , marginHorizontal:0 }]}>
                          <Text style={[customStyle.storel_card_title]}>
                            {imageKey1}
                          </Text>
                        </View>
                      </>
                    )}

                    {image.Image1 && (
                      <RenderImageItem
                        image={image}
                        pictureokay={image.pictureokay}
                        onPictureOkayChange={(value) => handleSetPictureOkay(def.DefId, image.Image1, image.QuestionImageId, image.KPIImageId, value, "Image1")}
                      />
                    )}

                    {/* Render Image2 View */}
                    
                    {image.Image2 && (
                      <>
                        <View style={[customStyle.storel_card_content, { paddingBottom: 10 , marginHorizontal:0 }]}>
                          <Text style={[customStyle.storel_card_title]}>
                            {imageKey2}
                          </Text>
                        </View>
                      </>
                    )}
                    {image.Image2 && (
                      <RenderImageItem2
                        image={image}
                        pictureokay={image.pictureokay2}
                       onPictureOkayChange={(value) => handleSetPictureOkay(def.DefId, image.Image2, image.QuestionImageId, image.KPIImageId, value, "Image2")}
                      />
                    )}
                  </View>
                )}
              />
            </>
          )}
        />
      </View>
    </View>
  );
});





function render_Picker(label_key,value_key,onChange=()=>{},selected_data={}){
  var data=[];

  // console.log(selected_data , "selected_data")

  let qtn=selected_data.qtn || {};
  let image=selected_data.image || '';

  let isQtnDisabled=qtn.isDisabled!=null && qtn.isDisabled!=''?qtn.isDisabled:false;

  let allAnswers=qtn.Answers || [];

  // console.log(qtn , "selectanswerpicker", isQtnDisabled, "isQtnDisabled");
  
  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,image) }}
      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:{})]}>{(selected_data.value!=null && selected_data.value!=''?selected_data.value: '-select-')}</Text>
      </ModalSelector>
  )
}

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.AIQuestionId==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.AIQuestionId+'_AnswerId'; 
                  let ans_key=s_qtn.AIQuestionId+'_Answer'; 
                  data[id_key]=0;
                  data[ans_key]='';
              }
              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.AIQuestionId==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);
          setrerenderdata(!rerenderdata);
      }
  })
}


function onselectionChange(option,qtn,image){

  // console.log(qtn , "QTNNNNN11111----");
  // console.log(image?.QuestionImageId , "image.QuestionImageIdddd");

  let data=QuestionsData;
  let id_key=qtn.AIQuestionId+'_AnswerId'+ image?.QuestionImageId; 


  let ans_key=qtn.AIQuestionId+'_Answer' + image?.QuestionImageId; 
  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.AIAnswerId==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);
      setrerenderdata(!rerenderdata);
  }
 
  
  
}

function setTextValue(value,qtn, image) {        
  let id_key=qtn.AIQuestionId+'_AnswerId'+ image.QuestionImageId; 
  let ans_key=qtn.AIQuestionId+'_Answer'+ image.QuestionImageId; 
  
  let obj=QuestionsData;
  if(qtn.QuestionType=='Date' ){
      let date_key=qtn.AIQuestionId+'_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);
  // setrerenderdata1(!rerenderdata1);
  if(timerRef?.current){
  clearTimeout(timerRef.current)
  }

  // timerRef.current= setTimeout(()=>{
    setHasUnsavedChanges(true);
    setrerenderdata1(!rerenderdata1);
  // },1000)

}




async function setMultiSelectValue(selectedItems=[],qtn, image) {  

  console.log('setMultiSelectValue',selectedItems);      
  let id_key=qtn.AIQuestionId+'_AnswerId'+ image.QuestionImageId; 
  let ans_key=qtn.AIQuestionId+'_Answer'+ image.QuestionImageId; 
  let multi_key=qtn.AIQuestionId+'_MultiOption'+ image.QuestionImageId;
  let obj=QuestionsData;
  obj[id_key]=0;
  obj[multi_key]=selectedItems.join(',');
  let anss=[];
  selectedItems.map((itemValue)=>{
      let ans = qtn.Answers.find(c1 => c1.AIAnswerId == itemValue); 
      if(ans.AIAnswerName){anss.push(ans.AIAnswerName)}
  });
  obj[ans_key]=anss.join(',');
  console.log('obj:',obj);
  setQuestionsData(obj);
  setHasUnsavedChanges(true);
  setrerenderdata(!rerenderdata);
}


const RenderItem = React.memo(({ item: qtn, index,image,QuestionsData }) => {
  console.log("index------",index)
  let selansid = '',
    selanswer = '',
    selimg = '',
    selimg2 = '',
    showImageTag = false,
    showImageTag2 = false;
  let id_key = qtn.AIQuestionId + '_AnswerId' + image.QuestionImageId;
  let ans_key = qtn.AIQuestionId + '_Answer' + image.QuestionImageId;
  let multi_key = qtn.AIQuestionId + '_MultiOption' + image.QuestionImageId;
  let date_key = qtn.AIQuestionId + '_Date' + image.QuestionImageId;
  let img_key = qtn.AIQuestionId + '_ImagePath1' + image.QuestionImageId;
  let imgname_key = qtn.AIQuestionId + '_ImageName1' + image.QuestionImageId;
  let img_key2 = qtn.AIQuestionId + '_ImagePath2' + image.QuestionImageId;
  let imgname_key2 = qtn.AIQuestionId + '_ImageName2' + image.QuestionImageId;
  let rating_key = qtn.AIQuestionId + '_Rating' + image.QuestionImageId;
  let voiceClip_key = qtn.AIQuestionId + '_VoiceClip' + image.QuestionImageId;
  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) {
      for (var i = 0; i < qtn.Answers.length; i++) {
        let obj = {
          AIAnswerId: parseInt(qtn.Answers[i].AIAnswerId),
          AIAnswerName: qtn.Answers[i].AIAnswerName,
        };
        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') {
    console.log("QuestionsData---------",QuestionsData)
    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 || ''):'';

  }

  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.AIAnswerId == selansid) {
          showImageTag = true;
        } else if (qtn.QuestionType == 'Multi choice list' && isandImgAl && selansid.indexOf(ansss.AIAnswerId) >= 0) {
          showImageTag = true;
        }

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

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

if (isDisabled == true) {
    return <View key={index} />;
  } else {
    return (
      <View style={[customStyle.sform_group2]} key={index}>
        <Text style={[customStyle.sform_label3]}>{qtn.AIQuestionName}</Text>
        {qtn.QuestionType == 'Single choice list' && qtn.Answers && render_Picker('AIAnswerName', 'AIAnswerId', onselectionChange, { value: selanswer, qtn, image })}
        {qtn.QuestionType == 'Multi choice list' && qtn.Answers && (
          <MultiSelect
            items={list_mcdata}
            uniqueKey="AIAnswerId"
            onSelectedItemsChange={(selectedItems) => {
              console.log('onSelectedItemsChange');
              setMultiSelectValue(selectedItems, qtn, image);
            }}
            selectedItems={selansid}
            selectText="Pick Items"
            searchInputPlaceholderText="Search Items..."
            tagRemoveIconColor={PrimaryTheme.$primary_color}
            tagBorderColor={PrimaryTheme.$primary_color}
            tagTextColor={PrimaryTheme.$primary_color}
            selectedItemTextColor={PrimaryTheme.$primary_color}
            selectedItemIconColor={PrimaryTheme.$primary_color}
            tagContainerStyle={{ height: 30, width: '100%', paddingVertical: 5 }}
            styleTextTag={{ fontSize: 14 }}
            itemTextColor={PrimaryTheme.$text_color}
            displayKey="AIAnswerName"
            searchInputStyle={{ color: '#CCC' }}
            submitButtonColor={PrimaryTheme.$primary_color}
            submitButtonText="Submit"
          />
        )}
        {(qtn.QuestionType == 'Number' || qtn.QuestionType == 'Decimal' || qtn.QuestionType == 'Text') && (
          <TextInput
            style={[customStyle.surveyQtn_InputStyle,]}
            placeholder=""
            placeholderTextColor={PageTheme.$placeholder_color}
            keyboardType={qtn.QuestionType == 'Decimal' ? 'decimal-pad' : qtn.QuestionType == 'Text' ? 'default' : 'number-pad'}
            value={selansid}
            onChangeText={(val) => {
              console.log("val------",val)
              setTextValue(val, qtn, image);
            }}
            autoComplete="off"
          />
        )}
        {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.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>
        )}
      </View>
    );
  }
});


const RenderSurveyQtns= React.memo(({image,QuestionsData})=> {
  const SurveyQuestions = image?.Questions;
  // console.log("SurveyQuestions----",SurveyQuestions?.length)


 return (
    <FlatList
      data={SurveyQuestions}
      // extraData={rerenderdata1}
      renderItem={({ item, index })=><RenderItem item={item} index={index} image={image} QuestionsData={QuestionsData}/>}
      keyExtractor={(item, index) => item.AIQuestionId.toString()}
      contentContainerStyle={customStyle.SVn_GroupViewList}
    />
  );
})


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,showImageTag2=false;
      let id_key=qtn.AIQuestionId+'_AnswerId'; 
      let ans_key=qtn.AIQuestionId+'_Answer'; 
      let multi_key=qtn.AIQuestionId+'_MultiOption';
      let date_key=qtn.AIQuestionId+'_Date';
      let img_key=qtn.AIQuestionId+'_ImagePath1';
      let imgname_key=qtn.AIQuestionId+'_ImageName1';
      let img_key2=qtn.AIQuestionId+'_ImagePath2';
      let imgname_key2=qtn.AIQuestionId+'_ImageName2';
      let rating_key=qtn.AIQuestionId+'_Rating'; 
      let voiceClip_key=qtn.AIQuestionId+'_VoiceClip'; 
      let list_mcdata=[];

      let isDisabled=qtn.isDisabled!=null?qtn.isDisabled:false
     
      if(isDisabled==true){

      }
      else{
          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){
              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]===''))){
              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=='')))){
              isvalid=false;
              notify(ST.Pleaserecordaudioclipfortherequiredfield,'SHORT');
              break;
          }
          else if(Object.keys(QD).indexOf(id_key)<0 || (Object.keys(QD).indexOf(id_key)>=0 && (QD[id_key]===''))){
              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]===''))){
              isvalid=false;
              notify(ST.Pleaseaddimages,'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;
                      }
                  }
              }
          }

      }
  } 
  
  return isvalid;
}

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

function onSaveCancel(){
  setShowAlert(false);
}


async function saveData(UploadStatus) {

  console.log(UploadStatus, "UploadStatus")

  setHasUnsavedChanges(false);
  setShowAlert(false);
  setLoaderTitle('Saving Data...');
  setProcessing(true);
  try {
      let { StoreId } = storeData;

      await db.transaction(async function (txn) {
          let q1 = `DELETE FROM ${AppTables.IMAGE_AUDIT_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
          let q2 = `DELETE FROM ${AppTables.IMAGE_AUDIT_QUESTION} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
        
          // Remove old data
          await txn.executeSql(q1, [], async function (txn2, txnres) {
              console.log('Image audit header data deleted');
          }, function (txn2, txnerr) { console.log(txnerr); },);

          await txn.executeSql(q2, [], async function (txn2, txnres) {
              console.log('Image audit questions deleted');
          }, function (txn2, txnerr) { console.log(txnerr); },);

          await insertData(UploadStatus);
      });
  } catch (err) {
      console.log(err);
  }
}


async function insertData(UploadStatus) {
  try {
    let { StoreId } = storeData;

    await db.transaction(async function (txn) {
      var headerValues = '';
      var imageValues = '';

      console.log("data-------OF INFOooo",JSON.stringify(dataInfo))
      for (var i = 0; i < dataInfo.length; i++) {
        let { MID, MenuId, Menu, DefData } = dataInfo[i];

        let ImageHeaderId = 'IMAGEAUDIT' + i + MID + moment().format('MMDDYYYYHHmmss');

        for (var j = 0; j < DefData.length; j++) {
          let { DefId, DefName, Images } = DefData[j];

          // Iterate over the Images array (handling both Image1 and Image2 separately)
          for (let k = 0; k < Images?.length; k++) {
            let image = Images[k];

            // Check if Image1 or Image2 are selected
            let pictureokay = image.pictureokay ? 1 : 0; // for Image1 checkbox
            let pictureokay2 = image.pictureokay2 ? 1 : 0; // for Image2 checkbox

            let statusChange = image.STATUS == "U" ? "U" : UploadStatus;

            // Only insert data if Image1 or Image2 is selected (avoid duplicates)
            // if (pictureokay || pictureokay2) {
              headerValues += headerValues !== '' ? ' , ' : '';
              headerValues += `('${StoreId}','${d2}','${ImageHeaderId}', '${MID}', '${MenuId}', '${Menu}', '${image.KPIImageId}', '${image.QuestionImageId}', '${DefId}', '${DefName}', '${image.ImageName || ''}', '${image.Image1 || ''}', '${image.Image2 || ''}', '${image.BaseUrl || ''}', '${pictureokay}', '${pictureokay2}', '${statusChange}')`;
            // }

            // Insert only if Image1 or Image2 is selected (avoid duplicates)
            // if (pictureokay || pictureokay2) {
            //   imageValues += imageValues !== '' ? ' , ' : '';
            //   imageValues += `('${ImageHeaderId}', '${StoreId}', '${d2}', '${MID}', '${image.QuestionImageId}', '${image.QuestionType}', '${pictureokay ? image.Image1 || '' : ''}', '${image.KPIImageId}', '', 0, '${d2}')`;
            // }
          }
        }
      }

      if (headerValues !== '') {
        let addHeaderData = `INSERT INTO ${AppTables.IMAGE_AUDIT_HDR_DATA} 
          (STORE_ID, VISIT_DATE, IMAGE_HEADER_ID, MID, MenuId, Menu, KPIImageId, QuestionImageId, DefId, DefName, ImageName, Image1, Image2, BaseUrl, pictureokay, pictureokay2, STATUS)
          VALUES ${headerValues}`;

        console.log("HEADER_VALUES---", headerValues);

        await txn.executeSql(addHeaderData, [], async function (txn2, txnres) {
          console.log('Image header data added');
          notify('Data saved successfully');
          setProcessing(false);

            if(UploadStatus == "U") {
              props.navigation.goBack();

            }


          // Uncomment if needed for image data insertion
          // if (imageValues !== '') {
          //   let addImagesData = `INSERT INTO ${AppTables.IMAGE_AUDIT_QUESTION} 
          //     (STORE_ID, VISIT_DATE, MID, QUESTION_ID, QUESTION_TYPE, ANSWER, ANSWER_ID, MULTI_OPTIONS_IDS, IS_DISABLED, ADDED_DATE) 
          //     VALUES ${imageValues}`;

          //   await txn.executeSql(addImagesData, [], async function (txn2, txnres) {
          //     console.log('Image data added successfully');
          //     notify('Data saved successfully');
          //     setProcessing(false);
          //   }, function (txn2, txnerr) {
          //     console.log(txnerr);
          //     setProcessing(false);
          //     notify('Error saving image data');
          //   });
          // }
        }, function (txn2, txnerr) {
          console.log(txnerr);
          setProcessing(false);
          notify('Error saving image header data');
        });
      }
    });
  } catch (err) {
    console.log(err);
    setProcessing(false);
  }
}

async function upload_Status() {
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  await saveData("P");

  setLoaderTitle('Uploading Data...');

  let storeInfo = dataInfo;

  let arr = [];


 // Create a shallow copy or filtered version of dataInfo
  let filteredStoreInfo = dataInfo.map(item => {
    let filteredDefData = item.DefData.map(defItem => {
      // Include all images, setting pictureokay/pictureokay2 to 0 if not already set
      let allImages = defItem.Images.map(image => ({
        ...image,
        pictureokay: image.pictureokay ? image.pictureokay : 0,
        pictureokay2: image.pictureokay2 ? image.pictureokay2 : 0,
      }));

      return {
        ...defItem,
        Images: allImages
      };
    });

    return {
      ...item,
      DefData: filteredDefData
    };
  });

  // Filter out any entries where Images is empty
  filteredStoreInfo = filteredStoreInfo.filter(item => item.DefData.some(defItem => defItem.Images.length > 0));


  await filteredStoreInfo.map((item, i) => {
    let itemObj2 = item;

    if (item.Status !== "U") {
      let rsData = item.DefData.map(item3 => {
        let Images = [];

        item3?.Images.map(item2 => {
          let obj = {
            KPIImageId: item2.KPIImageId,
            QuestionImageId: item2.QuestionImageId
          };

          if (item2?.Image1) {
            Images.push({
              ...obj,
              imageType: "Image1",
              Questions: item2.Questions1,
              Image: item2?.Image1,
              pictureokay: item2.pictureokay
            });
          }

          if (item2?.Image2) {
            Images.push({
              ...obj,
              imageType: "Image2",
              Questions: item2.Questions2,
              Image: item2?.Image2,
              pictureokay: item2.pictureokay2
            });
          }
        });

        item3["Images"] = Images;
        return item3;
      });

      itemObj2["UserId"] = props.UserId;
      itemObj2["DefData"] = rsData;
      arr.push(itemObj2);
    }
  });

  console.log("Filtered Data to Upload:", JSON.stringify(arr));

  console.log(JSON.stringify(arr), "postDATAAAA----------")

  let postData = {
      "MID": storeData?.MID,
      "Keys": "Sup_Image_Audit_Info",
      "JsonData": JSON.stringify(arr),
      "UserId": props.UserId,
  };

  // console.log("image audit infooo-------------ad", dataInfo);

  const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);

  // console.log(url, postData, 'url and postDaata...');

  await UploadData(url, postData)
      .then(async (res) => {
          console.log('res: 12', res);
          if (res?.UploadJsonResult == "Success") {
              await saveData("U");
              //  get_data();
              setProcessing(false);
          } else {
              setProcessing(false);
          }
      })
      .catch((err) => {
          console.log(err);
          setProcessing(false);
      });

}



// console.log(JSON.stringify(dataInfo), "data---------///")


  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS === 'ios'}>
    {processing && <CustomLoader fullHeight title={loaderTitle} />}
    
    <CustomHeader {...props} title={'Image Audit'} />

    {ConfirmSaveAlert(props,showAlert,onSaveCancel,upload_Status)}

    {!processing && <>
      <LinearGradient
        colors={[PageTheme.$gradient1, PageTheme.$primary_color]}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 0 }}
        style={[customStyle.roundScrollWrapper]}
      >
        <View style={[customStyle.pageContentWrapper]}>
          {!props.isDataDownloaded && <NoDataComponent {...props} />}
          <View style={[customStyle.storelist_parentwrap,{paddingHorizontal:10}]}>

          <View style={[customStyle.storel,customStyle.storeInfo_wrap]}>

          <View style={customStyle.storel_card_outer}> 
            <View style={customStyle.storel_card}>
              <View style={customStyle.storel_card_content}>
                <Text style={customStyle.storel_card_title}>{storeData?.StoreName}</Text>
                <View style={customStyle.storel_card_subtitle}>
                  <Text style={customStyle.storel_card_subtitleTxt}>{storeData?.StoreType}</Text>
                </View>
              </View>                  
            </View>
            <View style={customStyle.storel_details}>
              <View style={customStyle.storel_code}>
                <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
                  <Text style={customStyle.storel_codeLbl}>{ST.StoreId+':'}</Text>
                  <Text style={customStyle.storel_codeText}>{storeData?.StoreId}</Text>
                </View>                    
                <View style={[customStyle.storel_codeCon]}>
                  <Text style={customStyle.storel_codeLbl}>{ST.Address+':'}</Text>
                  <Text style={customStyle.storel_codeText}>{storeData?.Address}</Text>
                </View>
              </View>
            </View>                
          </View> 

          </View>


          {
            <View style={[customStyle.storel_Con, { paddingBottom: 0 }]}>
              <FlatList
                data={dataInfo || []}
                // extraData={rerenderdata}
                style={customStyle.listcon}
                // nestedScrollEnabled={true}
                // removeClippedSubviews={false}
                // showsVerticalScrollIndicator={false}     
                contentContainerStyle={[{paddingBottom:200}]}
                renderItem={({ item }) => <ImageAuditItem item={item} {...props} />}
               
              />
            </View>
          }


          </View>
        </View>
      </LinearGradient>

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

        <View style={[customStyle.opening_Stock_btnWrap, {marginTop :40}]}>
              <GradientButton {...props} title={'Save And Upload'} onPress={()=>{onSubmitData()}}/> 
        </View> 
        </>}

    </Container>
  );
};

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