import React, {
  useState,
  useEffect,
  useRef,
  useContext,
  createContext,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import eventBus from "../../services/eventBus";
import Breadcrumb from "../../components/common/Breadcrumb";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import useImageGallery from "../../hooks/useImageGallery";
import {
  useProjectAssignedServices,
  useProjectName,
} from "../../hooks/useProjects";
import { setProjectId } from "../../slices/localVariablesSlice";
import ImageGalleryListView from "../../components/gallary/ImageGalleryListView";
import "../../components/gallary/ImageGallery.css";
import { useSelectedProject } from "../../slices/apiDataManager";
import GlobalModel from "../../components/common/GlobalModel";
import ViewGallery from "../../components/gallary/ViewGallery";
import { useFab } from "../../Context/FabContext";
import GalleryFilterPanel from "../../components/gallary/GalleryFilterPanel";
import { defaultGalleryFilterValue } from "../../components/gallary/GallerySchema";

const GalleryContext = createContext();

export const useGalleryContext = () => {
  let context = useContext(GalleryContext);

  if (!context) {
    throw new Error("Error");
  }
  return context;
};

const ImageGalleryPage = () => {
  const [filter, setFilter] = useState(defaultGalleryFilterValue);
  const selectedProjectId = useSelectedProject();
  const { projectNames } = useProjectName();
  const [filterData, setFilterdata] = useState(null);
  const updatedRef = useRef();
  const [openGallery, setOpenGallery] = useState({ isOpen: false, data: null });
  const { data: assignedServices = [], isLoading } =
    useProjectAssignedServices(selectedProjectId);

  const [selectedService, setSelectedService] = useState("");

  const handleServiceChange = (e) => {
    setSelectedService(e.target.value);
  };

  const contextMessager = {
    setOpenGallery,
  };

  const clearFilter = () => setFilter(defaultGalleryFilterValue);
  const { setOffcanvasContent, setShowTrigger } = useFab();

  useEffect(() => {
    setShowTrigger(true);
    setOffcanvasContent(
      "Gallery Filter",
      <GalleryFilterPanel
        onApply={setFilter}
        ref={updatedRef}
        clearFilter={clearFilter}
        setFilterdata={setFilterdata} />
    );

    return () => {
      setOffcanvasContent("", null);
      setShowTrigger(false);
    };
  }, []);

  const handleRemoveChip = (key, id) => {
    setFilter((prev) => {
      const updated = { ...prev };

      if (Array.isArray(updated[key])) {
        updated[key] = updated[key].filter((v) => v !== id);
        setTimeout(() => updatedRef.current?.resetFieldValue(key, updated[key]), 0);
      } else {
        updated[key] = null;
        setTimeout(() => updatedRef.current?.resetFieldValue(key, null), 0);
      }

      return updated;
    });
  };

  return (
    <GalleryContext.Provider value={contextMessager}>
      <div className="container-fluid">
        <Breadcrumb
          data={[{ label: "Home", link: "/dashboard" }, { label: "Gallery" }]}
        />

        <div className="card page-min-h p-2">
          <ImageGalleryListView
            filter={filter}
            filterData={filterData}
            removeFilterChip={handleRemoveChip}
            clearFilter={clearFilter} />
        </div>

        {openGallery?.isOpen && (
          <GlobalModel
            isOpen={openGallery?.isOpen}
            closeModal={() => setOpenGallery({ isOpen: false, data: null })}
          >
            <ViewGallery
              batch={openGallery?.data?.data}
              index={openGallery?.data?.index}
            />
          </GlobalModel>
        )}
      </div>
    </GalleryContext.Provider>
  );
};

export default ImageGalleryPage;
