'use client';

import { useState } from 'react';
import VirtualizedMediaGrid from '@/components/virtualized-media-grid';
import PhotoViewer from '@/components/photo-viewer';

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

export default function PhotosPage() {
  const [selectedPhoto, setSelectedPhoto] = useState<Photo | null>(null);
  const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);
  const [isViewerOpen, setIsViewerOpen] = useState(false);

  const handlePhotoClick = (photo: Photo, index: number = 0) => {
    setSelectedPhoto(photo);
    setCurrentPhotoIndex(index);
    setIsViewerOpen(true);
  };

  const handleCloseViewer = () => {
    setIsViewerOpen(false);
    setSelectedPhoto(null);
  };

  const handleNextPhoto = () => {
    // This would need to be implemented with the virtualized grid
    // For now, we'll keep the current simple behavior
  };

  const handlePrevPhoto = () => {
    // This would need to be implemented with the virtualized grid
    // For now, we'll keep the current simple behavior
  };

  const handleBookmark = async (photoId: number) => {
    try {
      await fetch(`/api/bookmarks/${photoId}`, { method: 'POST' });
    } catch (error) {
      console.error('Error bookmarking photo:', error);
    }
  };

  const handleUnbookmark = async (photoId: number) => {
    try {
      await fetch(`/api/bookmarks/${photoId}`, { method: 'DELETE' });
    } catch (error) {
      console.error('Error unbookmarking photo:', error);
    }
  };

  const handleRate = async (photoId: number, rating: number) => {
    try {
      await fetch(`/api/stars/${photoId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ rating })
      });
    } catch (error) {
      console.error('Error rating photo:', error);
    }
  };

  const formatFileSize = (bytes: number) => {
    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];
  };

  return (
    <>
      <VirtualizedMediaGrid
        type="photo"
        onItemClick={handlePhotoClick}
        onBookmark={handleBookmark}
        onUnbookmark={handleUnbookmark}
        onRate={handleRate}
      />

      {/* Photo Viewer */}
      <PhotoViewer
        photo={selectedPhoto!}
        isOpen={isViewerOpen}
        onClose={handleCloseViewer}
        onNext={handleNextPhoto}
        onPrev={handlePrevPhoto}
        showNavigation={false}
        showBookmarks={true}
        showRatings={true}
        formatFileSize={formatFileSize}
        onBookmark={handleBookmark}
        onUnbookmark={handleUnbookmark}
        onRate={handleRate}
      />
    </>
  );
}