"use client";

import { useState } from "react";
import VirtualizedMediaGrid from "@/components/virtualized-media-grid";
import VideoViewer from "@/components/video-viewer";

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

const VideosPage = () => {
  const [selectedVideo, setSelectedVideo] = useState<Video | null>(null);
  const [isPlayerOpen, setIsPlayerOpen] = useState(false);

  const handleVideoClick = (video: Video) => {
    setSelectedVideo(video);
    setIsPlayerOpen(true);
  };

  const handleClosePlayer = () => {
    setIsPlayerOpen(false);
    setSelectedVideo(null);
  };

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

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

  const handleRate = async (videoId: number, rating: number) => {
    try {
      await fetch(`/api/stars/${videoId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ rating })
      });
    } catch (error) {
      console.error('Error rating video:', 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="video"
        onItemClick={handleVideoClick}
        onBookmark={handleBookmark}
        onUnbookmark={handleUnbookmark}
        onRate={handleRate}
      />

      {/* Video Viewer */}
      <VideoViewer
        video={selectedVideo!}
        isOpen={isPlayerOpen}
        onClose={handleClosePlayer}
        showBookmarks={true}
        showRatings={true}
        formatFileSize={formatFileSize}
        onBookmark={handleBookmark}
        onUnbookmark={handleUnbookmark}
        onRate={handleRate}
      />
    </>
  );
};

export default VideosPage;