'use client'
import { useEffect, useState } from 'react'
import type { ImageItem } from '@/types/images'

interface LightboxProps {
  item: ImageItem | null
  onClose: () => void
}

function BlobImg({ blob, alt }: { blob: Blob; alt: string }) {
  const [url, setUrl] = useState<string | null>(null)

  useEffect(() => {
    const u = URL.createObjectURL(blob)
    setUrl(u)
    return () => URL.revokeObjectURL(u)
  }, [blob])

  if (!url) return null
  return <img src={url} alt={alt} className="max-h-full max-w-full object-contain" />
}

export function Lightbox({ item, onClose }: LightboxProps) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [onClose])

  if (!item) return null

  return (
    <div
      className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-slate-900 rounded-xl max-w-5xl w-full max-h-[90vh] overflow-hidden flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-4 py-3 border-b border-slate-700">
          <div>
            <span className="text-sm font-mono text-slate-300">{item.ref}</span>
            {item.shopifyProductTitle && (
              <span className="text-xs text-slate-500 ml-2">{item.shopifyProductTitle}</span>
            )}
          </div>
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-white text-xl leading-none"
          >✕</button>
        </div>

        <div className="flex flex-1 overflow-hidden min-h-0">
          <div className="flex-1 flex flex-col items-center justify-center p-4 bg-slate-950 border-r border-slate-700">
            <p className="text-xs text-slate-500 mb-2">Avant</p>
            <BlobImg blob={item.originalBlob} alt="Avant" />
          </div>
          <div className="flex-1 flex flex-col items-center justify-center p-4 bg-white/5">
            <p className="text-xs text-slate-500 mb-2">Après</p>
            {item.processedBlob
              ? <BlobImg blob={item.processedBlob} alt="Après" />
              : <p className="text-slate-600 text-sm">Traitement en cours…</p>
            }
          </div>
        </div>
      </div>
    </div>
  )
}
