import { useEffect, useCallback } from 'react';
import { X, ChevronLeft, ChevronRight } from 'lucide-react';
import type { Asset } from '@/types';

interface Props {
  asset: Asset;
  allAssets: Asset[];
  onClose: () => void;
  onNavigate: (asset: Asset) => void;
}

export function AssetPreview({ asset, allAssets, onClose, onNavigate }: Props) {
  const currentIndex = allAssets.findIndex((a) => a.id === asset.id);

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

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

  const handleKeyDown = useCallback((e: KeyboardEvent) => {
    if (e.key === 'Escape') onClose();
    if (e.key === 'ArrowLeft') goPrev();
    if (e.key === 'ArrowRight') goNext();
  }, [onClose, goPrev, goNext]);

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [handleKeyDown]);

  const hasPrev = currentIndex > 0;
  const hasNext = currentIndex < allAssets.length - 1;

  return (
    <div
      className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center"
      onClick={onClose}
    >
      <button
        onClick={onClose}
        className="absolute top-4 right-4 p-2 rounded-full bg-zinc-800 hover:bg-zinc-700 text-white z-10"
      >
        <X size={20} />
      </button>

      {/* Navigation arrows */}
      {hasPrev && (
        <button
          onClick={(e) => { e.stopPropagation(); goPrev(); }}
          className="absolute left-4 p-2 rounded-full bg-zinc-800/80 hover:bg-zinc-700 text-white z-10"
        >
          <ChevronLeft size={24} />
        </button>
      )}
      {hasNext && (
        <button
          onClick={(e) => { e.stopPropagation(); goNext(); }}
          className="absolute right-4 p-2 rounded-full bg-zinc-800/80 hover:bg-zinc-700 text-white z-10"
        >
          <ChevronRight size={24} />
        </button>
      )}

      <div className="max-w-[90vw] max-h-[90vh]" onClick={(e) => e.stopPropagation()}>
        {asset.type === 'image' ? (
          <img
            src={`/api/assets/file?path=${encodeURIComponent(asset.file_path)}`}
            alt=""
            className="max-w-full max-h-[90vh] object-contain rounded-lg"
          />
        ) : (
          <video
            src={`/api/assets/file?path=${encodeURIComponent(asset.file_path)}`}
            controls
            autoPlay
            className="max-w-full max-h-[90vh] rounded-lg"
          />
        )}
      </div>

      {/* Counter */}
      {allAssets.length > 1 && (
        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 text-xs text-zinc-400 bg-zinc-900/80 px-3 py-1 rounded-full">
          {currentIndex + 1} / {allAssets.length}
        </div>
      )}
    </div>
  );
}
