import React, { useState, useCallback, useEffect } from 'react';
import Container from '../components/container';
import { useRoute, useFocusEffect } from '@react-navigation/native';
import { customStyles, GetPageTheme } from '../styles/Global';
import { View, Text, TouchableOpacity, Platform, FlatList, StyleSheet, Image, ScrollView, BackHandler, Alert } from 'react-native';
import { db, ImageFolderPath, URL_IMAGE } from '../constants/constants';
import * as RNFS from 'react-native-fs';
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import CustomCamera from '../components/Camera';
import { METHODS, getMethodName } from '../constants/methodNames';
import moment from 'moment';
import CustomHeader from '../components/customHeader';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { useNavigation } from '@react-navigation/native';
import Icon from "react-native-vector-icons/Ionicons";
import CustomModal from '../components/CustomModal';
import { getDownloadJson1, restore_ImageWithMetaData, UploadData2 } from '../controller/functions';
import { MaterialCommunityIcons } from '../components/icons';
import { ConfirmSaveAlert } from '../components/alert';
import GradientButton from '../components/gradientButton';
import { UploadImagesWithoutWait } from '../constants/uploadData';
import { notify } from '../components/notify';
import Svg, { Path, SvgXml } from "react-native-svg";
import ApprovedIcon from '../assets/image/aprooved_icon.svg';
import PendingIcon from '../assets/image/pending_icon.svg';
import RejectIcon from '../assets/image/reject_icon.svg';


