'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 [photosList, setPhotosList] = useState<Photo[]>([]);
  const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);

  const handlePhotoClick = (photo: Photo, index?: number) => {
    setSelectedPhoto(photo);
    if (index !== undefined) {
      setCurrentPhotoIndex(index);
    }
    setIsViewerOpen(true);
  };

  const handlePhotosData = (photos: Photo[]) => {
    setPhotosList(photos);
  };

  const handleNextPhoto = () => {
    if (photosList.length === 0) return;
    
    const currentPhotoId = selectedPhoto?.id;
    if (!currentPhotoId) return;
    
    const currentIndex = photosList.findIndex(p => p.id === currentPhotoId);
    if (currentIndex === -1) return;
    
    const nextIndex = (currentIndex + 1) % photosList.length;
    setSelectedPhoto(photosList[nextIndex]);
    setCurrentPhotoIndex(nextIndex);
  };

  const handlePrevPhoto = () => {
    if (photosList.length === 0) return;
    
    const currentPhotoId = selectedPhoto?.id;
    if (!currentPhotoId) return;
    
    const currentIndex = photosList.findIndex(p => p.id === currentPhotoId);
    if (currentIndex === -1) return;
    
    const prevIndex = (currentIndex - 1 + photosList.length) % photosList.length;
    setSelectedPhoto(photosList[prevIndex]);
    setCurrentPhotoIndex(prevIndex);
  };

  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}
        onDataUpdate={handlePhotosData}
      />

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