'use client';

import { useState } from 'react';
import InfiniteVirtualGrid from '@/components/infinite-virtual-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 [isViewerOpen, setIsViewerOpen] = useState(false);

  const handlePhotoClick = (photo: Photo) => {
    setSelectedPhoto(photo);
    setIsViewerOpen(true);
  };

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

  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);
    }
  };

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

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