"use client"

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

export function EntryPhotoGallery({ photos, title, isAdminView }: { photos: any[], title: string, isAdminView?: boolean }) {
  const [fullscreenIndex, setFullscreenIndex] = useState<number | null>(null)
  
  useEffect(() => {
    if (fullscreenIndex === null) return
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setFullscreenIndex(null)
      if (e.key === "ArrowRight") setFullscreenIndex(prev => prev !== null ? (prev === photos.length - 1 ? 0 : prev + 1) : null)
      if (e.key === "ArrowLeft") setFullscreenIndex(prev => prev !== null ? (prev === 0 ? photos.length - 1 : prev - 1) : null)
    }
    
    document.body.style.overflow = "hidden"
    window.addEventListener("keydown", handleKeyDown)
    return () => {
      document.body.style.overflow = "auto"
      window.removeEventListener("keydown", handleKeyDown)
    }
  }, [fullscreenIndex, photos.length])

  if (!photos || photos.length === 0) return null

  return (
    <>
      <div 
        style={{ 
          display: "grid", 
          gridTemplateColumns: (!isAdminView && photos.length === 1) ? "1fr" : "repeat(auto-fit, minmax(250px, 1fr))", 
          gap: isAdminView ? "1rem" : "0.75rem" 
        }}
      >
        {photos.map((photo, i) => (
          <div key={photo.id} style={{ border: isAdminView ? "1px solid var(--border-color)" : "none", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
            <div 
              style={{ position: "relative", cursor: "pointer", aspectRatio: isAdminView ? "auto" : "4/3", height: isAdminView ? "200px" : "auto", display: "block" }} 
              onClick={() => setFullscreenIndex(i)}
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={photo.url} alt={`Fotografie ${i + 1} — ${title}`} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
              
              <a 
                href={photo.url} 
                download 
                target="_blank"
                onClick={(e) => e.stopPropagation()}
                style={{ position: "absolute", bottom: "0.5rem", right: "0.5rem", background: "rgba(0,0,0,0.6)", color: "white", padding: "0.4rem 0.6rem", borderRadius: "100px", fontSize: "0.75rem", textDecoration: "none", display: "flex", alignItems: "center", gap: "0.3rem", fontWeight: 500 }}
              >
                <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="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>
                Descărcare (1:1)
              </a>

              {/* Expansion hint icon */}
              <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" }}>
                <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>
            </div>
            
            {isAdminView && (
              <div style={{ padding: "0.75rem", fontSize: "0.85rem", background: "var(--surface-hover)", borderTop: "1px solid var(--border-color)" }}>
                <p><strong>Data:</strong> {new Date(photo.dateOfCapture).toLocaleDateString("ro-RO")}</p>
                {photo.equipment && <p><strong>Aparat:</strong> {photo.equipment}</p>}
                {photo.technicalSettings && <p><strong>Setări:</strong> {photo.technicalSettings}</p>}
              </div>
            )}
          </div>
        ))}
      </div>

      {!isAdminView && photos[0]?.equipment && (
        <p style={{ marginTop: "0.5rem", fontSize: "0.82rem", color: "var(--text-muted)", textAlign: "right" }}>
          📷 {photos[0].equipment}
          {photos[0].technicalSettings && ` — ${photos[0].technicalSettings}`}
        </p>
      )}

      {/* Lightbox Portal */}
      {fullscreenIndex !== null && typeof document !== "undefined" && createPortal(
        <div style={{ position: "fixed", inset: 0, zIndex: 9999, background: "rgba(0,0,0,0.9)", display: "flex", alignItems: "center", justifyContent: "center" }} onClick={() => setFullscreenIndex(null)}>
          <button 
            onClick={() => setFullscreenIndex(null)}
            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: 10000, 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) => { e.stopPropagation(); setFullscreenIndex(prev => prev !== null ? (prev === 0 ? photos.length - 1 : prev - 1) : null); }}
                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: 10000 }}
              >
                <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) => { e.stopPropagation(); setFullscreenIndex(prev => prev !== null ? (prev === photos.length - 1 ? 0 : prev + 1) : null); }}
                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: 10000 }}
              >
                <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[fullscreenIndex].url}
            alt={`Fullscreen imagine ${fullscreenIndex + 1}`}
            style={{ maxWidth: "90vw", maxHeight: "85vh", objectFit: "contain", userSelect: "none", cursor: "default", borderRadius: "var(--radius-md)" }}
            onClick={(e) => e.stopPropagation()}
          />
          
          <a 
            href={photos[fullscreenIndex].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" }}>
              {fullscreenIndex + 1} / {photos.length}
            </div>
          )}
        </div>,
        document.body
      )}
    </>
  )
}
