import { useCallback, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ChevronLeft, ChevronRight, X, Download, ImageOff } from 'lucide-react';
import { authFetch } from '../../lib/auth';
import { useAuthedFileUrl } from '../../lib/authedFile';

/** One lightbox entry: the (possibly data:/`/api/files`) URL plus the human filename,
 *  so downloads and alt text use the real name rather than a URL stamp. */
export interface LightboxImage {
  url: string;
  name?: string;
}

interface Props {
  images: LightboxImage[];
  index: number;
  onClose: () => void;
  onNavigate: (index: number) => void;
}

export default function ImageLightbox({ images, index, onClose, onNavigate }: Props) {
  const current = images[index];

  const goPrev = useCallback(() => {
    if (index > 0) onNavigate(index - 1);
  }, [index, onNavigate]);

  const goNext = useCallback(() => {
    if (index < images.length - 1) onNavigate(index + 1);
  }, [index, images.length, onNavigate]);

  // /api/files/* needs the auth token, which a native <img src> can't send — resolve
  // the currently-shown image to a blob URL fetched with the Authorization header.
  const { url: resolvedSrc, status } = useAuthedFileUrl(current?.url);

  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') goPrev();
      if (e.key === 'ArrowRight') goNext();
    };
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [onClose, goPrev, goNext]);

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        transition={{ duration: 0.15 }}
        className="fixed inset-0 z-50 flex items-center justify-center bg-black/90"
        onClick={onClose}
      >
        {/* Action buttons */}
        <div className="absolute top-4 right-4 z-10 flex gap-2">
          <button
            onClick={async (e) => {
              e.stopPropagation();
              try {
                const res = await authFetch(current.url);
                const blob = await res.blob();
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = current.name || current.url.split('/').pop() || 'image';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
              } catch {
                window.open(current.url, '_blank');
              }
            }}
            className="p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors text-white"
            title="Download"
          >
            <Download className="h-5 w-5" />
          </button>
          <button
            onClick={onClose}
            className="p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors text-white"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Image counter */}
        {images.length > 1 && (
          <div className="absolute top-4 left-1/2 -translate-x-1/2 text-white/70 text-sm tabular-nums">
            {index + 1} / {images.length}
          </div>
        )}

        {/* Left arrow */}
        {index > 0 && (
          <button
            onClick={(e) => { e.stopPropagation(); goPrev(); }}
            className="absolute left-3 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors text-white"
          >
            <ChevronLeft className="h-6 w-6" />
          </button>
        )}

        {/* Right arrow */}
        {index < images.length - 1 && (
          <button
            onClick={(e) => { e.stopPropagation(); goNext(); }}
            className="absolute right-3 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors text-white"
          >
            <ChevronRight className="h-6 w-6" />
          </button>
        )}

        {/* Image */}
        {status === 'error' ? (
          <div
            className="flex flex-col items-center gap-2 rounded-lg bg-white/5 px-8 py-10 text-white/50"
            onClick={(e) => e.stopPropagation()}
          >
            <ImageOff className="h-10 w-10" />
            <span className="text-sm">{current?.name || 'Image not found'}</span>
          </div>
        ) : resolvedSrc ? (
          <img
            src={resolvedSrc}
            alt={current?.name || ''}
            className="max-h-[85vh] max-w-[90vw] object-contain rounded-lg"
            onClick={(e) => e.stopPropagation()}
          />
        ) : (
          <div
            className="h-40 w-40 rounded-lg bg-white/10 animate-pulse"
            onClick={(e) => e.stopPropagation()}
          />
        )}
      </motion.div>
    </AnimatePresence>
  );
}
