
"use client";

import { useState, useEffect, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { Folder, File, Image, Film } from "lucide-react";
import Link from "next/link";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";

interface FileSystemItem {
  name: string;
  path: string;
  isDirectory: boolean;
  size: number;
  thumbnail?: string;
  type?: string;
}

const FolderViewerPage = () => {
  const searchParams = useSearchParams();
  const path = searchParams.get("path");
  const [items, setItems] = useState<FileSystemItem[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (path) {
      fetchItems(path);
    }
  }, [path]);

  const fetchItems = async (currentPath: string) => {
    setLoading(true);
    try {
      const res = await fetch(`/api/files?path=${currentPath}`);
      const data = await res.json();
      setItems(data);
    } catch (error) {
      console.error('Error fetching 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 getFileIcon = (item: FileSystemItem) => {
    if (item.isDirectory) return <Folder className="text-blue-500" size={48} />;
    if (item.type === 'photo') return <Image className="text-green-500" size={48} />;
    if (item.type === 'video') return <Film className="text-red-500" size={48} />;
    return <File className="text-gray-500" size={48} />;
  };

  const isMediaFile = (item: FileSystemItem) => {
    return item.type === 'video' || item.type === 'photo';
  };

  if (!path) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <p className="text-gray-500 text-lg mb-4">Select a library from the sidebar</p>
          <p className="text-gray-400">Choose a media library above to browse its contents</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-zinc-950">
      {loading && (
        <div className="fixed inset-0 bg-black/5 backdrop-blur-sm z-50 flex items-center justify-center">
          <div className="bg-white dark:bg-slate-800 rounded-xl p-6 shadow-xl">
            <div className="flex items-center space-x-3">
              <div className="animate-spin rounded-full h-5 w-5 border-2 border-slate-900 dark:border-white border-t-transparent"></div>
              <span className="text-sm font-medium text-slate-700 dark:text-slate-300">Loading directory...</span>
            </div>
          </div>
        </div>
      )}
      
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {!path ? (
          <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">
                <Folder className="h-10 w-10 text-blue-500" />
              </div>
              <h2 className="text-2xl font-bold text-white mb-2">Select a Library</h2>
              <p className="text-zinc-400">
                Choose a media library from the sidebar to browse your files
              </p>
            </div>
          </div>
        ) : (
          <>
            <div className="mb-8">
              <nav className="flex items-center space-x-2 text-sm font-medium text-zinc-400 mb-4">
                <Link href="/folder-viewer" className="hover:text-white transition-colors">
                  Libraries
                </Link>
                <span>/</span>
                <span className="text-white font-semibold">{path.split('/').pop()}</span>
              </nav>
              <h1 className="text-3xl font-bold text-white tracking-tight">
                {path.split('/').pop()}
              </h1>
            </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) => (
                <div key={item.name} 
                     className="group relative bg-white dark:bg-slate-800 rounded-xl shadow-sm hover:shadow-lg transition-all duration-300 hover:-translate-y-1 overflow-hidden">
                  <Link href={item.isDirectory ? `/folder-viewer?path=${item.path}` : '#'} 
                        className="block">
                    <div className="aspect-square relative overflow-hidden">
                      {item.isDirectory ? (
                        <div className="absolute inset-0 bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-900/20 dark:to-indigo-900/20 flex items-center justify-center">
                          <div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center shadow-lg"
                               style={{ transform: 'perspective(100px) rotateY(-5deg) rotateX(5deg)' }}>
                            <Folder className="h-8 w-8 text-white" />
                          </div>
                        </div>
                      ) : isMediaFile(item) ? (
                        <div className="relative w-full h-full">
                          <img
                            src={item.thumbnail || '/placeholder.svg'}
                            alt={item.name}
                            className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                          />
                          <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 className="absolute bottom-2 left-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                            {item.type === 'video' ? (
                              <div className="bg-white/90 backdrop-blur-sm rounded-full p-2 shadow-lg">
                                <Film className="h-4 w-4 text-slate-800" />
                              </div>
                            ) : (
                              <div className="bg-white/90 backdrop-blur-sm rounded-full p-2 shadow-lg">
                                <Image className="h-4 w-4 text-slate-800" />
                              </div>
                            )}
                          </div>
                        </div>
                      ) : (
                        <div className="absolute inset-0 bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-700 dark:to-slate-800 flex items-center justify-center"
                             style={{ background: 'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)' }}>
                          <div className="w-16 h-16 bg-gradient-to-br from-slate-400 to-slate-600 rounded-2xl flex items-center justify-center shadow-lg"
                               style={{ transform: 'perspective(100px) rotateY(-5deg) rotateX(5deg)' }}>
                            {getFileIcon(item)}
                          </div>
                        </div>
                      )}
                    </div>
                    <div className="p-3">
                      <p className="text-sm font-semibold text-slate-900 dark:text-slate-100 truncate mb-1">{item.name}</p>
                      <p className="text-xs text-slate-600 dark:text-slate-400">{formatFileSize(item.size)}</p>
                    </div>
                  </Link>
                </div>
              ))}
            </div>
            
            {items.length === 0 && !loading && (
              <div className="text-center py-20">
                <div className="max-w-sm mx-auto">
                  <div className="w-16 h-16 bg-slate-100 dark:bg-slate-800 rounded-2xl flex items-center justify-center mx-auto mb-4">
                    <Folder className="h-8 w-8 text-slate-400" />
                  </div>
                  <h3 className="text-lg font-semibold text-slate-700 dark:text-slate-300 mb-2">Empty Directory</h3>
                  <p className="text-sm text-slate-500 dark:text-slate-400">No files or folders found in this location.</p>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

const FolderViewerPageWrapper = () => (
    <Suspense fallback={<div>Loading...</div>}>
        <FolderViewerPage />
    </Suspense>
)

export default FolderViewerPageWrapper;
