import React, { useRef, useState, useCallback, useEffect } from "react";
import moment from "moment";
import Avatar from "../../components/common/Avatar";
import { useGalleryContext } from "../../pages/Gallary/ImageGallaryPage";
import useImageGallery from "../../hooks/useImageGallery";
import { useSelectedProject } from "../../slices/apiDataManager";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import Pagination from "../common/Pagination";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { SpinnerLoader } from "../common/Loader";
import GalleryFilterChips from "./GalleryFilterChips";
const ImageGalleryListView = ({ filter, filterData, removeFilterChip, clearFilter }) => {
  const [hoveredImage, setHoveredImage] = useState(null);
  const selectedProject = useSelectedProject();
  const [currentPage, setCurrentPage] = useState(1);
  const { setOpenGallery } = useGalleryContext();

  const { data, isLoading, isError, error } = useImageGallery(
    selectedProject,
    currentPage,
    10,
    filter
  );

  const paginate = (page) => {
    if (page >= 1 && page <= (data?.totalPages ?? 1)) {
      setCurrentPage(page);
    }
  };

  if (!data?.data?.length && !isLoading) {
    return (
      <div
        className="d-flex justify-content-center align-items-center text-muted"
        style={{ minHeight: "50vh" }}
      >
        <span style={{ fontSize: "0.9rem" }}>
          {selectedProject
            ? "No images match the selected filters."
            : "Please Select Project!"}
        </span>
      </div>
    );
  }


  if (isLoading) {
    return (
      <div className="page-min-h d-flex justify-content-center align-items-center">
        <SpinnerLoader />
      </div>
    );
  } 

 


  return (
    <div className="main-content">
      <div className="col-12 mb-2 mt-2 px-4">
      <GalleryFilterChips
        filter={filter}
        filterData={filterData}
        removeFilterChip={removeFilterChip}
        clearFilter={clearFilter}
      />
    </div>
      <div className="activity-section">
        {data?.data?.map((batch) => {
          if (!batch.documents?.length) return null;

          const doc = batch.documents[0];
          const userName = `${doc.uploadedBy?.firstName || ""} ${doc.uploadedBy?.lastName || ""
            }`.trim();
          const date = formatUTCToLocalTime(doc.uploadedAt);
          //   const hasArrows = batch.documents.length > scrollThreshold;

          return (
            <div key={batch.batchId} className="grouped-section">
              <div className="group-heading">
                <div className="d-flex align-items-center mb-1">
                  <Avatar
                    size="xs"
                    firstName={doc.uploadedBy?.firstName}
                    lastName={doc.uploadedBy?.lastName}
                    className="me-2"
                  />
                  <div className="d-flex flex-column align-items-start">
                    <strong className="user-name-text">{userName}</strong>
                    <span className="text-muted small">{date}</span>
                  </div>
                </div>

                <div className="location-line text-secondary">
                  <div className="d-flex align-items-center flex-wrap gap-1 text-secondary">
                    <span className="d-flex align-items-center">
                      <span>{batch.buildingName}</span>
                      <i className="bx bx-chevron-right " />
                    </span>
                    <span className="d-flex align-items-center">
                      <span>{batch.floorName}</span>
                      <i className="bx bx-chevron-right m" />
                    </span>
                    <span className="d-flex align-items-center ">
                      <span>{batch.workAreaName || "Unknown"}</span>
                      <i className="bx bx-chevron-right " />
                      <span>{batch.activityName}</span>
                    </span>
                  </div>
                  {batch.workCategoryName && (
                    <span className="badge bg-label-primary ms-2">
                      {batch.workCategoryName}
                    </span>
                  )}
                </div>
              </div>

              <div className="image-group-wrapper">
                {/* {hasArrows && (
                  <button className="scroll-arrow left-arrow" onClick={() => scrollLeft(batch.batchId)}>
                    ‹
                  </button>
                )} */}
                <div
                  className="image-group-horizontal"
                //   ref={(el) => (imageGroupRefs.current[batch.batchId] = el)}
                >
                  {batch.documents.map((d, i) => {
                    const hoverDate = moment().format("DD MMMM, YYYY");
                    const hoverTime = moment(d.uploadedAt).format("hh:mm A");

                    return (
                      <div
                        key={d.id}
                        className="image-card"
                        onMouseEnter={() => setHoveredImage(d)}
                        onMouseLeave={() => setHoveredImage(null)}
                        onClick={() =>
                          setOpenGallery({
                            isOpen: true,
                            data: { data: batch, index: i },
                          })
                        }
                      >
                        <div className="image-wrapper">
                          <img src={d.url} alt={`Image ${i + 1}`} />
                        </div>
                        {hoveredImage === d && (
                          <div className="image-hover-description">
                            <p>
                              <strong>Date:</strong> {hoverDate}
                            </p>
                            <p>
                              <strong>Time:</strong> {hoverTime}
                            </p>
                            <p>
                              <strong>Activity:</strong> {batch.activityName}
                            </p>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
                {/* {hasArrows && (
                  <button className="scroll-arrow right-arrow" onClick={() => scrollRight(batch.batchId)}>
                    ‹
                  </button>
                )} */}
              </div>
            </div>
          );
        })}
      </div>

      {data?.data?.length > 0 && (
        <Pagination
          currentPage={currentPage}
          totalPages={data?.totalPages}
          onPageChange={paginate}
        />
      )}
    </div>
  );
};

export default ImageGalleryListView;
