import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useFocusEffect, useRoute } from '@react-navigation/native';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, DeviceEventEmitter, PermissionsAndroid, Keyboard, SectionList, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { clear_item, get_item } from '../components/localStorage';
import CustomHeader from '../components/customHeader';
import { Entypo, Ionicons, MaterialCommunityIcons } from '../components/icons';
import { UploadData2, ValidateEmail, checkRange, getAllFileForAFolder, restore_ImageWithMetaData, uploadContractFormFiles, validateNumber, validateNumber12, validateStoreAddStoreInfoText } from '../controller/functions';
import CustomLoader from '../components/CustomLoader';
import * as RNFS from 'react-native-fs';
import { db, CoverageImagePath, AppVersion, AddStoreImagePath, ImageFolderPath, URL_IMAGE } from '../constants/constants';
import MultiSelect from 'react-native-multiple-select';
import ModalSelector from 'react-native-modal-selector'

import CustomModal from '../components/CustomModal';
import { _checkLocationPermission } from '../components/geolocation';

import { METHODS, getMethodName } from '../constants/methodNames';
import { UploadImagesWithoutWait } from '../constants/uploadData';
import LinearGradient from 'react-native-linear-gradient';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg from '../assets/performics/camera_front_image.svg'
import GradientButton from '../components/gradientButton';
import { ConfirmSaveAlert } from '../components/alert';


