import { useState, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { GalleryItem } from "@/models/GalleryItem";

interface UseGalleryOptions {
  galleryId?: string;
  approved?: boolean;
  tags?: string[];
  limit?: number;
  offset?: number;
  searchQuery?: string;
}

export function useGallery(options: UseGalleryOptions = {}) {
  const [galleryItems, setGalleryItems] = useState<GalleryItem[]>([]);
  const [totalItems, setTotalItems] = useState<number>(0);

  // Build query parameters
  const queryParams = new URLSearchParams();
  // Safely handle null or undefined values
  if (options.galleryId) queryParams.append("galleryId", options.galleryId);
  if (options.approved !== undefined)
    queryParams.append("approved", options.approved.toString());
  if (options.tags && options.tags.length > 0) {
    options.tags.forEach((tag) => queryParams.append("tag", tag));
  }
  if (options.limit !== undefined)
    queryParams.append("limit", options.limit.toString());
  if (options.offset !== undefined)
    queryParams.append("offset", options.offset.toString());
  if (options.searchQuery) queryParams.append("search", options.searchQuery);

  const queryString = queryParams.toString();
  const endpoint = queryString ? `/media-items?${queryString}` : "/media-items";

  const { data, isLoading, isError, error, refetch } = useQuery<any>({
    queryKey: [endpoint],
    staleTime: 1000 * 60 * 5, // 5 minutes
  });

  useEffect(() => {
    if (data) {
      // Check if data is an array (direct response) or an object with galleryItems property
      if (Array.isArray(data)) {
        setGalleryItems(data);
        setTotalItems(data.length);
      } else if (typeof data === "object" && data.galleryItems) {
        setGalleryItems(data.galleryItems);
        setTotalItems(data.total || data.galleryItems.length || 0);
      } else {
        // Last fallback - try to handle unexpected response structures
        console.warn("Unexpected media data structure:", data);
        try {
          const possibleItems = Object.values(data).find((val) =>
            Array.isArray(val)
          );
          if (possibleItems) {
            setGalleryItems(possibleItems as GalleryItem[]);
            setTotalItems(possibleItems.length);
          } else {
            setGalleryItems([]);
            setTotalItems(0);
          }
        } catch (e) {
          console.error("Error parsing media data:", e);
          setGalleryItems([]);
          setTotalItems(0);
        }
      }
    } else {
      setGalleryItems([]);
      setTotalItems(0);
    }
  }, [data]);

  // Method to manually update media items (e.g., after operations)
  const updateGalleryItem = async (updatedItem: GalleryItem) => {
    // Update the media item in the local state if it exists
    setGalleryItems((prev) =>
      prev.map((item) => (item.id === updatedItem.id ? updatedItem : item))
    );

    // Refetch to ensure we have the latest data
    await refetch();
  };

  // Method to add a new media item to the cache
  const addGalleryItem = async (newItem: GalleryItem) => {
    setGalleryItems((prev) => [newItem, ...prev]);
    setTotalItems((prev) => prev + 1);

    // Refetch to ensure we have the latest data
    await refetch();
  };

  // Method to remove a media item from the cache
  const removeGalleryItem = async (itemId: string) => {
    setGalleryItems((prev) => prev.filter((item) => item.id !== itemId));
    setTotalItems((prev) => prev - 1);

    // Refetch to ensure we have the latest data
    await refetch();
  };

  return {
    galleryItems,
    totalItems,
    isLoading,
    isError,
    error,
    refetch,
    updateGalleryItem,
    addGalleryItem,
    removeGalleryItem,
  };
}
