'use client';

import { useState, useEffect } from 'react';
import { X, ChevronLeft, ChevronRight, Star, Bookmark } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { createPortal } from 'react-dom';

interface Photo {
  id: number;
  path: string;
  title: string;
  size: number;
  thumbnail: string;
  type: string;
  bookmark_count: number;
  avg_rating: number;
  star_count: number;
}

interface FileSystemItem {
  name: string;
  path: string;
  isDirectory: boolean;
  size: number;
  thumbnail?: string;
  type?: string;
  id?: number;
}

interface PhotoViewerProps {
  photo: Photo | FileSystemItem;
  isOpen: boolean;
  onClose: () => void;
  onNext?: () => void;
  onPrev?: () => void;
  showNavigation?: boolean;
  showBookmarks?: boolean;
  showRatings?: boolean;
  formatFileSize?: (bytes: number) => string;
  onBookmark?: (photoId: number) => void;
  onUnbookmark?: (photoId: number) => void;
  onRate?: (photoId: number, rating: number) => void;
}

export default function PhotoViewer({
  photo,
  isOpen,
  onClose,
  onNext,
  onPrev,
  showNavigation = false,
  showBookmarks = false,
  showRatings = false,
  formatFileSize,
  onBookmark,
  onUnbookmark,
  onRate
}: PhotoViewerProps) {
  const [isPhotoLoading, setIsPhotoLoading] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setIsPhotoLoading(true);
    }
  }, [isOpen, photo]);

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (!isOpen) return;

      switch (event.key) {
        case 'Escape':
          handleClose();
          break;
        case 'ArrowLeft':
          if (onPrev) {
            event.preventDefault();
            handlePrev();
          }
          break;
        case 'ArrowRight':
          if (onNext) {
            event.preventDefault();
            handleNext();
          }
          break;
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown);
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen, onNext, onPrev]);

  const handleClose = () => {
    setIsPhotoLoading(false);
    onClose();
  };

  const handleNext = () => {
    if (onNext) {
      setIsPhotoLoading(true);
      onNext();
    }
  };

  const handlePrev = () => {
    if (onPrev) {
      setIsPhotoLoading(true);
      onPrev();
    }
  };

  const handleBookmark = () => {
    if (onBookmark && 'id' in photo && photo.id !== undefined) {
      onBookmark(photo.id);
    }
  };

  const handleUnbookmark = () => {
    if (onUnbookmark && 'id' in photo && photo.id !== undefined) {
      onUnbookmark(photo.id);
    }
  };

  const handleRate = (rating: number) => {
    if (onRate && 'id' in photo && photo.id !== undefined) {
      onRate(photo.id, rating);
    }
  };

  const getPhotoTitle = () => {
    if ('title' in photo) return photo.title;
    if ('name' in photo) return photo.name;
    return 'Photo';
  };

  const getPhotoSize = () => {
    if (formatFileSize) {
      return formatFileSize(photo.size);
    }
    // Default format function
    const bytes = photo.size;
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const getBookmarkCount = () => {
    if ('bookmark_count' in photo) return photo.bookmark_count;
    return 0;
  };

  const getAvgRating = () => {
    if ('avg_rating' in photo) return photo.avg_rating;
    return 0;
  };

  const getPhotoId = () => {
    if ('id' in photo && photo.id !== undefined) return photo.id;
    return 0;
  };

  if (!isOpen || typeof window === 'undefined') return null;

  return createPortal(
    <div className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center" onClick={handleClose}>
      <div className="relative w-full h-full max-w-7xl max-h-full p-4 flex items-center justify-center" onClick={(e) => e.stopPropagation()}>
        <div className="absolute top-4 right-4 z-10">
          <Button
            variant="secondary"
            size="icon"
            onClick={handleClose}
            className="bg-black/50 backdrop-blur-sm hover:bg-black/70"
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* Navigation Arrows */}
        {showNavigation && onNext && onPrev && (
          <>
            <Button
              variant="secondary"
              size="icon"
              onClick={handlePrev}
              className="absolute left-4 top-1/2 -translate-y-1/2 z-10 bg-black/50 backdrop-blur-sm hover:bg-black/70"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="secondary"
              size="icon"
              onClick={handleNext}
              className="absolute right-4 top-1/2 -translate-y-1/2 z-10 bg-black/50 backdrop-blur-sm hover:bg-black/70"
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </>
        )}

        {isPhotoLoading && (
          <div className="flex items-center justify-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
          </div>
        )}
        
        <img
          src={`/api/photos/${getPhotoId()}`}
          alt={getPhotoTitle()}
          className={`max-w-full max-h-[90vh] w-auto h-auto object-contain rounded-lg ${isPhotoLoading ? 'hidden' : ''}`}
          onLoad={() => setIsPhotoLoading(false)}
          onError={() => setIsPhotoLoading(false)}
        />

        {/* Photo Info Bar */}
        <div className="absolute bottom-4 left-4 right-4 bg-black/70 backdrop-blur-sm rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-white font-medium">{getPhotoTitle()}</h3>
              <p className="text-gray-300 text-sm">{getPhotoSize()}</p>
            </div>
            {(showBookmarks || showRatings) && (
              <div className="flex items-center gap-4">
                {showBookmarks && (
                  <button
                    onClick={getBookmarkCount() > 0 ? handleUnbookmark : handleBookmark}
                    className="flex items-center gap-1 text-white hover:text-yellow-400 transition-colors"
                  >
                    <Bookmark className={`h-4 w-4 ${getBookmarkCount() > 0 ? 'fill-yellow-400 text-yellow-400' : ''}`} />
                  </button>
                )}
                {showRatings && (
                  <div className="flex gap-1">
                    {[1, 2, 3, 4, 5].map((rating) => (
                      <button
                        key={rating}
                        onClick={() => handleRate(rating)}
                        className="text-white hover:text-yellow-400 transition-colors"
                      >
                        <Star className={`h-4 w-4 ${rating <= Math.round(getAvgRating()) ? 'fill-yellow-400 text-yellow-400' : ''}`} />
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
}