function AddStore(props) {
    const route = useRoute();
    const ST = props.StaticText || {};
    // get all theme styles acc to current theme set
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);
    const globalStyle = globalStyles(props.DarkMode, route.name);

    const [processing, setProcessing] = useState(false);
    const [loaderTitle, setLoaderTitle] = useState();
    const [rerenderdata, setrerenderdata] = useState([]);
    // New
    const [StoreImage, setStoreImage] = useState('');
    const [SelectedImg, setSelectedImg] = useState('');
    const [StoreImgPath, setStoreImgPath] = useState('');
    const [showCamera, setShowCamera] = useState(false);
    const [addstoreconfigdata, setAddStoreConfigData] = useState([])
    const [storeData, setStoreData] = useState({});
    const [showModal, setShowModal] = useState(false);
    const [showModalAlert, setShowModalAlert] = useState(false);
    const [showDeffBeatAlert, setShowDeffBeatAlert] = useState(false);

    const selectimages = useRef({})
    const addstoreconfigCurr = useRef([])
    const [glb_gst, setglb_gst] = useState('');
    const [beatDay, setBeatDay] = useState('');

    const d1 = new Date();
    const d2 = moment(d1).format('MM/DD/YYYY');
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const handleUpload = () => {
        console.log("alerttt", validate())
        let rse = validate(); // Run validation
        if (!rse) return;
        console.log("Setting showModal to true"); // Debugging

        const today = getTodayName();
        console.log("today", today)
        if (beatDay && beatDay != '' && beatDay !== today) {
            setShowDeffBeatAlert(true)
        } else {
            setShowModalAlert(true); // Show the confirmation modal
        }
    };

    function getTodayName() {
        const days = [
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday",
            "Sunday",
        ];

        let dayNumber = new Date().getDay(); // Sunday = 0, Monday = 1...
        dayNumber = dayNumber === 0 ? 7 : dayNumber; // Sunday -> 7
        return days[dayNumber - 1]; // return weekday name
    }

    function onSaveCancel() {
        setShowModalAlert(false);
    }
    useEffect(() => {
        getdata();
        const onImageCapturedSubs = DeviceEventEmitter.addListener('onImageCaptured', (imgData) => { getImage(imgData) });
        return function cleanup() {
            onImageCapturedSubs.remove();
        };
    }, [])


    const validate = () => {
        let isValid = true;
        let rs = addstoreconfigdata
            .map(section => section.data)
            .flat()
        for (let i = 0; i < rs.length; i++) {
            const item = rs[i];
            if (item.answer === "" && item.IsMandatory === "true" && item.IsFieldShow == "true" && item.QuestionType != 'Image' && (item.FieldName != 'GSTNo' || item.FieldName != 'AadharNo')) {
                isValid = false;
                notify(`Please ${item.QuestionType == 'Text' || item.QuestionType == 'Number' ? 'Fill ' : 'Select'} ${item.DisplayName}`)
                break; // Exit loop early
            } if (item.answer === "" && item.IsMandatory === "true" && item.IsFieldShow == "true" && item.QuestionType == 'Image' && (item.FieldName != 'GSTImage' || item.FieldName != 'AadharFrontImage' || item.FieldName != 'AadharBackImage')) {
                isValid = false;
                notify(`Please Capture ${item.DisplayName}`)
                break; // Exit loop early
            }else if (item.answer != null && item.answer != '' && item.IsFieldShow == "true" && (item.QuestionType == 'Text' || item.QuestionType == 'Number') && (item.FieldName == "StoreName" || item.FieldName == "Address"||item.FieldName == "Locality"||item.FieldName == "ContactPerson"||item.FieldName == "BankName"||item.FieldName == "AccountHolderName") && item.answer.length < 3) {
                isValid = false;
                notify(`Please fill minimum 3 ${item.QuestionType == 'Text' ? 'Character ' : 'Digit'} ${item.DisplayName}`)
                break;
            }
            else if (item.answer != null && item.answer != '' && item.IsFieldShow == "true" && (item.QuestionType == 'Text' || item.QuestionType == 'Number') && item.FieldName == "Pincode" && item.answer.length < 6) {
                isValid = false;
                notify(`Please fill minimum 6 ${item.QuestionType == 'Text' ? 'Character ' : 'Digit'} ${item.DisplayName}`)
                break;
            } else if (item.answer != null && item.answer != '' && item.IsFieldShow == "true" && (item.QuestionType == 'Text' || item.QuestionType == 'Number') && item.FieldName == 'Phone' && item.answer.length < 10) {
                isValid = false;
                notify(`Please fill correct ${item.DisplayName}`)
                break;
            }
            else if (item.answer != null && item.answer != '' && item.IsFieldShow == "true" && (item.QuestionType == 'Text' || item.QuestionType == 'Email') && item.FieldName == 'Email' && !emailRegex.test(item.answer)) {
                isValid = false;
                notify(`Please fill correct ${item.DisplayName}`)
                break;
            }
            else if (item.answer === "" && item.IsMandatory === "true" && item.IsFieldShow == "true" && item.FieldName == 'TaxType' && (item.FieldName != 'GSTNo')) {
                isValid = false;
                notify(`Please Select ${item.DisplayName}`)
                break; // Exit loop early
            }

            else if (item.IsMandatory === "true" && item.IsFieldShow == "true" && (item.FieldName == 'GSTNo' || item.FieldName == 'GSTImage' || item.FieldName == 'AadharNo' || item.FieldName == 'AadharFrontImage' || item.FieldName == 'AadharBackImage') && !validatespecific()) {
                isValid = false;
                break; // Exit loop early
            } else if (item.answer != null && item.answer != "" && item.IsFieldShow == "true" && item.FieldName == 'GSTNo' && item.answer.length < 15) {
                notify(`Please fill correct ${item.DisplayName}`)
                isValid = false;
                break;
            } else if (item.answer != null && item.answer != "" && item.IsFieldShow == "true" && item.FieldName == 'AadharNo' && item.answer.length < 12) {
                notify(`Please fill correct ${item.DisplayName}`)
                isValid = false;
                break;
            }

            else if (item.answer != null && item.answer != '' && item.IsFieldShow == "true" && (item.QuestionType == 'Text' || item.QuestionType == 'Number') && item.FieldName == 'Pan' && item.answer.length < 10) {
                isValid = false;
                notify(`Please fill correct ${item.DisplayName}`)
                break;
            }
            else if (item.answer != null && item.answer != '' && item.IsFieldShow == "true" && (item.QuestionType == 'Text' || item.QuestionType == 'Number') && (item.FieldName == 'AccountNo') && item.answer.length < 8) {
                isValid = false;
                notify(`Please fill correct ${item.DisplayName}`)
                break;
            }
            else if (item.answer != null && item.answer != '' && item.IsFieldShow == "true" && (item.QuestionType == 'Text' || item.QuestionType == 'Number') && (item.FieldName == 'IFSC') && item.answer.length < 11) {
                isValid = false;
                notify(`Please fill correct ${item.DisplayName}`)
                break;
            }
        }
        return isValid;
    };


    const validatespecific = () => {
        let isValid = true;
        let rs = addstoreconfigdata
            .map(section => section.data)
            .flat()
        for (let i = 0; i < rs.length; i++) {
            const item = rs[i];
            console.log("dattttt", item)
            if (glb_gst == 'GST') {
                if (item.answer === "" && item.IsMandatory === "true" && item.IsFieldShow == "true" && item.FieldName == 'GSTNo') {
                    notify(`Please fill ${item.DisplayName}`)
                    isValid = false;
                    break;
                } else if (item.answer != null && item.answer != "" && item.IsFieldShow == "true" && item.FieldName == 'GSTNo' && item.answer.length < 15) {
                    notify(`Please fill correct ${item.DisplayName}`)
                    isValid = false;
                    break;
                } else if (item.answer === "" && item.IsMandatory === "true" && item.IsFieldShow == "true" && item.FieldName == 'GSTImage') {
                    notify(`Please Capture ${item.DisplayName}`)
                    isValid = false;
                    break;
                }
            } else if (glb_gst == 'Non GST') {
                if (item.answer === "" && item.IsMandatory === "true" && item.IsFieldShow == "true" && item.FieldName == 'AadharNo') {
                    notify(`Please fill ${item.DisplayName}`)
                    isValid = false;
                    break;
                } else if (item.answer != null && item.answer != "" && item.IsFieldShow == "true" && item.FieldName == 'AadharNo' && item.answer.length < 12) {
                    notify(`Please fill correct ${item.DisplayName}`)
                    isValid = false;
                    break;
                } else if (item.answer === "" && item.IsMandatory === "true" && item.IsFieldShow == "true" && (item.FieldName == 'AadharFrontImage' || item.FieldName == 'AadharBackImage')) {
                    notify(`Please Capture ${item.DisplayName}`)
                    isValid = false;
                    break;
                }
            }

        }

        return isValid;
    };

    async function getdata() {
        try {
            let token = await get_item('loginToken');
            let loginInfo = await get_item('loginInfo');
            const loginDetails = JSON.parse(loginInfo);
            let desg = loginDetails.Designation || '';

            await db.transaction(async (txn) => {
                let q = `SELECT DISTINCT BlockName,DisplayName,DefaultValue,QuestionType,ListJson,
                CASE WHEN IsMandatory = 1 THEN 'true' ELSE 'false' END AS IsMandatory,
                   CASE WHEN IsFieldShow = 1 THEN 'true' ELSE 'false' END AS IsFieldShow,
    FieldName, 
    CASE 
        WHEN FieldName = 'Pincode' THEN 6
        WHEN FieldName = 'Phone' THEN 10
        WHEN FieldName = 'GSTNo' THEN 15
		 WHEN FieldName = 'AadharNo' THEN 12
		  WHEN FieldName = 'Pan' THEN 10
		   WHEN FieldName = 'IFSC' THEN 11
		    WHEN FieldName = 'AccountNo' THEN 20
        ELSE 50
    END AS MaxLength
FROM Mapping_AddStoreConfiguration `;

                await txn.executeSql(q, [], async (txn2, txnres) => {
                    if (txnres.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            console.log("querrrrrr--data", data)
                            if (data) {
                                arr.push({ ...data, answer: '', answerid: '' });
                            }
                        }

                        // Ensure valid transformation
                        const groupedData = arr.reduce((acc, item, index) => {
                            // if (item?.IsFieldShow === "true") {
                            let section = acc.find(sec => sec?.title === item?.BlockName);
                            if (section) {
                                section.data.push(item);
                            } else {
                                acc.push({ title: item?.BlockName, isShow: item?.IsFieldShow, data: [item] });
                            }
                            // }
                            return acc;
                        }, []);

                        if (Array.isArray(groupedData)) {
                            setAddStoreConfigData([...groupedData]);
                        } else {
                            console.error("Invalid Data Structure:", groupedData);
                        }

                        setrerenderdata(prev => !prev);
                    } else {
                        console.warn("No Data Found in Mapping_AddStoreConfiguration Table");
                    }
                }, (txnE, txnerr) => { console.error("SQL Error:", txnerr); });
            });
        } catch (err) {
            console.error("Error in getdata:", err);
        }
    }

    async function upload_Data() {
        setShowModalAlert(false)
       // console.log("addstoreconfigdata", addstoreconfigdata);
        let d1 = new Date();
        let d2 = moment(d1).format('MM/DD/YYYY');
        let fpath = Platform.OS == 'ios' ? StoreImgPath.replace('file://', '') : StoreImgPath;
        console.log(fpath, 'path of imaggege');
        setProcessing(true);

        setLoaderTitle('Uploading Data...');

        let rs = addstoreconfigdata
            .map(section => section.data)
            .flat()
            .reduce((acc, curr) => {
                //console.log("data_verify", curr)
               // console.log("data_verify1", acc)
                const value = ((curr.answerid == "" || curr.answerid == "0" || curr.QuestionType == "Image") && curr.IsFieldShow == "true") ? curr.answer == "0" ? "" : curr.answer : ((curr.IsFieldShow == "false" && curr?.DefaultValue != "") ? curr?.DefaultValue : (curr.answerid == 0 || curr.answerid == '0') ? "" : curr.answerid);
                return { ...acc, [curr.FieldName]: value, "verificationReq": "0", UserId: props.UserId };
            }, {});


        let postData = {
            "MID": 0,
            "Keys": "KEY1",
            "JsonData": JSON.stringify([rs]),
            "UserId": props.UserId,
        };

       // console.log("addstoreinfo-------------ad", addstoreconfigdata)

        const url = props.baseurl + "UploadJsonDirect";

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

        let rsFile = addstoreconfigdata
            .map(section => section.data)
            .flat()
            .filter(itm => itm.QuestionType == "Image" && itm?.answer != "");

        await uploadContractFormFiles12(rsFile)

        await UploadData2(url, postData)
            .then(async (res) => {
                console.log('res: 12', res);
                if (res?.UploadJsonDirectResult == "Success") {
                    notify("Data Save Successfully.");
                    setProcessing(false);
                    if (props.AddNewStoreInJCP == "true" || props.AddNewStoreInJCP == true) {
                        if (props?.AddNewStoreVerificationReq) {
                            props.navigation.navigate('AddedStoreList')
                        } else {
                            props.set_startDownload({ startDownload: true });
                            props.navigation.navigate('NoticeBoard')
                        }
                    }
                }
                else {
                    notify(res?.UploadJsonDirectResult);
                    setProcessing(false);
                }
            })
            .catch((err) => {
                console.log(err); setProcessing(false);
            });

    }

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


        var isAllUploaded = false;
        return await Promise.all(
            allfiles.map(async (file, i) => {
                let index = i;
                let actualfilepath = 'file://' + `${ImageFolderPath}${file.answer}`;
                console.log("actualfilepath---", actualfilepath)
                let isExists = await RNFS.exists(actualfilepath).then((res) => { return res; });
                console.log('isExists file', isExists, file.answer, file);
                let isImageUploaded = false;
                // isExists==false
                if (isExists) {
                    let postData = new FormData();
                    postData.append('file', {
                        uri: actualfilepath,
                        type: file?.answerid,
                        name: file.answer,
                    });

                    postData.append('Foldername', "KYCImages");
                    postData.append('Path', d2);

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

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

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

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

    function render_Picker(label_key, value_key, onChange = () => { }, selected_data = {}) {
        let data = [];
        let qtn = selected_data.qtn || {};
        let index = selected_data.index;
        let sectionIndex = selected_data.sectionIndex

        // Ensure ListJson is parsed correctly
        let allAnswers = [];
        if (typeof qtn.ListJson === "string") {
            try {
                allAnswers = JSON.parse(qtn.ListJson);
            } catch (error) {
                console.error("Error parsing ListJson:", error);
            }
        } else if (Array.isArray(qtn.ListJson)) {
            allAnswers = qtn.ListJson;
        }

        let isQtnDisabled = qtn.isDisabled ? true : false;

        // Dynamically populate dropdown options
        data = allAnswers.map((item, index) => {
            return {
                key: index,
                label: item[label_key],
                value: item[value_key],
                component: selected_data.value == item[value_key] ? (
                    <View style={customStyle.addvis_selectedOpStyle}>

                        <Text style={customStyle.addvis_selectedOpTextStyle}>{item[label_key]}</Text>
                    </View>
                ) : null
            };
        });

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

        return (
            <ModalSelector
                data={data}
                touchableActiveOpacity={0.8}
                style={[customStyle.addVisPickerStyle]}
                onChange={(option) => onChange(option, qtn, index, sectionIndex)}
                overlayStyle={customStyle.addVisPickerOverlay}
                cancelContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
                optionStyle={customStyle.addvis_opStyle}
                optionTextStyle={customStyle.addvis_opTextStyle}
                selectedKey={selected_data.value}
                disabled={isQtnDisabled}
            >
                <Text style={[
                    customStyle.WQPicker_InputStyle,
                    isQtnDisabled ? customStyle.addVisPicker_Dis_InputStyle : { backgroundColor: PageTheme.$secondary_color_light }
                ]}>
                    {selected_data.value ? selected_data.value : '-' + ST.select + '-'}
                </Text>
            </ModalSelector>
        );
    }

    function onselectionChange(option, qtn, index, sectionIndex) {
        console.log(option, qtn, sectionIndex, index, "confirmmmmmm----------11111111111");
        let updatedData = addstoreconfigdata.map((section, secIndex) => {
            if (secIndex === sectionIndex) {
                // Clone the section and its data to ensure immutability
                const updatedSection = { ...section, data: [...section.data] };

                // Update the specific item in the section's data
                const updatedItem = { ...updatedSection.data[index] };
                updatedItem.answerid = option.value || "0";
                updatedItem.answer = option.label;
                // Replace the item in the section's data
                updatedSection.data[index] = updatedItem;
                const updatedItem2 = [...updatedSection.data];

                if (qtn?.FieldName === 'BeatDay') {
                    setBeatDay(option?.label)
                    console.log("lavel---", option?.label)
                }

                if (updatedItem?.FieldName === 'TaxType' && updatedItem?.answer === "GST") {
                    setglb_gst("GST");
                    for (let i = 0; i < updatedItem2.length; i++) {
                        if (["AadharNo", "AadharFrontImage", "AadharBackImage"].includes(updatedItem2[i].FieldName)) {
                            updatedItem2[i].IsFieldShow = "false";
                            updatedItem2[i].answer = "";
                            updatedItem2[i].answerid = 0;
                        }

                        if (["GSTNo", "GSTImage"].includes(updatedItem2[i].FieldName)) {
                            updatedItem2[i].IsFieldShow = "true";
                        }
                    }
                } else if (updatedItem?.FieldName === 'TaxType' && updatedItem?.answer === "Non GST") {
                    setglb_gst("Non GST")
                    for (let i = 0; i < updatedItem2.length; i++) {
                        if (["GSTNo", "GSTImage"].includes(updatedItem2[i].FieldName)) {
                            updatedItem2[i].IsFieldShow = "false";
                            updatedItem2[i].answer = "";
                            updatedItem2[i].answerid = 0;
                        }

                        if (["AadharNo", "AadharFrontImage", "AadharBackImage"].includes(updatedItem2[i].FieldName)) {
                            updatedItem2[i].IsFieldShow = "true";
                        }
                    }
                }

                updatedSection.data = updatedItem2
                return updatedSection;
            }
            return section; // Return unchanged sections
        });

        console.log("finalData==========", JSON.stringify(updatedData));
        setAddStoreConfigData([...updatedData]) // Update state in a single call
    }

    function setTextValue(value, qtn, sectionIndex, index, type = "") {

        console.log(value, qtn, sectionIndex, index, type = "")
        if (value != '') {
            let isValid = validateNumber(value, type);
            console.log("type:", type, isValid);
            if (!isValid) {
                return;
            }
        }

        let updatedData = addstoreconfigdata.map((section, secIndex) => {
            if (secIndex === sectionIndex) {

                const updatedSection = { ...section, data: [...section.data] };

                const updatedItem = { ...updatedSection.data[index] };
                updatedItem.answerid = "0";
                updatedItem.answer = value;

                updatedSection.data[index] = updatedItem;

                return updatedSection;
            }
            return section;
        });

        setAddStoreConfigData(updatedData);

    }

    async function openCamera(dataindex) {
        console.log("dataindex", dataindex)
        // setSelectImages(dataindex)
        selectimages.current = dataindex
        addstoreconfigCurr.current = addstoreconfigdata
        // setShowCamera(true);
        props.navigation.navigate('CameraScreen', { 'getImage': getImage, 'cameraType': ('back'), 'CheckInCameraGallery': props.CheckInCameraGallery, storeData: storeData, enableCameraFlip: (props.CheckInSwitchingCamera ? true : false) })
    }

    async function getImage(imgdata) {
        if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify(ST.Cameraunavailable);
        }

        else if (typeof imgdata == 'object' && imgdata.uri != null) {
            const img = imgdata;
            const storeDataDetail = imgdata.storeData || {}
            const imgurl = img.uri, imgWidth = img.width, imgHeight = img.ExtendedHeight;
            let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
            let picture_clickedd = isImgFromGallery == true ? img.datetime : new Date();
            ////change by jeevanp
            let picture_clicked_time = moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name = moment(picture_clickedd).format('MMDDYYYY_HHmmss')
            console.log("time", picture_clicked_time);
            console.log("time1", picture_clicked_time_for_pic_name);
            ////change by jeevanp
            let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
            let calculate_tym_date_over_img = picture_clicked_time;

            let filename = (props.UserId || '') + '_AddStoreImg-' + calculate_tym_date_for_filename + '.jpg';
            console.log(filename, "file_name");

            const mark_text1 = calculate_tym_date_over_img;
            const mark_text2 = 'User Id:' + props.UserId + ' | Image Type: Add Store Info' + ' | Date:' + calculate_tym_date_over_img;
            console.log(mark_text1 + "\n" + mark_text2, "mark_text2");

            setStoreImage(filename);
            console.log("selectimages========", selectimages.current)

            let sectionIndex = selectimages.current?.sectionIndex;
            let index = selectimages.current?.index;

            let imagePath = `${ImageFolderPath}${filename}`;
            console.log("checkin imgurl:", imagePath, imgurl);
            RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    // render data with clicked image
                    let uri = 'file://' + imagePath;
                    setStoreImgPath(uri);
                    setSelectedImg(uri)
                    let updatedData = addstoreconfigCurr.current.map((section, secIndex) => {
                        console.log("secIndex", secIndex, "sectionIndex", sectionIndex)
                        if (secIndex == sectionIndex) {
                            // Clone the section and its data to ensure immutability
                            const updatedSection = { ...section, data: [...section.data] };

                            // Update the specific item in the section's data
                            const updatedItem = { ...updatedSection.data[index] };
                            const getMimeType = (uri) => {
                                const extension = uri.split('.').pop().toLowerCase();

                                const mimeTypes = {
                                    jpg: 'image/jpeg',
                                    jpeg: 'image/jpeg',
                                    png: 'image/png',
                                    gif: 'image/gif',
                                    webp: 'image/webp',
                                };

                                return mimeTypes[extension] || 'application/octet-stream'; // Fallback
                            };

                            const mimeType = getMimeType(img.uri);
                            console.log(mimeType);
                            console.log(mimeType, "img===========", img)
                            updatedItem.answerid = mimeType;
                            updatedItem.answer = filename;

                            // Replace the item in the section's data
                            updatedSection.data[index] = updatedItem;

                            return updatedSection;
                        }
                        return section; // Return unchanged sections
                    });

                    setAddStoreConfigData(updatedData)
                    console.log("updatedData========", JSON.stringify(updatedData))
                    selectimages.current = {}
                    // add metdata then resize image and restored back to the imagePath
                    let restore_data = { "destFilePath": imagePath, "imgurl": imgurl, imgWidth, imgHeight, mark_text1, mark_text2 }
                    let is_restored = await restore_ImageWithMetaData(restore_data, imgdata);
                    console.log("image restored:", is_restored);
                }).catch(err => {
                    console.log('ERROR: image file write failed!!!', err);
                    console.log(err.message, err.code);
                });
        }
    }


    function _OpenCaptureImage_Modal(img) {
        const isImageCap = (img != '' || img != null) ? true : false;
        let camera2Label = 'test';
        return (
            <CustomModal
                style={customStyle.PromoImgModal}
                title={"Checkin Image"}
                // message={camera2Label}
                titleStyle={customStyle.PromoImgModal_title}
                messageStyle={customStyle.PromoImgModal_subtitle}
                showModal={showModal}
            >
                {
                    <View style={customStyle.PromoImgModalCon}>
                        <View style={customStyle.PromoImgModal_ImgWrap}>

                            <Image style={[customStyle.PromoImgModal_Img, (Platform.OS == 'ios' ? customStyle.android_flipIMageView : {})]} source={{ uri: SelectedImg }} />
                        </View>
                        <TouchableOpacity style={customStyle.PromoImgModal_CameraSmall} onPress={() => { openCamera() }}>
                            <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
                        </TouchableOpacity>
                    </View>
                }
            </CustomModal>
        )
    }

    function _RenderBeatDayDialog(showModal, beatDay, onClose, onCancel) {
        const today = getTodayName();
        return (
            <CustomModal
                style={customStyleBeat.BeatDayModal}
                title={"Beat Mismatch"}
                titleStyle={customStyleBeat.BeatDayModal_Title}
                messageStyle={customStyleBeat.BeatDayModal_Subtitle}
                showModal={showModal}
            >
                <View style={customStyleBeat.BeatDayModal_Content}>
                    <Text style={customStyleBeat.BeatDayModal_Message}>
                        Today is <Text style={{ fontWeight: "bold" }}>{today}</Text>.{"\n"}
                        You have selected Beat as{" "}
                        <Text style={{ fontWeight: "bold" }}>{beatDay}</Text>.
                    </Text>

                    {/* Buttons Row */}
                    <View
                        style={{
                            flexDirection: "row",
                            justifyContent: "space-around",
                            width: "100%",
                            marginTop: 20,
                        }}
                    >
                        {/* Cancel Button */}
                        <TouchableOpacity
                            style={[
                                customStyleBeat.BeatDayModal_Button,
                                { backgroundColor: "#999" },
                            ]}
                            onPress={onCancel}
                        >
                            <Text style={customStyleBeat.BeatDayModal_ButtonText}>Cancel</Text>
                        </TouchableOpacity>

                        {/* OK Button */}
                        <TouchableOpacity
                            style={customStyleBeat.BeatDayModal_Button_proceed}
                            onPress={onClose}
                        >
                            <Text style={customStyleBeat.BeatDayModal_ButtonText}>Proceed</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </CustomModal>
        );
    }



    function cancelImage() {
        // setImage1('');
        setSelectedImg('');
        setShowModal(false);
    }

    function _render_captureImage() {
        const isImageAvlbl = StoreImage != '' && StoreImage != null && StoreImgPath != '' && StoreImgPath != null;

        return (
            <View style={[customStyle.gtag_sImageWrap, { bottom: -40 }]}>
                <View style={customStyle.gtag_sImagelbl}>
                    <TouchableOpacity style={[customStyle.gtag_sImage_View]} onPress={() => { isImageAvlbl ? OpenImgModal(StoreImgPath) : openCamera() }}>
                        {!isImageAvlbl && <CameraImg width={80} height={80} />}
                        {isImageAvlbl && <CameraImg3 style={{ marginLeft: 5 }} width={80} height={80} />}
                    </TouchableOpacity>
                    {/* {isImageAvlbl && <Image style={[customStyle.gTag_Image,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:StoreImgPath}}/>}     */}
                    <Text style={[customStyle.gtag_sImagelblText, { marginTop: 0 }]}>{ST.ClickSelfieinfrontofStore}</Text>
                </View>

            </View>
        );
    }

    // console.log("addstoreconfigdata", JSON.stringify(addstoreconfigdata))

    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title={ST.AddStore} screen={props?.AddNewStoreVerificationReq ? "AddStore" : ""} />
            {ConfirmSaveAlert(props, showModalAlert, onSaveCancel, upload_Data, "Do you really want to add store ?")}
            {_OpenCaptureImage_Modal()}
            {_render_captureImage()}
            {/* Call your custom render function here */}
            {_RenderBeatDayDialog(showDeffBeatAlert, beatDay, () => { setShowModalAlert(true); setShowDeffBeatAlert(false) }, () => setShowDeffBeatAlert(false))}

            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
                <View style={[customStyle.pageContentWrapper]}>
                    <ScrollView style={{ flex: 1, width: '100%', paddingRight: 20, paddingLeft: 10 }}>
                        <SectionList
                            sections={addstoreconfigdata}
                            keyExtractor={(item, index) => `${item.FieldName}_${index}`} // Ensure unique keys for items

                            renderSectionHeader={({ section }) => {
                                // Find the index of the current section
                                console.log("section_header...", section)
                                if ((section?.isShow == "true" || section?.isShow == true)) {
                                    return (
                                        <View style={customStyle.opening_Stock_wrap}>
                                            <View style={[customStyle.opening_Stock_cat, { paddingVertical: 5 }]}>
                                                <TouchableOpacity activeOpacity={0.5} style={customStyle.opening_Stock_catHdr}>
                                                    <LinearGradient
                                                        colors={[PageTheme.$primary_color, PageTheme.$secondary_color_light]}
                                                        start={{ x: 0, y: 0 }}
                                                        end={{ x: 1, y: 1 }}
                                                        style={customStyle.opening_Stock_catInner}
                                                    >
                                                        <Text style={customStyle.opening_Stock_catText}>
                                                            {section?.title ? section?.title : ''}
                                                        </Text>
                                                    </LinearGradient>
                                                </TouchableOpacity>
                                            </View>
                                        </View>
                                    );
                                }

                            }}

                            renderItem={({ item, index, section }) => {

                                const sectionIndex = addstoreconfigdata.findIndex(sec => sec.title === section.title);

                                // console.log(section,"sectionIndex=======",sectionIndex)
                                let qtn = item;

                                let qtnIndex = index;
                                let selansid = "", selanswer = "", showImageTag1 = false, showImageTag2 = false;
                                let id_key = `${qtn.FieldName}_AnswerId`;
                                let ans_key = `${qtn.FieldName}_Answer`;
                                let multi_key = `${qtn.FieldName}_MultiOption`;

                                let list_mcdata = [];

                                // let isNAImageAvl=item.CategoryNotExistCamera=='true' || data.CategoryNotExistCamera==1?1:0;
                                // let NAImage1=isNAImageAvl==1 && data.CatNAImage!=null?data.CatNAImage:'';
                                // let NAImage1Path=NAImage1!=''?`file://${ImageFolderPath+menu1.ScreenName}/`+'':'';

                                let NAImage1Path = ''

                                if (qtn.IsFieldShow == "false") {
                                    return null
                                }

                                return (
                                    <View style={[customStyle.opening_Stock_wrap, { paddingHorizontal: 2 }]}>
                                        <Text style={customStyle.AddStockM_label}>{qtn.DisplayName}</Text>

                                        {qtn.QuestionType === "Single choice list" &&
                                            render_Picker("Name", "Id", onselectionChange, { value: qtn.answer, qtn, sectionIndex, index })
                                        }

                                        {qtn.QuestionType === "Multi choice list" &&
                                            <MultiSelect
                                                items={list_mcdata}
                                                uniqueKey="AnswerId"
                                                onSelectedItemsChange={(selectedItems) => setMultiSelectValue(selectedItems, qtn, window)}
                                                selectedItems={selansid}
                                                selectText="Pick Items"
                                                searchInputPlaceholderText={`${ST.SearchItems}...`}
                                                tagRemoveIconColor={PageTheme.$primary_color}
                                                tagBorderColor={PageTheme.$primary_color}
                                                tagTextColor={PageTheme.$primary_color}
                                                selectedItemTextColor={PageTheme.$primary_color}
                                                selectedItemIconColor={PageTheme.$primary_color}
                                                itemTextColor={PageTheme.$text_color}
                                                displayKey="Answer"
                                                searchInputStyle={EStyle_Qtn_MultiChoice}
                                                submitButtonColor={PageTheme.$primary_color}
                                                submitButtonText={ST.Submit}
                                            />
                                        }

                                        {["Number", "Decimal", "Text", "TextSpc", "Number", "Email"].includes(qtn.QuestionType) &&
                                            <TextInput
                                                style={[customStyle.WStkInputStyle, { textAlign: 'left' }]}
                                                placeholder=""
                                                autoComplete="off"
                                                placeholderTextColor={PageTheme.$placeholder_color}
                                                keyboardType={
                                                    qtn.QuestionType === "Decimal" ? "decimal-pad" :
                                                        qtn.QuestionType === "Number" ? "number-pad" :
                                                            qtn.QuestionType === "TextSpc" ? "default" :
                                                                qtn.QuestionType === "Email" ? "email-address" :
                                                                    qtn.QuestionType === "Text" ? "Text" :
                                                                        "default"
                                                }
                                                maxLength={qtn.MaxLength || 60}
                                                value={qtn.answer + ""}


                                                onChangeText={(val) => {
                                                    let sanitizedValue = val;

                                                    if (qtn.QuestionType === "Number") {
                                                        // Allow only whole numbers (no decimals, no special chars)
                                                        sanitizedValue = val.replace(/[^0-9]/g, "");
                                                    } else if (qtn.QuestionType === "Decimal") {
                                                        // Allow only valid decimal numbers
                                                        sanitizedValue = val.replace(/[^0-9.]/g, ""); // Remove non-numeric & non-dot
                                                        if ((sanitizedValue.match(/\./g) || []).length > 1) {
                                                            sanitizedValue = sanitizedValue.replace(/\.+$/, ""); // Remove extra dots
                                                        }
                                                    } else if (qtn.QuestionType === "Text") {
                                                        if (qtn?.FieldName === 'GSTNo' || qtn?.FieldName === 'Pan' || qtn?.FieldName === 'IFSC' || qtn?.FieldName === 'AccountNo') {
                                                            sanitizedValue = val.replace(/[^a-zA-Z0-9]/g, "");
                                                        } else if (qtn?.FieldName === 'StoreName' || qtn?.FieldName === 'Address' || qtn?.FieldName === 'Locality') {
                                                            sanitizedValue = val.replace(/[^a-zA-Z0-9 \-\/(),.&:]/g, "");
                                                        }
                                                        else {
                                                            // Allow only letters, numbers, and spaces (no special characters)
                                                            sanitizedValue = val.replace(/[^a-zA-Z0-9 ]/g, "");
                                                        }

                                                    }

                                                    setTextValue(sanitizedValue, qtn, sectionIndex, index);
                                                }}
                                            />
                                        }


                                        {qtn.QuestionType === "Image" && <View style={[customStyle.openStk_prdCameras]}>
                                            <View style={[customStyle.openStkCameraCon, customStyle.WSCameraCon]}>

                                                {(qtn.answer == '' || qtn.answer == null) ?
                                                    <TouchableOpacity style={[]} onPress={() => { openCamera({ sectionIndex, index }, {}, 0, '1', '3') }}>
                                                        <CameraImg2 width={50} height={50} />
                                                    </TouchableOpacity> : (qtn.answer != '' && qtn.answer != null) ?
                                                        <TouchableOpacity onPress={() => {
                                                            // OpenImgModal(qtn.answer, window, {}, 0, '1', '3')
                                                        }}>
                                                            <CameraImg3 width={50} height={50}  />
                                                        </TouchableOpacity> : null
                                                }

                                            </View>
                                        </View>
                                        }

                                    </View>
                                );
                            }}
                        />

                        <View style={[customStyle.addstore_Stock_btnWrap, {}]}>
                            <GradientButton {...props} title={ST.Save} onPress={() => { handleUpload() }} />
                        </View>
                    </ScrollView>

                </View>
            </LinearGradient>
        </Container>
    );
}

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



const customStyleBeat = StyleSheet.create({
    BeatDayModal: {
        padding: 20,
    },
    BeatDayModal_Title: {
        fontSize: 20,
        fontWeight: "bold",
        color: "#333",
        textAlign: "center",
        marginBottom: 10,
    },
    BeatDayModal_Subtitle: {
        fontSize: 16,
        color: "#666",
        textAlign: "center",
        marginBottom: 15,
    },
    BeatDayModal_Content: {
        padding: 10,
    },
    BeatDayModal_Message: {
        fontSize: 16,
        textAlign: "center",
        color: "#444",
    },
    BeatDayModal_Button: {
        backgroundColor: "#2196F3",
        paddingVertical: 10,
        paddingHorizontal: 25,
        borderRadius: 10,
    },
    BeatDayModal_Button_proceed: {
        backgroundColor: "#2196F3",
        paddingVertical: 10,
        paddingHorizontal: 25,
        marginStart: 30,
        borderRadius: 10,
    },
    BeatDayModal_ButtonText: {
        color: "#fff",
        fontWeight: "bold",
        fontSize: 16,
    },
});





