import React, { useState, useEffect, useRef } from 'react';
import { View, Text, TextInput, ScrollView, TouchableOpacity, Platform, Image, Modal, BackHandler, Keyboard } from 'react-native';
import ModalSelector from 'react-native-modal-selector';
import MultiSelect from 'react-native-multiple-select';
import CustomHeader from '../../../components/CustomHeader';
import IMAGES from '../../../constants/Images';
import { GlobalTheme, Screen } from '../../../theme';
import CustomButton from '../../../components/CustomButton';
import { styles } from './style';
import { toastError, toastSuccess } from '../../../constants/Toast';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import Icon from 'react-native-vector-icons/FontAwesome';
import CustomCamera from '../../../components/CustomCamera';
import db from '../../../constants/database';
import { getImage } from '../../../constants/function';
import CustomIcon from '../../../constants/IconGenerator';
import { ImageZoom } from '@likashefqet/react-native-image-zoom';
import { useFocusEffect } from '@react-navigation/native';
import { validateNumber } from '../../../constants/validations';
import { ConfirmSaveAlert } from '../../../components/Alert';
import { SafeAreaView } from 'react-native-safe-area-context';
import moment from 'moment';
import Loader from '../../../constants/Loader';
import { useSelector } from 'react-redux';

const FeedbackFormScreen = ({ route, navigation }) => {
  const { CategoryId, SurveyId, CategoryName  , storeData} = route.params || {};
  let user_exist_data = useSelector(state => state?.user);
  const userId =  user_exist_data.UserId || '' ;
  const [questions, setQuestions] = useState([]);
  const [answers, setAnswers] = useState({});
  const [enabledQuestions, setEnabledQuestions] = useState({});
  const [showCamera, setShowCamera] = useState(false);
  const [activeCameraQId, setActiveCameraQId] = useState(null);
  const [selectedImg, setSelectedImg] = useState(null);
  const [questionsFlat, setQuestionsFlat] = useState([]);

  const [showModal, setShowModal] = useState(false);
  const [zoomImageUrl, setZoomImageUrl] = useState(null);
  const [showZoomImage, setShowZoomImage] = useState(false);

  const [showAlert, setShowAlert] = useState(false);
  const [loadingsave, setLoadingSave] = useState(false);
  const d2 = moment().format('MM/DD/YYYY');

  // handle disable and enable functions

  console.log("storeDatastoreDatastoreData",storeData)

  const disableQtn = () => {
    let disableQ = questions?.map(q => {

    });
  }

  // end  handle disable and enable functions

  const loadSavedAnswers = async () => {
    const query = `SELECT * FROM FeedBackLocalTable WHERE CATEGORY_ID='${CategoryId}' AND SURVEY_ID='${SurveyId}' AND STORE_ID='${storeData?.StoreId}' AND VISIT_DATE='${d2}'`;
    // console.log("local saved answers query ===>", query)
    db.transaction(tx => {
      tx.executeSql(
        query,
        [],
        (tx, results) => {
          const localAnswers = {};
          let enb = {}
          for (let i = 0; i < results.rows.length; i++) {
            const item = results.rows.item(i);
            let answer = null;
            if (item.IMAGE1 && item.IMAGE1 !== '') {
              answer = item.IMAGE1.trim();
            } else if (item.ANSWER && item.ANSWER !== '') {
              if (typeof item.ANSWER === 'string' && item.ANSWER.includes(',')) {
                answer = item.ANSWER.split(',').map(val => parseInt(val.trim(), 10));
              } else {
                answer = item.ANSWER;
              }
            }

            if (item.QUESTION_TYPE == 'Single choice list') {
              answer = `${item?.ANSWER_ID},${item.ANSWER}`
            } else if (item.QUESTION_TYPE == 'Multi choice list') {
              answer = item?.MULTI_OPTIONS_IDS && JSON.parse(item?.MULTI_OPTIONS_IDS)
              // console.log("answer------multi", answer, item)
            }



            enb = item?.IS_DISABLED && JSON.parse(item?.IS_DISABLED)
            localAnswers[item.QUESTION_ID] = answer;
            // console.log("item?.IMAGE1", item?.IMAGE1)
            localAnswers[item.QUESTION_ID + "Img1"] = item?.IMAGE1 ? ('file:///data/user/0/com.performicsstoredna/files/PerformicsAllImages/Store_DNA/' + item.IMAGE1) : "";
            localAnswers[item.QUESTION_ID + "Img2"] = item?.IMAGE1 ? ('file:///data/user/0/com.performicsstoredna/files/PerformicsAllImages/Store_DNA/' + item.IMAGE2) : "";

            // enabledMap[item.QUESTION_ID] = item.IS_DISABLED === 1 ? false : true; // isDisabled
          }

          setAnswers(prev => ({
            ...prev,
            ...localAnswers
          }));
          //  console.log("enb----",enb)
          if (Object.keys(enb).length > 0) {
            setEnabledQuestions(enb);  // ✅ restore isDisabled state
          }
        },
        (tx, error) => {
          console.log('Error fetching saved answers:', error);
        }
      );
    });
  };

  const saveData = async () => {
    setLoadingSave(true);
    try {
      let valuesArray = [];

      questions?.map(q => {
        let answer = answers[q.QuestionId] || '';
        let img1 = answers[q.QuestionId + "Img1"] || '';
        let img2 = answers[q.QuestionId + "Img2"] || '';
        let selanswer = "", selansid = "", multi = "";

        // console.log("questionlist======", q, "questionlist====");

        if (q.QuestionType == 'Single choice list') {
          let slValue = answer?.split(",")
          selanswer = slValue?.[1] || ''
          selansid = slValue?.[0] || "0"
          // console.log("selanswer==", selanswer, "selansid", selansid, "answ", answer, q)

        } else if (q.QuestionType == 'Multi choice list') {
          // console.log("multi------", answer)
          multi = JSON.stringify(answer)
          selansid = "0"
        } else {
          selanswer = answer
          selansid = "0"
        }

        // console.log("selanswer==",selanswer ,"selansid" , selansid , "answ",answer)

        let imgName1 = img1.split("/").pop();
        let imgName2 = img2.split("/").pop();

        //  console.log("multi------multi",multi)
        let enb = JSON.stringify(enabledQuestions)
        valuesArray.push(` ('${d2}','${SurveyId}', '${CategoryId}','${q.Question}','${q.QuestionId}','${q.QuestionType}','${selanswer || ''}','${selansid}','${q.QuestionImageAllow}','${imgName1 || ''}','${imgName2 || ''}','${q.ImageAllow1}','${q.ImageAllow2}','${multi}','${q.QuestionRefImage}', '${enb}', '${q.EnableQuestion}' , '${storeData.StoreId || ''}') `);
      });

      const queryStr = valuesArray.join(', ');
      let insertQuery = `INSERT INTO FeedBackLocalTable (VISIT_DATE, SURVEY_ID, CATEGORY_ID, QUESTION, QUESTION_ID, QUESTION_TYPE ,ANSWER,ANSWER_ID,QuestionImageAllow,IMAGE1,IMAGE2,IMAGE_ALLOW1,IMAGE_ALLOW2,MULTI_OPTIONS_IDS, QUESTION_REF_IMAGE, IS_DISABLED , IS_ENABLED, STORE_ID) VALUES ${queryStr}`

      db.transaction(tx => {
        let deleteQuery = `DELETE FROM FeedBackLocalTable WHERE CATEGORY_ID='${CategoryId}' AND SURVEY_ID='${SurveyId}' AND STORE_ID='${storeData?.StoreId}' AND VISIT_DATE='${d2}'`;
        console.log('Executing DELETE query:', deleteQuery);
        tx.executeSql(deleteQuery, [], () => {

          // console.log("insertQuery------",insertQuery)
          tx.executeSql(insertQuery, [], async function (txn2, txnres) {
            toastSuccess('Success', 'Data saved successfully.');
            setLoadingSave(false);
            navigation.goBack();
          }, function (txnE, txnerr) {
            console.log('Delete error:', txnerr); toastError('Error', txnerr);
            setLoadingSave(false);
          },);

        }, err => console.log('Delete error:', err));
      });
    } catch (e) {
      toastError('Error', e);
      setLoadingSave(false);
      console.log('Transaction error:', e);
    }
  };

  // const handleAnswerChange = (questionId, value, enableList = '', disableList = '', qtn) => {
    
  //   setAnswers(prev => ({ ...prev, [questionId]: value }));
  //   const updated = { ...enabledQuestions };
  //   if (disableList) {
  //     disableList.split(',').forEach(id => {
  //       updated[parseInt(id)] = false;
  //     });
  //   }
  //   if (enableList) {
  //     enableList.split(',').forEach(id => {
  //       updated[parseInt(id)] = true;
  //     });
  //   }
  //   setEnabledQuestions(updated);
  // };

   function cleanSelector(disableList,qtn,showImageTag,showImageTag2) {
    let objTemp={...answers}
    disableList?.split(",").map((itm,index)=>{
      objTemp[itm]=""
      delete objTemp[itm+"Img1"]
      delete objTemp[itm+"Img2"]
    })
    if(showImageTag){
        delete objTemp[qtn?.QuestionId+"Img1"]
    }
    if(showImageTag2){
        delete objTemp[qtn?.QuestionId+"Img2"]
    }
    // console.log("objTemp-----3",showImageTag,showImageTag2,objTemp)s
    setAnswers(objTemp);
    
  }


  const handleAnswerChange = (questionId, value, enableList = '', disableList = '', qtn,showImageTag=false,showImageTag2=false) => {
    const prevValue = answers[questionId];

    // Clean selector logic: only for Single choice list
    if (
      qtn.QuestionType === 'Single choice list' &&
      prevValue &&
      prevValue !== value
    ) {
      cleanSelector(disableList,qtn,showImageTag,showImageTag2);
      console.log('qtn------',qtn)
    }

    // Update the answer
    setAnswers(prev => ({ ...prev, [questionId]: value }));

    // Enable/disable dependent questions
    const updated = { ...enabledQuestions };

    if (disableList) {
      disableList.split(',').forEach(id => {
        updated[parseInt(id)] = false;
      });
    }

    if (enableList) {
      enableList.split(',').forEach(id => {
        updated[parseInt(id)] = true;
      });
    }

    setEnabledQuestions(updated);
  };

  const handleImageCaptured = async (photo) => {
    console.log("activeCameraQId-----", activeCameraQId)
    if (activeCameraQId && photo?.uri) {
      try {
        const imgdata = {
          uri: photo.uri,
          width: photo.width,
          ExtendedHeight: photo.height,
          storeData: {}
        };

        const res = await getImage(imgdata ,userId , storeData);
        const imagePath = 'file://' + (res?.finalPath || photo.uri);
        setAnswers(prev => ({
          ...prev,
          [activeCameraQId]: imagePath
        }));
        setSelectedImg(imagePath);
        setShowModal(true);
      } catch (e) {
        console.warn("Watermarking failed:", e);
      }
    }
    setShowCamera(false);
  };

  const openCamera = (questionId, type = 0) => {
    setActiveCameraQId(questionId);
    setShowCamera(true);
  };

  // Fixed function to handle image tap - properly set activeCameraQId
  const handleImageTap = (questionId, type = 0) => {
    const currentImage = answers[questionId];
    // Set the active camera question ID
    setActiveCameraQId(questionId);

    if (currentImage) {
      setSelectedImg(currentImage);
      setShowModal(true);
      // setActiveCameraQId(questionId+"Img"+type);
    } else {
      openCamera(questionId, type);
    }
  };

  const transformSurveyData = (flatData) => {
    const grouped = {};
    flatData?.forEach(item => {
      if (!grouped[item.QuestionId]) {
        grouped[item.QuestionId] = {
          QuestionId: item.QuestionId,
          Question: item.Question,
          QuestionType: item.QuestionTypeNew,
          QEnable: item.QEnable,
          EnableQuestion: item.EnableQuestion,
          DisableQuestion: item.DisableQuestion,
          QuestionSequence: item.QuestionSequence,
          CategorySequence: item.CategorySequence,
          QuestionRefImage: item.QuestionRefImage,
          MinLength: item.MinLength,
          MaxLength: item.MaxLength,
          LengthValidation: item.LengthValidation,
          QuestionImageMandatory: item.QuestionImageMandatory, // images
          QuestionImageAllow: item.QuestionImageAllow,
          ImageAllow1: item.ImageAllow1,
          ImageAllow2: item.ImageAllow2,
          Image1Mandatory: item.Image1Mandatory,
          Image2Mandatory: item.Image2Mandatory,
          Answers: []
        };
      }
      if (!['Number', 'Text', 'OnlyText'].includes(item.QuestionTypeNew)) {
        if (item.AnswerId || item.Answer) {
          grouped[item.QuestionId].Answers.push({
            AnswerId: item.AnswerId,
            Answer: item.Answer,
            isDisabled: item.DisableQuestion,
            isEnabled: item.EnableQuestion,
            ImageAllow2: item.ImageAllow2,
            ImageAllow1: item.ImageAllow1
          });
        }
      }
    });
    return Object.values(grouped).sort((a, b) => a.QuestionSequence - b.QuestionSequence);
  };

  const loadQuestions = () => {
    const query = `SELECT * FROM FeedbackCategory WHERE CategoryId = '${CategoryId}' AND SurveyId = '${SurveyId}' ORDER BY QuestionSequence ASC`;
    console.log('Executing SELECT query:', query);

    db.transaction(tx => {
      tx.executeSql(
        `SELECT * FROM FeedbackCategory WHERE CategoryId = ? AND SurveyId = ? ORDER BY QuestionSequence ASC`,
        [CategoryId, SurveyId],
        (tx, results) => {
          const rows = [];
          for (let i = 0; i < results.rows.length; i++) {
            rows.push(results.rows.item(i));
          }
          // console.log('Fetched Questions:', rows);

          setQuestionsFlat(rows);
          const transformed = transformSurveyData(rows);
          setQuestions(transformed);

          const enableMap = {};
          transformed.forEach(q => {
            enableMap[q.QuestionId] = q.QEnable === true || q.QEnable === 1;
          });
          setEnabledQuestions(enableMap);
          loadSavedAnswers();
        },
        (tx, err) => {
          console.log('Error loading questions:', err);
        }
      );
    });
  };

  const openRefImageView = (imgUrl) => {
    setZoomImageUrl(imgUrl);
    setShowZoomImage(true);
  };

  useEffect(() => {
    loadQuestions();
  }, []);

  useFocusEffect(
    React.useCallback(() => {
      const onBackPress = () => {
        if (showZoomImage) {
          setShowZoomImage(false);
          return true; // block default back action
        }
        return false; // allow default back behavior
      };

      const subscription = BackHandler.addEventListener('hardwareBackPress', onBackPress);

      return () => subscription.remove(); // ✅ modern cleanup
    }, [showZoomImage])
  );

  async function validate() {
    let isValid = true;

    for (let qtn of questions) {
      // Skip disabled questions
      // console.log("enabledQuestions[qtn.QuestionId]", typeof enabledQuestions[qtn.QuestionId] , qtn)
      if (!enabledQuestions[qtn.QuestionId]) continue;

      let selansid = '', selanswer = '', selimg = '', showImageTag = false, showImageTag2 = false, isImageMandateforAns = false;

      // console.log("answers===", JSON.stringify(answers))
      const answer = answers[qtn.QuestionId];
      const qType = qtn.QuestionType;
      const qText = qtn.Question;

      let image1 = answers[qtn?.QuestionId + "Img1"] || '';
      let image2 = answers[qtn.QuestionId + "Img2"] || '';
      // console.log(answers, "answer==========", image1, answer)
      // images

      const isTruthy = (val) => val === true || val === 'true' || val === 1 || val === '1';

      let isImg1mandatory = isTruthy(qtn.Image1Mandatory) || isTruthy(qtn.QuestionImageMandatory);
      let isImg2mandatory = isTruthy(qtn.Image2Mandatory);

      let isImgAllowed = ((qtn.QuestionImageAllow == true || qtn.QuestionImageAllow == 'true' || qtn.QuestionImageAllow == 1) || (qtn.QuestionType == "Image"));
      // let isImg1mandatory = (qtn.Image1Mandatory == "true") || (qtn.Image1Mandatory == true) || (qtn.QuestionImageMandatory == "true") || (qtn.QuestionImageMandatory == true)

      // let isImg2mandatory = (qtn?.Image2Mandatory == "true" || qtn?.Image2Mandatory == 'true');
      let isQuestionImageMandatory = qtn.QuestionType == "Image" ? (qtn?.QuestionImageMandatory == "true" || qtn?.QuestionImageMandatory == true) : true;

      // console.log("isImg1mandatory qutn", qtn.Image1Mandatory, "questionss", qtn)
      // TEXT / NUMBER / ONLYTEXT fields
      if (['Text', 'Number', 'OnlyText'].includes(qType)) {
        if (!answer || answer === '') {
          toastError('Please fill details for: ', `${qText}`);
          isValid = false;
          break;
        }

        const minL = qtn.MinLength || 0;
        const maxL = qtn.MaxLength || 10;
        const needsLengthValidation = qtn.LengthValidation === 'true' || qtn.LengthValidation === true || qtn.LengthValidation === 1; // works file recheck 

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

        if (needsLengthValidation) {
          if (answer?.length < minL) {
            toastError('', `Minimum ${minL} characters required in: ${qText}`);
            isValid = false;
            break;
          }
          if (answer?.length > maxL) {
            toastError('', `Maximum ${maxL} characters allowed in: ${qText}`);
            isValid = false;
            break;
          }
        }
      }

      // SINGLE CHOICE
      else if (qType === 'Single choice list') {
        console.log("Single choice questions", qType, answer)
        const selectedValue = answer?.split(',')[1]; // get the actual ANSWER value
        
        if (!selectedValue || selectedValue.trim() === '') {
          toastError('Please select an option for:', `${qText}`);
          isValid = false;
          break;
        }
        // if (!answer || answer === '') {
        //   toastError('Please select an option for:', `${qText}`);
        //   isValid = false;
        //   break;
        // }
      }

      // MULTI CHOICE
      else if (qType === 'Multi choice list') {
        if (!Array.isArray(answer) || answer.length === 0) {
          toastError('Please select at least one option for:', `${qText}`);
          isValid = false;
          break;
        }
      }
      // IMAGE
      else if (qType === 'Image') {
        if (!image1 || image1 === '') {
          toastError('', `Please capture image for: ${qText}`);
          isValid = false;
          break;
        }
      }

      if ((qtn.QuestionType == 'Single choice list' || qtn.QuestionType == 'Multi choice list')) {
        // console.log("answers[qtn?.QuestionId]----", answers[qtn?.QuestionId], qtn?.QuestionId)
        if (qtn.QuestionType != 'Multi choice list') {
          let slValue = answers[qtn?.QuestionId]?.split(",")
          selanswer = slValue?.[1] || ''
          selansid = slValue?.[0] || '0'
        }

        if (qtn.Answers && qtn.Answers.length > 0) {
          for (var i = 0; i < qtn.Answers.length; i++) {
            let ansss = qtn.Answers[i];

            let isandImgAl = (ansss.ImageAllow1 == true || ansss.ImageAllow1 == 'true' || ansss.ImageAllow1 == 1);
            let isandImgAl2 = (ansss.ImageAllow2 == true || ansss.ImageAllow2 == 'true' || ansss.ImageAllow2 == 1);

            let an = answers[qtn.QuestionId]
            // console.log("showImageTag2------", isandImgAl, ansss, qtn.AnswerId, qtn, an, answers)
            if (qtn.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
              showImageTag = true;
            }
            else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && qtn?.AnswerId?.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 && qtn?.AnswerId?.indexOf(ansss?.AnswerId) >= 0)) {
              showImageTag2 = true;
            }

          }
        }
      }

      // console.log("isImg1mandatory answerrrrrrrr", isImg1mandatory, image1, image2)

      if (showImageTag && isImg1mandatory && (!image1 || image1 === '')) {
        isValid = false;
        toastError('', `Please capture image for: ${qText}`);
        break;
      }
      if (showImageTag2 && isImg2mandatory && (!image2 || image2 === '')) {
        isValid = false;
        toastError('', `Please capture image for 2: ${qText}`);
        break;
      }

      // Other types like Audio, Rating, Date can be added similarly here
    }

    return isValid;
  }

  function setTextValue(value, qtn, type = '') {
    if (value !== '') {
      const isValid = validateNumber(value, type);
      if (!isValid) return;
    }

    let valToSave = value;

    // If it's decimal type and requires rounding
    if (qtn.QuestionType === 'Decimal' && qtn.LengthValidation === 'true') {
      const valSplit = value.split('.')[1]?.length;
      if (valSplit === undefined || valSplit < 2) {
        valToSave = value;
      } else if (/^\d+\.\d{2}$/.test(value)) {
        valToSave = Number(value).toFixed(2);
      }
    }

    setAnswers(prev => ({
      ...prev,
      [qtn.QuestionId]: valToSave
    }));

  }

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

  function onSaveCancel() {
    setShowAlert(false);
  }

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: GlobalTheme.colors.primary }}>
      <CustomHeader title="Feedback and Rating" rightIcon={IMAGES.menuIcon} leftIcon={IMAGES.leftArrowIcon} onLeftPress={() => navigation.goBack()} onRightPress={() => navigation.navigate('Dashboard')} />
      <KeyboardAwareScrollView extraScrollHeight={Platform.OS === 'android' ? 200 : 0} keyboardShouldPersistTaps="handled" enableOnAndroid contentContainerStyle={{ flexGrow: 1 }} style={{ flex: 1, backgroundColor: GlobalTheme.colors.white }}>
        <View style={{ flex: 1, backgroundColor: GlobalTheme.colors.white }}>
          <View style={styles.container}>
            <View style={styles.cardview}>
              <Text style={styles.categoryName}>{CategoryName}</Text>
              {questions.map((qtn) => {
                let selansid = '', selanswer = '';
                let imgQS = qtn.QuestionId + "Img"

                if (!enabledQuestions[qtn.QuestionId]) return null;

                let maxlen = (qtn.LengthValidation == true || qtn.LengthValidation == 'true') && qtn.MaxLength != null && qtn.MaxLength != '' ? qtn.MaxLength : 10;
                let minlen = (qtn.LengthValidation == true || qtn.LengthValidation == 'true') && qtn.MinLength != null && qtn.MinLength != '' ? qtn.MinLength : 0;
                // question image
                let isImgAllowed = ((qtn.QuestionImageAllow == true || qtn.QuestionImageAllow == 'true' || qtn.QuestionImageAllow == 1) || (qtn.QuestionType == "Image"));
                let isQuestionImageMandatory = qtn.QuestionType == "Image" ? (qtn?.QuestionImageMandatory == "true" || qtn?.QuestionImageMandatory == true) : true;

                // Answer Images
                let Image1Mandatory = (qtn.Image1Mandatory == "true") || (qtn.Image1Mandatory == true) || (qtn.QuestionImageMandatory == "true") || (qtn.QuestionImageMandatory == true)
                let Image2Mandatory = (qtn.Image2Mandatory == "true") || (qtn.Image2Mandatory == true)

                {/* console.log(Image1Mandatory, "Image1Mandatory", qtn.QuestionImageMandatory, "qtn.QuestionImageMandatory") */ }

                {/* console.log("maxlen", maxlen, "===========", "minlen", minlen); */ }
                let showImageTag = false, showImageTag2 = false
                if (qtn.QuestionType == 'Image' && isImgAllowed) {
                  showImageTag = true;
                }
                if ((qtn.QuestionType == 'Single choice list' || qtn.QuestionType == 'Multi choice list')) {
                  {/* console.log("answers[qtn?.QuestionId]----", answers[qtn?.QuestionId], qtn?.QuestionId) */ }
                  if (qtn.QuestionType != 'Multi choice list') {
                    let slValue = answers[qtn?.QuestionId]?.split(",")
                    selanswer = slValue?.[1] || ''
                    selansid = slValue?.[0] || '0'
                  }

                  if (qtn.Answers && qtn.Answers.length > 0) {
                    for (var i = 0; i < qtn.Answers.length; i++) {
                      let ansss = qtn.Answers[i];

                      let isandImgAl = (ansss.ImageAllow1 == true || ansss.ImageAllow1 == 'true' || ansss.ImageAllow1 == 1);
                      let isandImgAl2 = (ansss.ImageAllow2 == true || ansss.ImageAllow2 == 'true' || ansss.ImageAllow2 == 1);

                      let an = answers[qtn.QuestionId]
                      {/* console.log("showImageTag2------", isandImgAl, ansss, qtn.AnswerId, qtn, an, answers) */ }
                      if (qtn.QuestionType == 'Single choice list' && (isandImgAl && ansss.AnswerId == selansid)) {
                        showImageTag = true;
                      }
                      else if (qtn.QuestionType == 'Multi choice list' && (isandImgAl && qtn?.AnswerId?.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 && qtn?.AnswerId?.indexOf(ansss?.AnswerId) >= 0)) {
                        showImageTag2 = true;
                      }

                    }
                  }
                }

                return (
                  <View key={qtn.QuestionId} style={styles.questionBlock}>
                    <Text style={styles.questionText}>{qtn.Question}</Text>
                    {/* {console.log("qtn.QuestionRefImage", qtn.QuestionRefImage, Image2Mandatory)} */}
                    {qtn.QuestionRefImage != null && qtn.QuestionRefImage != '' && (
                      <TouchableOpacity style={styles.WItem_RefImgBtn} onPress={() => openRefImageView(qtn.QuestionRefImage)}>
                        <CustomIcon iconLibrary={'Entypo'} icon='image-inverted' size={30} color="black" />
                      </TouchableOpacity>
                    )}

                    {qtn.QuestionType === 'Single choice list' && (
                      <ModalSelector animationType='fade' optionContainerStyle={{ backgroundColor: '#fff' }} cancelContainerStyle={{ backgroundColor: '#fff' }}
                        key={qtn.QuestionId}
                        data={qtn.Answers.map(ans => ({ key: ans.AnswerId, label: ans.Answer }))}
                        initValue="Select one"
                        onChange={option => {
                          // console.log("option---", option)
                          const selectedAnswer = option.label;
                          const matchedRow = questionsFlat?.find(item =>
                            item.QuestionId === qtn.QuestionId && item.Answer === selectedAnswer
                          );
                          const enableQ = matchedRow?.EnableQuestion || '';
                          const disableQ = matchedRow?.DisableQuestion || '';
                          console.log("showImageTag------",showImageTag,showImageTag2)
                          handleAnswerChange(
                            qtn.QuestionId,
                            `${option?.key},${selectedAnswer}`,
                            enableQ,
                            disableQ,
                            qtn,
                            showImageTag,
                            showImageTag2
                          );
                        }}
                      >
                        <Text style={styles.selectorBox}>
                          {selanswer || '---Select option---'}
                        </Text>
                      </ModalSelector>
                    )}

                    {qtn.QuestionType === 'Multi choice list' && (
                      <MultiSelect
                        //  items={list_mcdata}
                        // uniqueKey="AnswerId"
                        // onSelectedItemsChange={(selectedItems) => { console.log('onSelectedItemsChange'); setMultiSelectValue(selectedItems, qtn) }}
                        // selectedItems={selansid}
                        items={qtn.Answers}
                        uniqueKey="AnswerId"
                        displayKey="Answer"
                        onSelectedItemsChange={(selected) =>
                          handleAnswerChange(qtn.QuestionId, selected, qtn.EnableQuestion, qtn.DisableQuestion, qtn , "", "")
                        }
                        selectedItems={
                          Array.isArray(answers[qtn.QuestionId])
                            ? answers[qtn.QuestionId].map(a => parseInt(a))
                            : []
                        }
                        selectText="Pick Items"
                        searchInputPlaceholderText="Search Items..."
                        searchIcon={<Icon name="search" size={18} color="#888" />}
                        tagRemoveIconColor="#ccc"
                        tagBorderColor="#ccc"
                        tagTextColor="#000"
                        selectedItemTextColor={GlobalTheme.colors.primary}
                        selectedItemIconColor="#000"
                        itemTextColor="#000"
                        styleMainWrapper={styles.multiSelect}
                        submitButtonText={'Submit'}
                        textColor={GlobalTheme.colors.black}
                        submitButtonColor={GlobalTheme.colors.secondary}
                        styleItemsContainer={styles.styleItemsContainer}
                        styleListContainer={styles.styleListContainer}
                        styleInputGroup={styles.styleInputGroup}
                        styleDropdownMenuSubsection={styles.styleDropdownMenuSubsection}
                        styleDropdownMenu={styles.styleDropdownMenu}
                      />
                    )}

                    {(qtn.QuestionType === 'Text' || qtn.QuestionType === 'OnlyText' || qtn.QuestionType === 'Number') && (
                      <TextInput
                        style={styles.textInput}
                        placeholder="Enter here..."
                        placeholderTextColor={'gray'}
                        keyboardType={qtn.QuestionType === 'Number' ? 'number-pad' : 'default'}
                        value={answers[qtn.QuestionId] || ''}
                        minLength={minlen}
                        maxLength={maxlen}
                        onChangeText={(val) => { setTextValue(val, qtn, qtn.QuestionType == 'Decimal' ? 'decimal' : qtn.QuestionType == 'Text' ? 'text' : qtn.QuestionType == 'OnlyText' ? 'onlytext' : 'numeric') }}
                        // onChangeText={(text) => handleAnswerChange(qtn.QuestionId, text)}
                        returnKeyType={(Platform.OS === 'ios') ? 'done' : 'next'}
                      />
                    )}

                    <View style={{ flexDirection: 'row', alignItems: 'center', flex: 1 }}>
                      {showImageTag &&
                        <View style={[]}>
                          <TouchableOpacity onPress={() => { handleImageTap(imgQS + 1) }}>
                            <Image source={answers[imgQS + 1] ? IMAGES.greenCameraIcon : Image1Mandatory ? IMAGES.redCameraIcon : IMAGES.normalCameraIcon} style={styles.iconStyle} />
                          </TouchableOpacity>
                        </View>
                      }

                      {showImageTag2 &&
                        <View style={[]}>
                          <TouchableOpacity onPress={() => { handleImageTap(imgQS + 2) }}>
                            <Image source={answers[imgQS + 2] ? IMAGES.greenCameraIcon : Image2Mandatory ? IMAGES.redCameraIcon : IMAGES.normalCameraIcon} style={styles.iconStyle} />
                          </TouchableOpacity>
                        </View>
                      }
                    </View>
                  </View>
                );
              })}
            </View>
          </View>
          {showZoomImage && zoomImageUrl && (
            <View style={styles.album_ZOOM_wrap}>
              <TouchableOpacity style={styles.closeIcon} onPress={() => setShowZoomImage(false)} >
                <Icon name="times-circle" size={35} color="#fff" />
              </TouchableOpacity>
              <ImageZoom cropWidth={Screen.screenWidth} cropHeight={Screen.screenHeight} imageWidth={Screen.screenWidth} imageHeight={Screen.screenHeight} style={styles.album_ZOOM} uri={zoomImageUrl} minScale={1} maxScale={5} doubleTapScale={3} isSingleTapEnabled isDoubleTapEnabled resizeMode="contain" />
            </View>
          )}

          {showModal && selectedImg && (
            <Modal visible={showModal} transparent={true} animationType="fade" onRequestClose={() => setShowModal(false)}>
              <View style={{ flex: 1, backgroundColor: '#00000088', justifyContent: 'center', alignItems: 'center' }}>
                <View style={styles.modal_view}>
                  <Image source={{ uri: selectedImg }} style={{ width: 250, height: 250, borderRadius: 10, marginBottom: 15 }} resizeMode="contain" />
                  <TouchableOpacity
                    style={styles.modal_view2}
                    onPress={() => {
                      setShowModal(false);
                      if (activeCameraQId) {
                        openCamera(activeCameraQId);
                      }
                    }}
                  >
                    <Text style={{ color: '#fff' }}>Retake</Text>
                  </TouchableOpacity>

                  <TouchableOpacity style={styles.modal_view2} onPress={() => setShowModal(false)}>
                    <Text style={{ color: '#fff' }}>Close</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </Modal>
          )}

          <ConfirmSaveAlert showAlert={showAlert} onCancelCallBack={onSaveCancel} onYesCallBack={saveData} msg="Do you really want to save data?" />
          {showCamera && (
            <Modal visible={showCamera} animationType="slide" presentationStyle="fullScreen">
              <CustomCamera
                onImageCaptured={handleImageCaptured}
                onClose={() => setShowCamera(false)}
              />
            </Modal>
          )}
          <Loader visible={loadingsave} loadingtext={'Saving Data...'} />
        </View>
      </KeyboardAwareScrollView>
      <View style={{ backgroundColor: GlobalTheme.colors.white }}>
        <CustomButton onPress={onSubmitData} title={'Save'} style={styles.btnbg} textstyle={styles.btntext} />
      </View>
    </SafeAreaView>
  );
};

export default FeedbackFormScreen;