"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { ChevronLeft, ChevronRight } from "lucide-react"
import Link from "next/link"
import { createClient } from "@/lib/supabase/client"

interface Slide {
  id: string
  title: string
  subtitle: string
  button_text: string
  button_link: string
  background_image?: string
}


export function HeroCarousel() {
  const [currentSlide, setCurrentSlide] = useState(0)
  const [slides, setSlides] = useState<Slide[]>([])
  const [isLoading, setIsLoading] = useState(true)

  const [isOpen, setIsOpen] = useState(false)
  const [activeImage, setActiveImage] = useState<string | null>(null)

  const hasText = (value?: string) => value !== undefined && value.trim().length > 3

  useEffect(() => {
    let isMounted = true

    const loadSlides = async () => {
      const supabase = createClient()

      try {
        const { data, error } = await supabase
          .from("hero_slides")
          .select("*")
          .eq("is_active", true)
          .order("order_index", { ascending: true })

        if (!isMounted) return

        if (!error) {
          setSlides(data ?? [])
        }
      } catch (err) {
        // Silent fail
      } finally {
        if (isMounted) {
          setIsLoading(false)
        }
      }
    }

    loadSlides()

    return () => {
      isMounted = false
    }
  }, [])

  useEffect(() => {
    if (slides.length === 0) return

    const timer = setInterval(() => {
      setCurrentSlide((prev) => (prev + 1) % slides.length)
    }, 6000)

    return () => clearInterval(timer)
  }, [slides.length])

  const nextSlide = () => setCurrentSlide((prev) => (prev + 1) % slides.length)

  const prevSlide = () => setCurrentSlide((prev) => (prev - 1 + slides.length) % slides.length)

  if (isLoading) {
    return (
      <section className="relative h-[70vh] md:h-screen w-full overflow-hidden bg-gray-300 dark:bg-gray-800">
        <div
          className="
            absolute inset-0
            bg-gradient-to-r
            from-transparent
            via-white/40
            to-transparent
            -translate-x-full
            animate-[shimmer_1.8s_infinite]
          "
        />

        <div className="absolute bottom-24 left-10 md:left-14 space-y-4">
          <div className="h-10 w-72 md:w-[420px] rounded bg-gray-400/80 dark:bg-gray-700" />
          <div className="h-6 w-96 md:w-[520px] rounded bg-gray-400/70 dark:bg-gray-700" />
          <div className="h-12 w-40 rounded bg-gray-400/60 dark:bg-gray-700 mt-4" />
        </div>
      </section>
    )
  }

  if (slides.length === 0) {
    return null
  }

  return (
    <>
      <section className="relative w-full overflow-hidden h-[70vh] md:h-screen">
        {slides.map((slide, index) => (
          <div
            key={slide.id}
            className={`absolute top-[70px] md:top-[100px] left-0 right-0 bottom-0 transition-opacity duration-1000 ${
              index === currentSlide ? "opacity-100 z-20" : "opacity-0 pointer-events-none z-10"
            }`}
          >
            {/* BACKGROUND (CLICÁVEL) */}
            <div
              className="absolute inset-0 bg-cover bg-center cursor-zoom-in z-0"
              onClick={() => {
                if (slide.background_image) {
                  setActiveImage(slide.background_image)
                  setIsOpen(true)
                }
              }}
              style={{
                backgroundImage: slide.background_image
                  ? `url(${slide.background_image})`
                  : `url(/placeholder.svg?query=${encodeURIComponent(slide.title || "slide")})`,
              }}
            >
              <div className="absolute inset-0 bg-black/30" />
            </div>

            {/* CONTEÚDO (NÃO BLOQUEIA CLIQUE DA IMAGEM) */}
            <div className="relative h-full flex items-center z-10 pr-10 pl-14 pointer-events-none">
              <div className="max-w-3xl pointer-events-auto">
                {hasText(slide.title) && (
                  <h1 className="text-4xl md:text-6xl font-bold mb-6 bg-white/60 backdrop-blur px-6 py-2 inline-block">
                    {slide.title}
                  </h1>
                )}

                {hasText(slide.subtitle) && (
                  <p className="text-lg md:text-2xl mb-8 bg-white/60 backdrop-blur px-6 py-2">{slide.subtitle}</p>
                )}

                {hasText(slide.button_text) && hasText(slide.button_link) && (
                  <Button size="lg" asChild>
                    <Link href={slide.button_link}>{slide.button_text}</Link>
                  </Button>
                )}
              </div>
            </div>
          </div>
        ))}

        {/* SETAS */}
        <button
          onClick={prevSlide}
          className="absolute left-4 top-1/2 -translate-y-1/2 z-20 bg-white/50 backdrop-blur p-3 rounded-full hover:scale-110 transition-transform duration-200"
        >
          <ChevronLeft />
        </button>

        <button
          onClick={nextSlide}
          className="absolute right-4 top-1/2 -translate-y-1/2 z-20 bg-white/50 backdrop-blur p-3 rounded-full hover:scale-110 transition-transform duration-200"
        >
          <ChevronRight />
        </button>

        {/* INDICADORES */}
        <div className="absolute bottom-6 left-1/2 -translate-x-1/2 z-40 flex gap-3">
          {slides.map((_, index) => (
            <button
              key={index}
              onClick={() => setCurrentSlide(index)}
              className={`h-2 rounded-full transition-all ${
                index === currentSlide ? "w-8 bg-white" : "w-2 bg-white/50"
              }`}
            />
          ))}
        </div>
      </section>

      {/* MODAL FULLSCREEN */}
      {isOpen && activeImage && (
        <div
          className="fixed inset-0 z-[999] bg-black/90 flex items-center justify-center"
          onClick={() => setIsOpen(false)}
        >
          <img
            src={activeImage || "/placeholder.svg"}
            alt="Imagem ampliada"
            className="max-w-[95vw] max-h-[95vh] object-contain"
          />

          <button
            className="absolute top-6 right-6 text-white text-3xl"
            onClick={(e) => {
              e.stopPropagation()
              setIsOpen(false)
            }}
          >
            ✕
          </button>
        </div>
      )}
    </>
  )
}
