'use client';

import { useState } from 'react';
import InfiniteVirtualGrid from '@/components/infinite-virtual-grid';
import VideoViewer from '@/components/video-viewer';
import PhotoViewer from '@/components/photo-viewer';

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

export default function BookmarksPage() {
  const [selectedItem, setSelectedItem] = useState<MediaItem | null>(null);
  const [isViewerOpen, setIsViewerOpen] = useState(false);
  const [isVideoPlayerOpen, setIsVideoPlayerOpen] = useState(false);

  const handleItemClick = (item: MediaItem) => {
    if (item.type === 'video') {
      setSelectedItem(item);
      setIsVideoPlayerOpen(true);
    } else {
      setSelectedItem(item);
      setIsViewerOpen(true);
    }
  };

  const handleCloseVideoPlayer = () => {
    setIsVideoPlayerOpen(false);
    setSelectedItem(null);
  };

  const handleClosePhotoViewer = () => {
    setIsViewerOpen(false);
    setSelectedItem(null);
  };

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

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

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

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

      {/* Video Player */}
      {selectedItem && selectedItem.type === 'video' && (
        <VideoViewer
          video={selectedItem}
          isOpen={isVideoPlayerOpen}
          onClose={handleCloseVideoPlayer}
          showBookmarks={true}
          showRatings={true}
          onBookmark={handleBookmark}
          onUnbookmark={handleUnbookmark}
          onRate={handleRate}
        />
      )}

      {/* Photo Viewer */}
      {selectedItem && selectedItem.type === 'photo' && (
        <PhotoViewer
          photo={selectedItem}
          isOpen={isViewerOpen}
          onClose={handleClosePhotoViewer}
          showBookmarks={true}
          showRatings={true}
          onBookmark={handleBookmark}
          onUnbookmark={handleUnbookmark}
          onRate={handleRate}
        />
      )}
    </>
  );
}