function GroomingPictures(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 [processing, setProcessing] = useState(true);
  const [images, setImages] = useState([]);
  //camera
  const [showCamera, setShowCamera] = useState(false);
  const [clickImageType, setClickImageType] = useState('0');
  const [showImageSaveOp, setShowImageSaveOp] = useState(true);
  const [reCapImgModalObj, setReCapImgModalObj] = useState({});
  const [loaderTitle, setLoaderTitle] = useState();
  const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [rerenderdata2, setrerenderdata2] = useState(0);
  const [showModalAlert, setShowModalAlert] = useState(false);
  const [_hasImages, SethasImages] = useState(false);
  const [isCameraOpen, setIsCameraOpen] = useState(true);

  const [showModal, setShowModal] = useState(false);
  const [SelectedImg, setSelectedImg] = useState('');
  const navigation = useNavigation();
  const d1 = new Date();
  const d2 = moment(d1).format('MM/DD/YYYY');
  const [activeSessions, setActiveSessions] = useState([]);
  ///store related state
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [isBeatPlan, setIsBeatPlan] = useState(false);
  const [isNonMerchan, setIsNonMerchan] = useState(false);
  const [isNonProg, setIsNonProg] = useState(false);
  const [isStoreSearch, setIsStoreSearch] = useState(false);
  const [storeData, setStoreData] = useState({});

  useFocusEffect(useCallback(
    () => {
      getData();
    }, []));

  useEffect(() => {
    let params = props.route.params ? props.route.params : {};
    let storeData1 = params.storeData || {};
    console.log("storeData1", storeData1)
    let isAdhoc = params.isAdhoc || false;
    let isBeat = params.isBeat != null ? params.isBeat : false;
    let isNonMerchan1 = params.isNonMerchans != null ? params.isNonMerchans : false;
    let isNonProgam = params.isNonProgs != null ? params.isNonProgs : false;
    let isStoreSearch = params.isStoreSearch != null ? params.isStoreSearch : false;
    setIsAdhocScreen(isAdhoc);
    setIsBeatPlan(isBeat);
    setIsNonMerchan(isNonMerchan1);
    setIsNonProg(isNonProgam)
    setIsStoreSearch(isStoreSearch)
    setStoreData(storeData1);
  })

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

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

  function onBeforeRemove(e) {
    console.log("logsss", showCamera, hasUnsavedChanges)
    if (showCamera == true) {
      e.preventDefault();
      setShowCamera(false);
    }
    else {
      if (hasUnsavedChanges == true) {
        e.preventDefault(); // Prevent default behavior of leaving the screen
        onRemoveScreen(e);
      }
      else {
        return;
      }
    }
  }

  function onRemoveScreen(e) {
    BgUnsavedChanges(false)
    props.navigation.dispatch(e.data.action);
  }

  async function getData() {
    try {
      setProcessing(true);
      let imagePath = `${ImageFolderPath + 'GROOMINGIMG'}`;
      const files = await RNFS.readDir(imagePath);
      const uris = files.filter(file => file.isFile()).map(file => `file://${file.path}`);
      console.log("imagePath", uris)
      if (uris && uris.length > 0) {
        const result = uris?.map(filePath => {
          const filename = filePath.split('/').pop();
          return {
            filePath,
            filename
          };
        });

        await uploadContractFormFiles12(result);
      }
      await DownloadGroomingData();
      db.transaction((txn) => {
        const menuQuery = `SELECT * FROM Master_GroomingImages `;
        // First: Fetch Menu
        txn.executeSql(menuQuery, [], (txn2, txnres) => {
          const len = txnres.rows.length;
          const groomingArr = [];
          for (let i = 0; i < len; i++) {
            let data = txnres.rows.item(i);
            console.log("data--------", data)
            if (data.GroomingImages) {
              data['GroomingImages'] = JSON.parse(data?.GroomingImages || [])
            }
            groomingArr.push(data);
          }
          const now = new Date();
          const currentTime = now.toTimeString().slice(0, 8);
          const isTimeBetween = (current, start, end) =>
            current >= start && current <= end;
          const filtered = groomingArr.filter(item => {
            const hasImages = item?.GroomingImages && item?.GroomingImages?.length > 0;
            const inTime = isTimeBetween(currentTime, item.StartTime, item.EndTime);
            return inTime || hasImages; // ✅ include if time matches OR images exist
          });

          const noImages = filtered?.some(item =>
            !Array.isArray(item?.GroomingImages) || item.GroomingImages.length === 0
          );

          if (!noImages) SethasImages(true)
          setActiveSessions(filtered);
          setProcessing(false)
        }, (txn2, err2) => {
          console.error("Menu fetch error:", err2);
          setActiveSessions([]);
          setProcessing(false);
        });
      });
    } catch (err) {
      console.error("getData error:", err);
      setProcessing(false);
    }
  }

  function onSaveCancel() {
    setShowModalAlert(false);
  }
  async function OpenImgModal(image, index) {
    setSelectedImg(image?.filePath)
    setShowModal(true);
    if ((image != '' && image != null)) {
      setShowImageSaveOp(false);
    } else {
      setShowImageSaveOp(true);
    }
    setReCapImgModalObj({ image, index })
  }
  function cancelImage() {
    setSelectedImg('');
    setReCapImgModalObj({})
    setShowModal(false);
    setIsCameraOpen(true)
  }

  function BgUnsavedChanges(val) {
    hasUnsavedChangesRef.current = val
    setHasUnsavedChanges(val);
  }

  async function getImage(imgdata) {
    setIsCameraOpen(true)
    if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
      notify(ST.Cameraunavailable);
    }
    else if (typeof imgdata == 'object' && imgdata.uri != null) {
      const img = imgdata;
      const imgurl = img.uri, imgWidth = img.width, imgHeight = img.ExtendedHeight;
      let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
      let picture_clickedd = isImgFromGallery == true ? img.datetime : new Date();
      ////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')
      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 || '') + '_GroomingImg-' + calculate_tym_date_for_filename + '.jpg';

      const mark_text1 = calculate_tym_date_over_img;
      const mark_text2 = 'User Id:' + props.UserId + ' | Image Type: ' + props.GroomingObj?.GroomingTitle + ' | Date:' + calculate_tym_date_over_img;
      let imagePath = `${ImageFolderPath + 'GROOMINGIMG'}/${filename}`;
      RNFS.copyFile(imgurl, imagePath)
        .then(async (resn) => {
          console.log("filename=>", imagePath,)
          // render data with clicked image
          let uri = 'file://' + imagePath;
          // Create a new image object
          const newImage = {
            GroomingId: clickImageType,
            filename: filename,
            filePath: uri,
            UserId: props.UserId,
            VisitDate: props.VisitDate
          };

          const retakeModel = reCapImgModalObj; // coming like { image: ..., index: ... }
          if (retakeModel && retakeModel.image) {
            const { GroomingId: retakeId } = retakeModel.image;
            setImages(prevImages => {
              let updated = [...prevImages];
              if (retakeModel?.index !== undefined && updated[retakeModel?.index]) {
                // ✅ Update single index if provided
                updated[retakeModel?.index] = {
                  ...updated[retakeModel?.index],
                  filePath: uri,
                  filename: filename,
                };
              } else {
                // ✅ Update all items with matching GroomingId
                updated = prevImages.map((img, idx) => {
                  // update only if both GroomingId and index match
                  if (img.GroomingId === retakeId && idx === retakeModel?.index) {
                    return {
                      ...img,
                      filePath: uri,
                      filename: filename,
                    };
                  }
                  return img; // leave others unchanged
                });
              }

              return updated;
            });

            setReCapImgModalObj({});
          }
          else {
            // NORMAL MODE ✅ APPEND new image
            setImages(prevImages => {
              const updated = [...prevImages, newImage];
              return updated;
            });
          }
          setSelectedImg(uri)
          BgUnsavedChanges(true)
          setrerenderdata2(prev => !prev);
          // 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);
        })
        .catch(err => {
          console.log('ERROR: image file write failed!!!');
          console.log(err.message, err.code);
        });
    }
  }

  function _OpenCaptureImage_Modal(img) {
    const isImageCap = (img != '' || img != null) ? true : false;
    return (
      <CustomModal
        style={customStyle.PromoImgModal}
        title={props.GroomingObj?.GroomingTitle || 'Grooming Picture'}
        message={""}
        titleStyle={customStyle.PromoImgModal_title}
        messageStyle={customStyle.PromoImgModal_subtitle}
        showModal={showModal}
      >
        {
          isImageCap &&
          <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('1') }}>
              <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
            </TouchableOpacity>

            {!showImageSaveOp &&
              <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { cancelImage() }}>
                <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
              </TouchableOpacity>
            }
          </View>
        }
      </CustomModal>
    )
  }

  async function openCamera(id) {
    console.log('openCamera', id);
    setHasUnsavedChanges(false)
    setClickImageType(id);
    setShowCamera(true);
    setShowModal(false)
    setIsCameraOpen(false)
  }

  async function upload_Data() {
    setShowModalAlert(false);
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    setProcessing(true);
    setLoaderTitle('Uploading Data...');
    const groupedData = images.reduce((acc, img) => {
      // Check if GroomingId already exists
      let existing = acc.find(item => item.GroomingId === img.GroomingId);
      const imgData = {
        filename: img.filename,
      };
      if (existing) {
        // ✅ Add image to existing GroomingId
        existing.images.push(imgData);
      } else {
        // ✅ Create new entry
        acc.push({
          GroomingId: img.GroomingId,
          VisitDate: img.VisitDate,
          UserId: img.UserId,
          images: [imgData],
        });
      }
      return acc;
    }, []);

    //console.log("Grouped JSON:", JSON.stringify(groupedData));
    let postData = {
      MID: 0,
      Keys: "GroomingPictures",
      JsonData: JSON.stringify(groupedData),
      UserId: props.UserId,
    };
    const url = props.baseurl + 'UploadJsonDirect';
    console.log(JSON.stringify(postData), 'url and postDaata...');
    console.log('upload_data----', images);
    await uploadContractFormFiles12(images);
    await UploadData2(url, postData)
      .then(async res => {
        console.log('res: 12', res, url);
        if (res?.UploadJsonDirectResult == 'Success') {
          const result = await DownloadGroomingData();
          notify('Data Upload Successfully.');
          // Insert into SQLite
          setProcessing(false);
          // Navigate back after upload
          const isEmpty = !storeData || Object.keys(storeData).length === 0;
          navigation.goBack();
        } else {
          notify(res?.UploadJsonDirectResult);
          setProcessing(false);
        }
      })
      .catch(err => {
        console.log(err);
        setProcessing(false);
      });
  }


  async function DownloadGroomingData() {
    try {
      const postdata = {
        Downloadtype: "Master_GroomingImages",
        Username: props.UserId,
        Param1: "",
        Param2: Platform.OS === "ios" ? "iOS" : "Android",
      };
      const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log("Download URL:", url, postdata);
      const res = await getDownloadJson1(url, postdata);
      if (!res || typeof res !== "object") {
        notify("Downloading issues: Invalid response");
        return false;
      }
      const data_arr = res["Master_GroomingImages"] || [];
      if (!data_arr.length) {
        console.warn("⚠️ No Master_GroomingImages found");
        return false;
      }
      const insertResult = await insertJsonDataToTable(db, "Master_GroomingImages", data_arr);
      console.log("DB insert result:", insertResult);
      return insertResult;
    } catch (err) {
      console.error("DownloadGroomingData error:", err);
      return false; // or throw err if you want the caller to catch
    }
  }

  async function insertJsonDataToTable(db, tableName, jsonData) {
    console.log("jsonData----------", jsonData);
    if (!Array.isArray(jsonData) || jsonData.length === 0) return true;
    const columns = Array.from(new Set(jsonData.flatMap(row => Object.keys(row))));
    const normalizedData = jsonData.map(row =>
      columns.reduce((acc, col) => {
        acc[col] = row[col] ?? null;
        return acc;
      }, {})
    );

    const valuesArray = normalizedData.map(row =>
      "(" + columns.map(col => {
        let val = row[col];
        if (val === null || val === undefined) return "NULL";
        if (typeof val === "number") return val;
        if (typeof val === "boolean") return val ? 1 : 0;
        // If val is an object or array, stringify it
        if (typeof val === "object") val = JSON.stringify(val);
        // Escape single quotes in strings
        return `'${val.toString().replace(/'/g, "''")}'`;
      }).join(",") + ")"
    );
    const sql = `INSERT INTO ${tableName} (${columns.join(",")}) VALUES ${valuesArray.join(",")};`;
    return new Promise((resolve, reject) => {
      db.transaction(txn => {
        txn.executeSql(`DELETE FROM ${tableName}`, [], () => {
          txn.executeSql(sql, [], () => {
            console.log(`✅ Inserted data into table: ${tableName}`);
            resolve(true);
          }, (tx, error) => {
            console.error(`❌ Insert failed in table: ${tableName}`, error);
            reject(error);
          });
        }, (tx, error) => {
          console.error(`❌ Delete failed in table: ${tableName}`, error);
          reject(error);
        });
      });
    });
  }

  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.filePath;
        console.log('actualfilepath---', actualfilepath, file);
        let isExists = await RNFS.exists(actualfilepath).then(res => {
          return res;
        });
        console.log('isExists file', isExists, file);
        let isImageUploaded = false;
        if (isExists) {
          let postData = new FormData();
          postData.append('file', {
            uri: actualfilepath,
            type: 'image/jpeg',
            name: file.filename,
          });
          postData.append('Foldername', 'GroomingImages');
          postData.append('Path', d2);
          console.log("postData", postData)
          isImageUploaded = await UploadImagesWithoutWait(postData, url);
          if (isImageUploaded == true) {
            console.log(
              'isExists file uploaded',
              isExists,
              uploadCount,
              index,
              allfiles.length - 1,
            );
            await RNFS.unlink(actualfilepath);
            uploadCount++;
            if (uploadCount == allfiles.length) {
              isAllUploaded = true;
            }
          } else {
            console.log('file not uploaded:', isExists, actualfilepath);
          }
        } else {
          //file does not exists
          uploadCount++;
          if (uploadCount == allfiles.length) {
            isAllUploaded = true;
          }
        }

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

  const handleUpload = () => {
    let rse = validate(); // Run validation
    if (!rse) return;
    console.log('Setting showModal to true'); // Debugging
    setShowModalAlert(true); // Show the confirmation modal
  };

  const validate = () => {
    let isValid = true;
    for (let i = 0; i < activeSessions?.length; i++) {
      const item = activeSessions[i];
      const currentImages = item?.GroomingImages ? item?.GroomingImages?.length : 0;
      if (currentImages == 0 && images?.length == 0 && item?.MinImage !== 0) {
        notify(item?.Message)
        isValid = false;
        break;
      } if (currentImages == 0 && images?.length > 0 && images?.length < item?.MinImage) {
        notify(item?.Message + " atleast " + item?.MinImage)
        isValid = false;
        break;
      }
    }

    return isValid;
  };

  const renderSession = ({ item }) => {
    const now = new Date();
    const currentTime = now.toTimeString().slice(0, 8);
    const isTimeBetween = (current, start, end) => current >= start && current <= end;
    const currentImages = item?.GroomingImages ? item?.GroomingImages?.length : 0;
    const isActive = isTimeBetween(currentTime, item.StartTime, item.EndTime) && currentImages == 0;
    // Calculate current uploaded images
    const remainingImages = item.MaxImage - currentImages;
    const currentImageCount = images.filter(
      img => img.GroomingId === item.GroomingId
    ).length;

    return (
      <View style={[styles.card, isActive && styles.activeCard]}>
        {/* 🔹 Static SVG icon in top-right corner */}
        {!isActive && (
          <View style={styles.topRightIcon}>
            {item?.AuditStatus === 'Aprooved' ? (<ApprovedIcon width={20} height={20} />) : item?.AuditStatus === 'Reject' ? (<RejectIcon width={20} height={20} />) : (<PendingIcon width={20} height={20} />)}
          </View>
        )}
        <View style={styles.titleContainer}>
          <Image
            source={{ uri: item.Icon }}
            style={styles.icon}
          />
          <Text style={styles.title}>
            {item.GroomingName}{" "}
            {isActive && <Text style={styles.activeTag}>● Active</Text>}
          </Text>
        </View>

        <Text style={styles.message}>{item.Message}</Text>
        <Text style={styles.time}>
          🕒 {item.StartTime} - {item.EndTime}
        </Text>
        {/* Show progress for Min/Max Images */}
        {isActive && (
          <View style={styles.slotsContainer}>
            <Text style={styles.slotsText}>
              {`Images: ${images.filter(img => img.GroomingId === item.GroomingId).length
                }/${item.MaxImage}`}
            </Text>

          </View>
        )}

        {isActive && (
          <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
            <TouchableOpacity
              key={item?.GroomingId}
              style={[
                styles.addButton,
                { marginRight: 10 },
                currentImageCount >= item.MaxImage && styles.disabledButton, // change color
              ]}
              onPress={() => currentImageCount < item.MaxImage && openCamera(item?.GroomingId)}
              disabled={currentImageCount >= item.MaxImage} // disables touch
            >
              <Icon
                name="add"
                size={28}
                color={currentImageCount >= item.MaxImage ? '#888' : '#fff'} // optional icon color change
              />
            </TouchableOpacity>

            {images?.length > 0 && (
              <ScrollView horizontal style={{}}>
                {images
                  ?.filter(img => img.GroomingId === item.GroomingId)
                  .map((img, index) => (
                    <View key={index} style={{ position: 'relative', marginRight: 10 }}>
                      <TouchableOpacity onPress={() => OpenImgModal(img, index)}>
                        <Image
                          source={{ uri: img.filePath }}
                          style={styles.previewImage}
                        />
                      </TouchableOpacity>

                      {/* Delete Icon */}
                      <TouchableOpacity
                        style={{
                          position: 'absolute',
                          top: 0,
                          right: 5,
                          backgroundColor: 'black',
                          borderColor: 'black',
                          borderWidth: 2,
                          borderRadius: 12,
                          padding: 3,
                          zIndex: 1,
                          elevation: 1,
                        }}
                        onPress={() => {
                          Alert.alert(
                            "Delete Image",
                            "Are you sure you want to delete this image?",
                            [
                              { text: "Cancel", style: "cancel" },
                              {
                                text: "Delete",
                                style: "destructive",
                                onPress: () => {
                                  // Remove the image from images array
                                  const newImages = images.filter(
                                    (i) => i.filePath !== img.filePath
                                  );
                                  setImages(newImages); // assuming images is in state
                                }
                              }
                            ]
                          );
                        }}
                      >
                        <Icon name="trash-outline" size={20} color="white" />
                      </TouchableOpacity>
                    </View>
                  ))}
              </ScrollView>
            )}
          </View>
        )}
        {/* Show existing images */}
        {item?.GroomingImages && item?.GroomingImages?.length > 0 && (
          <>
            <Text style={styles.slotsText}>
              {`Images: ${item?.GroomingImages?.length
                }/${item.MaxImage}`}
            </Text>

            <ScrollView horizontal showsHorizontalScrollIndicator={false}>
              {item?.GroomingImages.map((img, index) => (
                <View key={index} style={{ alignItems: 'center', marginLeft: 8, marginRight: 8 }}>
                  {console.log("item-------", img)}
                  <Image
                    source={{ uri: img?.ImageUrl }}
                    style={[styles.previewImage, { marginRight: 0, }]}
                  />
                  <Text style={{ fontSize: 8, color: '#000', textAlign: 'center', marginTop: 4, fontWeight: 500 }}>
                    {`${moment(img?.CaptureDate, "DD/MM/YYYY").format("DD MMM, YYYY")}-${img?.CaptureTime}`}

                  </Text>
                </View>

              ))}
            </ScrollView>
          </>

        )}
      </View>
    );
  };


  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS == 'ios' ? true : false}>
      {processing && <CustomLoader title={ST.Loading + '...'} />}
      <CustomHeader {...props} showaddstore={true} title={props.GroomingObj?.GroomingTitle || 'Grooming Picture'} />
      {ConfirmSaveAlert(
        props,
        showModalAlert,
        onSaveCancel,
        upload_Data,
        'Do you really want to save data ?',
      )}

      <CustomCamera cameraType={'back'} BottomText={`User Id:' + "testmer" + ' | Image Type: ${props.GroomingObj?.GroomingTitle}`} enableCameraFlip={false} onImageCaptured={(imgData) => { setShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { setShowCamera(false); }} />
      {_OpenCaptureImage_Modal()}
      <LinearGradient
        colors={[PageTheme.$gradient1, PageTheme.$primary_color]}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 0 }}
        style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper]}>
          {activeSessions.length > 0 ? (
            <FlatList
              data={activeSessions}
              keyExtractor={(item) => item.GroomingId.toString()}
              renderItem={renderSession}
              contentContainerStyle={styles.list}
              style={{ marginLeft: 7, marginRight: 7, marginTop: 7, marginBottom: 40 }}
            />
          ) : !processing && (
            <Text style={styles.noData}>{`No active ${props.GroomingObj?.GroomingTitle || 'grooming session'} right now.`}</Text>
          )}
        </View>
      </LinearGradient>
      <View
        pointerEvents="box-none"
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          zIndex: 9999,
          elevation: 9999,
        }}
      >
        {!_hasImages && activeSessions.length > 0  && isCameraOpen && (
          <View style={customStyle.opening_Stock_btnWrap}>
            <GradientButton {...props} title={ST.Save} onPress={handleUpload} />
          </View>
        )}
      </View>
    </Container>
  );
}

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F9FAFB",
    padding: 16,
  },
  list: {
    paddingBottom: 30,
  },
  card: {
    backgroundColor: "white",
    borderRadius: 16,
    padding: 16,
    marginBottom: 12,
    shadowColor: "#000",
    borderColor: "#d3d3d3",
    borderWidth: 1,
    shadowOpacity: 0.1,
    shadowRadius: 6,
    shadowOffset: { width: 0, height: 3 },
    elevation: 3,
  },
  title: {
    fontSize: 18,
    fontWeight: "700",
    color: "#333",
  },
  message: {
    marginTop: 4,
    fontSize: 14,
    color: "#666",
  },
  time: {
    marginTop: 8,
    fontSize: 13,
    color: "#888",
  },
  image: {
    width: 100,
    height: 100,
    borderRadius: 10,
    marginTop: 10,
    marginRight: 8,
  },
  noData: {
    textAlign: "center",
    alignContent: "center",
    alignItems: "center",
    color: "#999",
    marginTop: 250,
    fontWeight: "500",
    fontSize: 20,
  }, activeCard: {
    borderColor: "#4CAF50",
    borderWidth: 1.5,
    backgroundColor: "#F0FFF9",
  },

  activeTag: {
    color: "#4CAF50",
    fontSize: 12,
  },

  imageProgressContainer: {
    marginTop: 8,
  },

  imageProgressText: {
    fontSize: 13,
    color: "#555",
    marginBottom: 4,
  },

  iconRow: {
    flexDirection: "row",
    alignItems: "center",
  },

  imageSlot: {
    width: 20,
    height: 20,
    borderRadius: 4,
    marginRight: 6,
  },
  slotsContainer: {
    marginBottom: 10,
    marginTop: 6,
    marginStart: 6
  },
  slotsText: {
    fontSize: 16,
    marginBottom: 5,
    marginLeft: 5,
    marginTop: 2,
    fontWeight: "500",
  },
  iconRow: {
    flexDirection: "row",
  },
  slot: {
    width: 50,
    height: 50,
    marginRight: 10,
    borderRadius: 8,
    justifyContent: "center",
    alignItems: "center",
  },
  addButton: {
    backgroundColor: '#007AFF',
    width: 50,
    height: 50,
    borderRadius: 30,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 3 },
    shadowOpacity: 0.3,
    shadowRadius: 2,
    elevation: 1,

  },
  disabledButton: {
    backgroundColor: '#ccc', // grey when disabled
  },
  previewImage: {
    width: 84,
    height: 84,
    borderRadius: 8,
    marginRight: 10,
  },
  titleContainer: {
    flexDirection: 'row',     // icon + text in a row
    alignItems: 'flex-start',     // vertically center them
    justifyContent: 'flex-start', // center horizontally
  },
  icon: {
    marginRight: 6,
    height: 25,
    width: 25,
  },
  topRightIcon: {
    position: 'absolute',
    top: 15,
    right: 8,
    zIndex: 10,
    elevation: 10,
  },

});
