'use client'

import * as React from 'react'
import { ChevronLeft, ChevronRight, Camera } from 'lucide-react'
import { cn } from '@/lib/utils'

interface PropertyGalleryProps {
  images: string[]
  title: string
  onImageClick?: (index: number) => void
  className?: string
}

export function PropertyGallery({ images, title, onImageClick, className }: PropertyGalleryProps) {
  const [currentPage, setCurrentPage] = React.useState(0)
  const imagesPerPage = 4
  const totalPages = Math.ceil(images.length / imagesPerPage)
  
  const visibleImages = images.slice(
    currentPage * imagesPerPage,
    (currentPage + 1) * imagesPerPage
  )

  const handlePrevious = (e: React.MouseEvent) => {
    e.stopPropagation()
    setCurrentPage((prev) => (prev === 0 ? totalPages - 1 : prev - 1))
  }

  const handleNext = (e: React.MouseEvent) => {
    e.stopPropagation()
    setCurrentPage((prev) => (prev === totalPages - 1 ? 0 : prev + 1))
  }

  // Ensure we always show 4 slots (fill with placeholder if needed)
  const displayImages = [...visibleImages]
  while (displayImages.length < 4 && images.length > 0) {
    displayImages.push(images[displayImages.length % images.length])
  }

  return (
    <div className={cn('relative group overflow-hidden rounded-lg', className)}>
      {/* Main grid layout - 1 large + 3 small */}
      <div className="grid grid-cols-3 grid-rows-2 gap-1 aspect-[4/3]">
        {/* Large image - spans 2 columns and 2 rows */}
        <button
          type="button"
          className="col-span-2 row-span-2 relative overflow-hidden focus:outline-none focus:ring-2 focus:ring-primary focus:ring-inset"
          onClick={() => onImageClick?.(currentPage * imagesPerPage)}
          aria-label={`Ver foto principal de ${title}`}
        >
          <img
            src={displayImages[0]}
            alt={`${title} - Foto principal`}
            className="absolute inset-0 w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
          />
        </button>

        {/* Three smaller images stacked */}
        {displayImages.slice(1, 4).map((image, idx) => (
          <button
            key={`${image}-${idx}`}
            type="button"
            className="relative overflow-hidden focus:outline-none focus:ring-2 focus:ring-primary focus:ring-inset"
            onClick={() => onImageClick?.(currentPage * imagesPerPage + idx + 1)}
            aria-label={`Ver foto ${idx + 2} de ${title}`}
          >
            <img
              src={image}
              alt={`${title} - Foto ${idx + 2}`}
              className="absolute inset-0 w-full h-full object-cover transition-transform duration-300 hover:scale-110"
            />
            {/* Show remaining count on last image if more than 4 total */}
            {idx === 2 && images.length > imagesPerPage && (
              <div className="absolute inset-0 bg-foreground/40 flex items-center justify-center transition-opacity">
                <span className="text-card font-semibold text-sm flex items-center gap-1">
                  <Camera className="size-4" />
                  +{images.length - imagesPerPage}
                </span>
              </div>
            )}
          </button>
        ))}
      </div>

      {/* Navigation arrows - only show if more than one page */}
      {totalPages > 1 && (
        <>
          <button
            type="button"
            onClick={handlePrevious}
            className="absolute left-2 top-1/2 -translate-y-1/2 size-8 rounded-full bg-card/90 text-foreground shadow-md flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-card focus:opacity-100 focus:outline-none focus:ring-2 focus:ring-primary"
            aria-label="Fotos anteriores"
          >
            <ChevronLeft className="size-5" />
          </button>
          <button
            type="button"
            onClick={handleNext}
            className="absolute right-2 top-1/2 -translate-y-1/2 size-8 rounded-full bg-card/90 text-foreground shadow-md flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-card focus:opacity-100 focus:outline-none focus:ring-2 focus:ring-primary"
            aria-label="Próximas fotos"
          >
            <ChevronRight className="size-5" />
          </button>

          {/* Page indicators */}
          <div className="absolute bottom-2 left-1/2 -translate-x-1/2 flex gap-1.5">
            {Array.from({ length: totalPages }).map((_, idx) => (
              <button
                key={idx}
                type="button"
                onClick={(e) => {
                  e.stopPropagation()
                  setCurrentPage(idx)
                }}
                className={cn(
                  'size-2 rounded-full transition-all',
                  currentPage === idx 
                    ? 'bg-card w-4' 
                    : 'bg-card/60 hover:bg-card/80'
                )}
                aria-label={`Ir para página ${idx + 1} de fotos`}
                aria-current={currentPage === idx ? 'true' : undefined}
              />
            ))}
          </div>
        </>
      )}
    </div>
  )
}
