"use client";

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import InlineVideoPlayer from "@/components/inline-video-player";
import { Bookmark, Heart, Star, Film, Image as ImageIcon } from 'lucide-react';

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

export default function BookmarksPage() {
  const [items, setItems] = useState<MediaItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedItem, setSelectedItem] = useState<MediaItem | null>(null);
  const [isPlayerOpen, setIsPlayerOpen] = useState(false);
  const [scrollPosition, setScrollPosition] = useState(0);

  useEffect(() => {
    fetchBookmarkedItems();
  }, []);

  const fetchBookmarkedItems = async () => {
    try {
      const response = await fetch('/api/bookmarks');
      const data = await response.json();
      setItems(data);
    } catch (error) {
      console.error('Error fetching bookmarked items:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleItemClick = (item: MediaItem) => {
    setScrollPosition(window.scrollY);
    setSelectedItem(item);
    setIsPlayerOpen(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleClosePlayer = () => {
    setIsPlayerOpen(false);
    setSelectedItem(null);
    // Restore scroll position
    setTimeout(() => {
      window.scrollTo({ top: scrollPosition, behavior: 'smooth' });
    }, 100);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-4"></div>
          <p className="text-muted-foreground">Loading bookmarked items...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-zinc-950">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-12 h-12 bg-blue-500 rounded-lg flex items-center justify-center">
              <Bookmark className="h-6 w-6 text-white" />
            </div>
            <div>
              <h1 className="text-3xl font-bold text-white">Bookmarked Items</h1>
              <p className="text-zinc-400 mt-1">
                {items.length} {items.length === 1 ? 'item' : 'items'} bookmarked
              </p>
            </div>
          </div>
        </div>

        {items.length === 0 ? (
          <div className="flex flex-col items-center justify-center min-h-[60vh]">
            <div className="text-center max-w-md">
              <div className="w-20 h-20 bg-zinc-900 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg">
                <Bookmark className="h-10 w-10 text-zinc-400" />
              </div>
              <h2 className="text-2xl font-bold text-white mb-2">No Bookmarks Yet</h2>
              <p className="text-zinc-400">
                Start bookmarking videos and photos by clicking the bookmark icon.
              </p>
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 gap-4">
            {items.map((item) => (
              <Card
                key={item.id}
                className="group bg-white dark:bg-slate-800 border-0 shadow-sm hover:shadow-lg transition-all duration-300 hover:-translate-y-1 overflow-hidden cursor-pointer"
                onClick={() => handleItemClick(item)}
              >
                <CardHeader className="p-0">
                  <div className={`relative overflow-hidden ${item.type === 'photo' ? 'aspect-square' : 'aspect-video'} bg-slate-200 dark:bg-slate-700`}>
                    {item.thumbnail ? (
                      <img
                        src={item.thumbnail}
                        alt={item.title}
                        className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-slate-200 to-slate-300 dark:from-slate-700 dark:to-slate-800">
                        {item.type === 'photo' ? (
                          <ImageIcon className="w-12 h-12 text-slate-400" />
                        ) : (
                          <Film className="w-12 h-12 text-slate-400" />
                        )}
                      </div>
                    )}
                    <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                  </div>
                </CardHeader>
                <CardContent className="p-3">
                  <CardTitle className="text-sm font-semibold text-slate-900 dark:text-slate-100 truncate mb-1">
                    {item.title || item.path.split('/').pop()}
                  </CardTitle>
                  <CardDescription className="text-xs text-slate-600 dark:text-slate-400">
                    {formatFileSize(item.size)}
                  </CardDescription>
                  
                  {/* Stats */}
                  <div className="flex items-center gap-3 mt-2 text-xs text-slate-500 dark:text-slate-400">
                    <div className="flex items-center gap-1">
                      <Heart className="h-3 w-3" />
                      <span>{item.bookmark_count || 0}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Star className="h-3 w-3" />
                      <span>{item.avg_rating?.toFixed(1) || '0.0'}</span>
                    </div>
                  </div>
                  
                  <div className="text-xs text-slate-500 dark:text-slate-400 mt-1 truncate">
                    {item.type === 'photo' ? (
                      <span className="flex items-center gap-1">
                        <ImageIcon className="h-3 w-3" /> {item.library_path?.split('/').pop()}
                      </span>
                    ) : (
                      <span className="flex items-center gap-1">
                        <Film className="h-3 w-3" /> {item.library_path?.split('/').pop()}
                      </span>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* Inline Video Player */}
      {selectedItem && selectedItem.type === 'video' && (
        <InlineVideoPlayer
          video={{
            id: selectedItem.id,
            title: selectedItem.title || selectedItem.path.split('/').pop() || 'Untitled',
            path: selectedItem.path,
            size: selectedItem.size,
            thumbnail: selectedItem.thumbnail || '',
          }}
          isOpen={isPlayerOpen}
          onClose={handleClosePlayer}
          scrollPosition={scrollPosition}
        />
      )}
    </div>
  );
}