"use client";
import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import GalleryItem from "./GalleryItem";
import { Skeleton } from "@/components/ui/skeleton";
import Link from "next/link";
import { GalleryItem as GalleryItemType } from "@/models/GalleryItem";
import { useEffect, useState } from "react";

const PAGE_SIZE = 3;

const GallerySection = () => {
  const [page, setPage] = useState(1);
  const [items, setItems] = useState<GalleryItemType[]>([]);
  const [hasMore, setHasMore] = useState(true);

  const {
    data: galleryItems,
    isLoading,
    error,
    isFetching,
  } = useQuery<{
    data: GalleryItemType[];
    total: number;
    hasMore: boolean;
  }>({
    queryKey: [`/galleries?page=${page}&pageSize=${PAGE_SIZE}`],
    enabled: hasMore,
  });

  useEffect(() => {
    if (galleryItems?.data?.length) {
      setItems((prev) => {
        const newItems = galleryItems.data.filter(
          (item) => !prev.some((existing) => existing.id === item.id)
        );
        return [...prev, ...newItems];
      });
      setHasMore(galleryItems.hasMore);
    }
  }, [galleryItems]);

  const handleLoadMore = () => {
    if (hasMore) setPage((prev) => prev + 1);
  };

  if (error || isLoading || isFetching) {
    return (
      <div className="py-16 text-center">
        <p className="text-destructive">
          Error loading gallery items. Please try again later.
        </p>
      </div>
    );
  }
  return (
    <section id="gallery" className="py-20 md:py-28 lg:py-36 bg-secondary">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <h2 className="text-3xl font-bold tracking-tight text-primary sm:text-4xl font-heading">
            Museum Gallery
          </h2>
          <p className="mt-3 max-w-2xl mx-auto text-xl text-gray-500">
            Explore our collection of artifacts, exhibits, and historical
            landmarks.
          </p>
        </div>

        {isLoading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {Array(PAGE_SIZE)
              .fill(0)
              .map((_, i) => (
                <div
                  key={i}
                  className="bg-white rounded-lg overflow-hidden shadow-lg"
                >
                  <Skeleton className="w-full h-64" />
                  <div className="p-6">
                    <Skeleton className="h-6 w-3/4 mb-2" />
                    <Skeleton className="h-4 w-full mb-4" />
                    <Skeleton className="h-4 w-1/4" />
                  </div>
                </div>
              ))}
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {(items || [])?.map((item) => (
              <GalleryItem key={item.id} item={item} />
            ))}
          </div>
        )}

        <div className="mt-12 text-center">
          {hasMore ? (
            <Button
              onClick={handleLoadMore}
              disabled={isFetching}
              className="bg-primary hover:bg-primary-dark text-white text-sm px-6 py-2 rounded-md transition"
            >
              {isFetching ? "Loading..." : "Load More"}
            </Button>
          ) : (
            <Link href="/gallery">
              <Button className="bg-primary hover:bg-primary-dark">
                View Full Gallery
              </Button>
            </Link>
          )}
        </div>
      </div>
    </section>
  );
};

export default GallerySection;
