"use client"

import { useState, useEffect } from "react"
import { createBrowserClient } from "@/lib/supabase/client"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ImageIcon, Loader2 } from "lucide-react"
import Image from "next/image"

interface GalleryImage {
  id: string
  title: string
  description: string | null
  image_url: string
  category: string
}

export function GallerySection() {
  const [images, setImages] = useState<GalleryImage[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [selectedCategory, setSelectedCategory] = useState("all")

  useEffect(() => {
    fetchImages()
  }, [])

  const fetchImages = async () => {
    try {
      const supabase = createBrowserClient()
      const { data, error } = await supabase
        .from("gallery_images")
        .select("*")
        .eq("is_active", true)
        .order("display_order", { ascending: true })

      if (error) throw error
      setImages(data || [])
    } catch (error) {
      console.error("[v0] Error fetching gallery:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const categories = [
    { value: "all", label: "Todas" },
    { value: "campus", label: "Campus" },
    { value: "events", label: "Eventos" },
    { value: "students", label: "Alunos" },
    { value: "infrastructure", label: "Infraestrutura" },
  ]

  const filteredImages = selectedCategory === "all" ? images : images.filter((img) => img.category === selectedCategory)

  return (
    <section id="galeria" className="py-20 bg-background scroll-mt-32">
      <div className="container mx-auto px-4">
        <div className="text-center mb-12">
          <ImageIcon className="h-12 w-12 text-primary mx-auto mb-4" />
          <h2 className="text-3xl md:text-4xl font-bold mb-4">Galeria Uniporá</h2>
          <p className="text-lg text-muted-foreground">
            Conheça nossa estrutura, eventos e a vida acadêmica na Uniporá
          </p>
        </div>

        <Tabs value={selectedCategory} onValueChange={setSelectedCategory} className="w-full">
          <TabsList className="grid w-full max-w-2xl mx-auto grid-cols-5 mb-8">
            {categories.map((cat) => (
              <TabsTrigger key={cat.value} value={cat.value}>
                {cat.label}
              </TabsTrigger>
            ))}
          </TabsList>

          {isLoading ? (
            <div className="flex justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
          ) : filteredImages.length === 0 ? (
            <div className="text-center py-12">
              <p className="text-muted-foreground">Nenhuma imagem encontrada nesta categoria.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredImages.map((image) => (
                <div key={image.id} className="group relative overflow-hidden rounded-lg aspect-video bg-muted">
                  <Image
                    src={image.image_url || "/placeholder.svg"}
                    alt={image.title}
                    fill
                    className="object-cover transition-transform duration-300 group-hover:scale-110"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity">
                    <div className="absolute bottom-0 left-0 right-0 p-4 text-white">
                      <h3 className="font-semibold mb-1">{image.title}</h3>
                      {image.description && <p className="text-sm text-white/90">{image.description}</p>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </Tabs>
      </div>
    </section>
  )
}
