'use client'

import { useState, useEffect, useCallback } from 'react'
import Image from 'next/image'
import { X, ChevronLeft, ChevronRight, ZoomIn, ZoomOut } from 'lucide-react'

interface ImageLightboxProps {
  images: string[]
  currentIndex: number
  open: boolean
  onClose: () => void
  onChangeIndex?: (index: number) => void
}

export function ImageLightbox({ images, currentIndex, open, onClose, onChangeIndex }: ImageLightboxProps) {
  const [idx, setIdx] = useState(currentIndex)
  const [zoomed, setZoomed] = useState(false)

  useEffect(() => { setIdx(currentIndex) }, [currentIndex])

  const goTo = useCallback((i: number) => {
    const next = (i + images.length) % images.length
    setIdx(next)
    setZoomed(false)
    onChangeIndex?.(next)
  }, [images.length, onChangeIndex])

  useEffect(() => {
    if (!open) return
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
      if (e.key === 'ArrowRight') goTo(idx - 1)
      if (e.key === 'ArrowLeft') goTo(idx + 1)
    }
    window.addEventListener('keydown', handler)
    document.body.style.overflow = 'hidden'
    return () => {
      window.removeEventListener('keydown', handler)
      document.body.style.overflow = ''
    }
  }, [open, idx, goTo, onClose])

  if (!open || images.length === 0) return null

  return (
    <div
      className="fixed inset-0 z-[100] bg-black/90 flex flex-col"
      onClick={onClose}
      dir="ltr"
    >
      {/* Top bar */}
      <div className="flex items-center justify-between px-6 py-4 text-white z-10">
        <button onClick={onClose} className="p-2 hover:bg-white/20 rounded-full transition-colors">
          <X className="w-6 h-6" />
        </button>
        <div className="text-sm">
          {idx + 1} / {images.length}
        </div>
        <button
          onClick={(e) => { e.stopPropagation(); setZoomed(!zoomed) }}
          className="p-2 hover:bg-white/20 rounded-full transition-colors"
        >
          {zoomed ? <ZoomOut className="w-5 h-5" /> : <ZoomIn className="w-5 h-5" />}
        </button>
      </div>

      {/* Image area */}
      <div
        className="flex-1 flex items-center justify-center relative overflow-hidden px-4"
        onClick={(e) => e.stopPropagation()}
      >
        {images.length > 1 && (
          <>
            <button
              onClick={() => goTo(idx - 1)}
              className="absolute left-4 top-1/2 -translate-y-1/2 p-3 bg-white/10 hover:bg-white/30 rounded-full text-white transition-colors z-10"
            >
              <ChevronLeft className="w-6 h-6" />
            </button>
            <button
              onClick={() => goTo(idx + 1)}
              className="absolute right-4 top-1/2 -translate-y-1/2 p-3 bg-white/10 hover:bg-white/30 rounded-full text-white transition-colors z-10"
            >
              <ChevronRight className="w-6 h-6" />
            </button>
          </>
        )}

        <div
          className={`relative transition-transform duration-300 ${zoomed ? 'scale-150 cursor-zoom-out' : 'cursor-zoom-in'}`}
          onClick={() => setZoomed(!zoomed)}
          style={{ width: '80%', maxWidth: 900, height: '70vh' }}
        >
          <Image
            src={images[idx]}
            alt={`صورة ${idx + 1}`}
            fill
            className="object-contain"
            sizes="(max-width: 768px) 100vw, 80vw"
            priority
          />
        </div>
      </div>

      {/* Thumbnails */}
      {images.length > 1 && (
        <div className="flex justify-center gap-2 p-4 bg-black/50 overflow-x-auto" onClick={e => e.stopPropagation()}>
          {images.map((img, i) => (
            <button
              key={i}
              onClick={() => goTo(i)}
              className={`relative w-16 h-12 rounded-lg overflow-hidden shrink-0 border-2 transition-all ${
                i === idx ? 'border-white opacity-100' : 'border-transparent opacity-50 hover:opacity-80'
              }`}
            >
              <Image src={img} alt="" fill className="object-cover" sizes="64px" />
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
