"use client"

import { useState, useEffect } from "react"
import { createPortal } from "react-dom"

type Photo = {
  url: string
  filename?: string
}

interface PhotoCarouselProps {
  photos: Photo[]
  altText: string
  height?: string | number
  borderRadius?: string
  objectFit?: "cover" | "contain"
}

export function PhotoCarousel({ 
  photos, 
  altText, 
  height = "200px", 
  borderRadius = "var(--radius-t-lg)",
  objectFit = "cover" 
}: PhotoCarouselProps) {
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isFullscreen, setIsFullscreen] = useState(false)

  useEffect(() => {
    if (!isFullscreen) return
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setIsFullscreen(false)
      if (e.key === "ArrowRight") setCurrentIndex(prev => (prev === photos.length - 1 ? 0 : prev + 1))
      if (e.key === "ArrowLeft")  setCurrentIndex(prev => (prev === 0 ? photos.length - 1 : prev - 1))
    }
    
    document.body.style.overflow = "hidden"
    window.addEventListener("keydown", handleKeyDown)
    return () => {
      document.body.style.overflow = "auto"
      window.removeEventListener("keydown", handleKeyDown)
    }
  }, [isFullscreen, photos.length])

  if (!photos || photos.length === 0) {
    return (
      <div style={{ width: "100%", height, background: "var(--surface-hover)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-muted)", borderRadius }}>
        Fără imagine
      </div>
    )
  }

  const handlePrev = (e?: React.MouseEvent | KeyboardEvent) => {
    if (e && 'preventDefault' in e) e.preventDefault()
    if (e && 'stopPropagation' in e) e.stopPropagation()
    setCurrentIndex(prev => (prev === 0 ? photos.length - 1 : prev - 1))
  }

  const handleNext = (e?: React.MouseEvent | KeyboardEvent) => {
    if (e && 'preventDefault' in e) e.preventDefault()
    if (e && 'stopPropagation' in e) e.stopPropagation()
    setCurrentIndex(prev => (prev === photos.length - 1 ? 0 : prev + 1))
  }

  return (
    <>
      <div 
        style={{ position: "relative", width: "100%", height, borderRadius, overflow: "hidden", cursor: "pointer" }} 
        onClick={() => setIsFullscreen(true)}
      >
        {/* Expansion hover hint */}
        <div style={{ position: "absolute", top: "0.5rem", right: "0.5rem", background: "rgba(0,0,0,0.6)", color: "white", padding: "0.4rem", borderRadius: "50%", display: "flex", pointerEvents: "none", zIndex: 11 }}>
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M9 21H3v-6"/><path d="M14 10 3 21"/></svg>
        </div>

        {/* eslint-disable-next-line @next/next/no-img-element */}
      <img 
        src={photos[currentIndex].url} 
        alt={`${altText} - ${currentIndex + 1}`} 
        style={{ width: "100%", height: "100%", objectFit, display: "block" }}
      />
      
      {photos.length > 1 && (
        <>
          <button
            onClick={handlePrev}
            style={{
              position: "absolute",
              top: "50%",
              left: "8px",
              transform: "translateY(-50%)",
              background: "rgba(0,0,0,0.5)",
              color: "white",
              border: "none",
              borderRadius: "50%",
              width: "28px",
              height: "28px",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              cursor: "pointer",
              zIndex: 10
            }}
            aria-label="Imaginea anterioară"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"/></svg>
          </button>
          
          <button
            onClick={handleNext}
            style={{
              position: "absolute",
              top: "50%",
              right: "8px",
              transform: "translateY(-50%)",
              background: "rgba(0,0,0,0.5)",
              color: "white",
              border: "none",
              borderRadius: "50%",
              width: "28px",
              height: "28px",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              cursor: "pointer",
              zIndex: 10
            }}
            aria-label="Imaginea următoare"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6"/></svg>
          </button>

          <div style={{
            position: "absolute",
            bottom: "8px",
            right: "8px",
            background: "rgba(0,0,0,0.6)",
            color: "white",
            fontSize: "0.7rem",
            padding: "2px 6px",
            borderRadius: "12px",
            fontWeight: 600,
            zIndex: 10
          }}>
            {currentIndex + 1} / {photos.length}
          </div>
        </>
      )}
    </div>

    {/* Lightbox Portal */}
    {isFullscreen && typeof document !== "undefined" && createPortal(
      <div style={{ position: "fixed", inset: 0, zIndex: 99999, background: "rgba(0,0,0,0.9)", display: "flex", alignItems: "center", justifyContent: "center" }} onClick={() => setIsFullscreen(false)}>
        <button 
          onClick={(e) => { e.stopPropagation(); setIsFullscreen(false); }}
          style={{ position: "absolute", top: "1.5rem", right: "1.5rem", background: "rgba(255,255,255,0.1)", border: "none", color: "white", borderRadius: "50%", padding: "0.5rem", cursor: "pointer", zIndex: 100000, display: "flex" }}
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
        
        {photos.length > 1 && (
          <>
            <button 
              onClick={(e) => { handlePrev(e as any); }}
              style={{ position: "absolute", left: "1.5rem", top: "50%", transform: "translateY(-50%)", background: "rgba(255,255,255,0.1)", border: "none", color: "white", borderRadius: "50%", width: "48px", height: "48px", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", zIndex: 100000 }}
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"/></svg>
            </button>
            <button 
              onClick={(e) => { handleNext(e as any); }}
              style={{ position: "absolute", right: "1.5rem", top: "50%", transform: "translateY(-50%)", background: "rgba(255,255,255,0.1)", border: "none", color: "white", borderRadius: "50%", width: "48px", height: "48px", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", zIndex: 100000 }}
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6"/></svg>
            </button>
          </>
        )}

        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img 
          src={photos[currentIndex].url}
          alt={`${altText} Fullscreen - ${currentIndex + 1}`}
          style={{ maxWidth: "90vw", maxHeight: "85vh", objectFit: "contain", userSelect: "none", cursor: "default", borderRadius: "var(--radius-md)" }}
          onClick={(e) => e.stopPropagation()}
        />
        
        <a 
          href={photos[currentIndex].url}
          download
          target="_blank"
          onClick={(e) => e.stopPropagation()}
          style={{ position: "absolute", bottom: "3.5rem", background: "rgba(255,255,255,0.1)", color: "white", padding: "0.5rem 1.25rem", borderRadius: "999px", fontSize: "0.85rem", textDecoration: "none", display: "flex", alignItems: "center", gap: "0.5rem", border: "1px solid rgba(255,255,255,0.2)" }}
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          Descarcă
        </a>

        {photos.length > 1 && (
          <div style={{ position: "absolute", bottom: "1.5rem", color: "rgba(255,255,255,0.7)", fontSize: "0.9rem", fontWeight: 500, letterSpacing: "1px" }}>
            {currentIndex + 1} / {photos.length}
          </div>
        )}
      </div>,
      document.body
    )}
    </>
  )
}
