"use client";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import GalleryItem from "@/components/gallery/GalleryItem";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { GalleryItem as GalleryItemType } from "@/models/GalleryItem";
import Head from "next/head";
import Image from "next/image";
import Link from "next/link";

const PAGE_SIZE = 3;
const categories = [
  { id: "all", name: "All Items" },
  { id: "artifacts", name: "Artifacts" },
  { id: "buildings", name: "Buildings" },
  { id: "landmarks", name: "Landmarks" },
  { id: "documents", name: "Documents" },
  { id: "models", name: "Models" },
  { id: "memorials", name: "Memorials" },
  { id: "exhibits", name: "Exhibits" },
];

const GalleryPage = () => {
  const [page, setPage] = useState(1);
  const [items, setItems] = useState<GalleryItemType[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [activeCategory, setActiveCategory] = useState("all");

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

  // Filter items based on active category
  const filteredItems =
    activeCategory === "all"
      ? items
      : items?.filter((item) => item.category === activeCategory);

  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);
  };

  return (
    <>
      <Head>
        <title>Gallery | Badagry Museum</title>
        <meta
          name="description"
          content="Explore our collection of artifacts, exhibits, and historical landmarks at the Badagry Museum. View images of historical items from Nigeria's slavery history."
        />
        <meta
          name="keywords"
          content="Badagry Museum gallery, slave trade artifacts, historical landmarks, Nigerian cultural heritage, museum exhibits"
        />

        {/* Open Graph / Facebook */}
        <meta property="og:type" content="website" />
        <meta
          property="og:url"
          content="https://badagry.museumcall.com/gallery"
        />
        <meta property="og:title" content="Gallery | Badagry Museum" />
        <meta
          property="og:description"
          content="Explore our collection of artifacts, exhibits, and historical landmarks at the Badagry Museum."
        />
        <meta
          property="og:image"
          content="https://pixabay.com/get/g640f5ea3f705ccc32d084e514478459b6c9d6b34df1622477ad0650f66b9124306c5ef69528d5f7ca61e059ae74aa94a355f1d3e0f9363e46018be7e0540119c_1280.png"
        />

        {/* Twitter */}
        <meta property="twitter:card" content="summary_large_image" />
        <meta
          property="twitter:url"
          content="https://badagrymuseum.org/gallery"
        />
        <meta property="twitter:title" content="Gallery | Badagry Museum" />
        <meta
          property="twitter:description"
          content="Explore our collection of artifacts, exhibits, and historical landmarks at the Badagry Museum."
        />
        <meta
          property="twitter:image"
          content="https://pixabay.com/get/g640f5ea3f705ccc32d084e514478459b6c9d6b34df1622477ad0650f66b9124306c5ef69528d5f7ca61e059ae74aa94a355f1d3e0f9363e46018be7e0540119c_1280.png"
        />
      </Head>

      <section className="relative w-full min-h-screen bg-gray-950 text-white flex flex-col justify-between">
        {/* Background image covering the right half */}
        <div className="absolute -inset-y-20 right-20 w-1/2 overflow-hidden hidden lg:block">
          <img
            src="/images/IMG_0259-min-removebg-preview.png" // Path to your background image (e.g., in public/images)
            alt="Photographer holding a camera"
            className="object-left-top grayscale object-cover h-auto max-w-full"
            style={{ width: "100%" }}
          />
        </div>

        {/* Main content area - Text and Button */}
        <div className="relative overflow-x-hidden z-10 flex flex-col items-center justify-center lg:items-start lg:justify-start pt-20 pb-12 px-8 md:px-16 lg:pl-24 lg:pr-1/2 lg:pt-32 flex-grow">
          {/* Horizon Title */}
          <div className="flex items-center mb-5">
            <div className="w-4 h-4 bg-red-600 mr-4"></div>
            <h1
              className="font-serif text-5xl md:text-6xl lg:text-7xl xl:text-8xl font-bold tracking-tight mb-4 text-center lg:text-left"
              style={{ fontFamily: "Georgia, serif", lineHeight: "1.2" }}
            >
              Museum Gallery
            </h1>
          </div>

          {/* Welcome Text */}
          <p className="max-w-xl text-lg md:text-xl leading-relaxed mb-10 text-center lg:text-left">
            Explore our collection of artifacts, exhibits, and historical
            landmarks that tell the story of Nigeria's past.
          </p>

          {/* Button */}
          <Link
            href="#explore-gallery"
            className="bg-transparent border border-white text-white py-3 px-8 rounded-lg text-lg hover:bg-white hover:text-black transition duration-300"
          >
            Explore Gallery
          </Link>
        </div>

        {/* Image Grid below the main content */}
        <div className="relative z-10 grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4 p-8 md:p-16 lg:pl-24 lg:pr-1/2 pb-16 items-end">
          <div className="aspect-w-5 aspect-h-3 overflow-hidden rounded-lg">
            <Image
              src="/images/1507903190231.193-min.jpeg" // Corresponds to misty mountains in screenshot
              alt="Misty mountains"
              fill
              className="object-cover grayscale"
            />
          </div>

          <div className="aspect-w-4 aspect-h-4 overflow-hidden rounded-lg">
            <Image
              src="/images/IMG_0374-min.jpg" // Corresponds to person on mountain in screenshot
              alt="Person on mountain at sunset"
              fill
              className="object-cover grayscale"
            />
          </div>

          {/* <div className="col-span-2 md:col-span-1 row-span-2 flex flex-col gap-4 self-end"> */}
          <div className="aspect-w-3 aspect-h-2 overflow-hidden rounded-lg">
            <Image
              src="/images/IMG_0495_11zon.jpg" // This image was previously linked to 'Waterfall' in your code
              alt="Waterfall 1"
              fill
              className="object-cover grayscale"
            />
          </div>
          <div className="aspect-w-3 aspect-h-2 overflow-hidden rounded-lg h-full">
            <Image
              src="/images/IMG_0495_11zon.jpg" // Reusing the same waterfall image if you don't have a second distinct tall one
              alt="Waterfall 2"
              fill
              className="object-cover grayscale"
            />
          </div>
          {/* </div> */}

          <div className="aspect-w-4 aspect-h-3 overflow-hidden rounded-lg">
            <Image
              src="/images/1507903190231.193-min.jpeg" // Reusing image for mountain antenna, as visually implied in screenshot
              alt="Mountain antenna"
              fill
              className="object-cover grayscale"
            />
          </div>

          <div className="aspect-w-4 aspect-h-3 overflow-hidden rounded-lg">
            <Image
              src="/images/IMG_0272-min.jpg"
              alt="Snowy mountains and river"
              fill
              className="object-cover grayscale"
            />
          </div>

          <div className="aspect-w-4 aspect-h-3 overflow-hidden rounded-lg">
            <Image
              src="/images/IMG_0526_11zon.jpg"
              alt="Snowy mountains and river"
              fill
              className="object-cover grayscale"
            />
          </div>

          <div className="aspect-w-4 aspect-h-3 overflow-hidden rounded-lg">
            <Image
              src="/images/IMG_0278-min.jpg"
              alt="Snowy mountains and river"
              fill
              className="object-cover grayscale"
            />
          </div>

          <div className="aspect-w-4 aspect-h-3 overflow-hidden rounded-lg">
            <Image
              src="/images/IMG_0517_11zon.jpg"
              alt="Snowy mountains and river"
              fill
              className="object-cover grayscale"
            />
          </div>
          <div className="aspect-w-4 aspect-h-3 overflow-hidden rounded-lg hidden md:block">
            <Image
              src="/images/IMG_0488_11zon.jpg"
              alt="Snowy mountains and river"
              fill
              className="object-cover grayscale"
            />
          </div>
        </div>
      </section>

      <section className="py-16 bg-secondary" id="explore-gallery">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="mb-10">
            <Tabs
              defaultValue="all"
              value={activeCategory}
              onValueChange={setActiveCategory}
            >
              <TabsList className="h-auto flex flex-wrap justify-center mb-6">
                {categories.map((category) => (
                  <TabsTrigger
                    key={category.id}
                    value={category.id}
                    className="py-2 px-4 data-[state=active]:bg-primary data-[state=active]:text-white"
                  >
                    {category.name}
                  </TabsTrigger>
                ))}
              </TabsList>
            </Tabs>
          </div>

          {isLoading ? (
            // Loading state
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {Array(9)
                .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>
          ) : error ? (
            // Error state
            <div className="bg-white p-8 rounded-lg shadow-lg text-center">
              <p className="text-destructive mb-4">
                Error loading gallery items. Please try again later.
              </p>
              <Button
                onClick={() => window.location.reload()}
                className="bg-primary hover:bg-primary-dark"
              >
                Retry
              </Button>
            </div>
          ) : filteredItems.length === 0 ? (
            // No items in selected category
            <div className="bg-white p-8 rounded-lg shadow-lg text-center">
              <p className="text-gray-600">No items found in this category.</p>
              <Button
                onClick={() => setActiveCategory("all")}
                className="mt-4 bg-primary hover:bg-primary-dark"
              >
                View All Gallery Items
              </Button>
            </div>
          ) : (
            // Display gallery items
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredItems.map((item) => (
                <GalleryItem key={item.id} item={item} />
              ))}
            </div>
          )}

          <div className="mt-12 grid grid-cols-1 gap-6 items-center justify-items-center">
            {hasMore && (
              <Button
                onClick={handleLoadMore}
                disabled={isFetching}
                className="bg-primary hover:bg-primary-dark text-white text-sm px-6 py-4 rounded-lg transition"
              >
                {isFetching ? "Loading..." : "Load More"}
              </Button>
            )}
          </div>
        </div>
      </section>
    </>
  );
};

export default GalleryPage;
