import { useState, useRef, useEffect } from 'react'
import { ImageOff, X } from 'lucide-react'
import { apiOrigin } from '@/lib/api/client'

function buildSrc(value: string | null | undefined): string | null {
  if (!value) return null
  if (value.startsWith('http')) return value
  const clean = value.replace(/^\/+/, '').replace(/^storage\//, '')
  return `${apiOrigin}/${clean}`
}

export function TableImagePreview({
  src,
  alt = '',
}: {
  src: string | null | undefined
  alt?: string
}) {
  const [open, setOpen] = useState(false)
  const resolved = buildSrc(src)
  const backdropRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setOpen(false)
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [open])

  if (!resolved) {
    return (
      <div className='flex h-10 w-14 items-center justify-center rounded-lg bg-muted text-muted-foreground'>
        <ImageOff className='size-4' />
      </div>
    )
  }

  return (
    <>
      <button
        type='button'
        className='group relative block h-10 w-14 shrink-0 overflow-hidden rounded-lg border border-border/50 bg-muted transition hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'
        onClick={() => setOpen(true)}
      >
        <img
          src={resolved}
          alt={alt}
          className='h-full w-full object-cover transition group-hover:scale-110'
          loading='lazy'
        />
        <div className='absolute inset-0 bg-black/0 transition group-hover:bg-black/10' />
      </button>

      {open && (
        <div
          ref={backdropRef}
          className='fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-sm'
          onClick={(e) => {
            if (e.target === backdropRef.current) setOpen(false)
          }}
        >
          <button
            type='button'
            className='absolute top-4 right-4 z-10 rounded-full bg-white/10 p-2 text-white transition hover:bg-white/20'
            onClick={() => setOpen(false)}
          >
            <X className='size-5' />
          </button>
          <img
            src={resolved}
            alt={alt}
            className='max-h-[85vh] max-w-[90vw] rounded-xl object-contain shadow-2xl'
          />
        </div>
      )}
    </>
  )
}
