
"use client";

import { useState, useEffect, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Folder, File, Image, Film, Play, ChevronLeft, Home, Star } from "lucide-react";
import { StarRating } from "@/components/star-rating";
import Link from "next/link";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import PhotoViewer from "@/components/photo-viewer";
import VideoViewer from "@/components/video-viewer";
import { Button } from "@/components/ui/button";

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

interface BreadcrumbItem {
  name: string;
  path: string;
}

const FolderViewerPage = () => {
  const searchParams = useSearchParams();
  const router = useRouter();
  const path = searchParams.get("path");
  const [items, setItems] = useState<FileSystemItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedVideo, setSelectedVideo] = useState<FileSystemItem | null>(null);
  const [isPlayerOpen, setIsPlayerOpen] = useState(false);
  const [isVideoLoading, setIsVideoLoading] = useState(false);
  const [selectedPhoto, setSelectedPhoto] = useState<FileSystemItem | null>(null);
  const [isPhotoViewerOpen, setIsPhotoViewerOpen] = useState(false);
  const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);
  const [libraries, setLibraries] = useState<{id: number, path: string}[]>([]);
  const [error, setError] = useState<string>('');

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

  const fetchLibraries = async () => {
    try {
      const res = await fetch('/api/libraries');
      const data = await res.json();
      setLibraries(data);
    } catch (error) {
      console.error('Error fetching libraries:', error);
    }
  };

  const fetchItems = async (currentPath: string) => {
    setLoading(true);
    setError('');
    try {
      const res = await fetch(`/api/files?path=${encodeURIComponent(currentPath)}`);
      const data = await res.json();
      
      if (!Array.isArray(data)) {
        console.error('Invalid response format:', data);
        setItems([]);
        setError('Invalid response from server');
      } else {
        setItems(data);
      }
    } catch (error) {
      console.error('Error fetching items:', error);
      setItems([]);
      setError('Failed to load directory contents');
    } 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 formatFilePath = (path: string) => {
    if (!path) return '';
    
    // Split path into directory and filename
    const lastSlashIndex = path.lastIndexOf('/');
    const lastBackslashIndex = path.lastIndexOf('\\');
    const lastSeparatorIndex = Math.max(lastSlashIndex, lastBackslashIndex);
    
    if (lastSeparatorIndex === -1) {
      // No directory separator found, return as is
      return path;
    }
    
    const directory = path.substring(0, lastSeparatorIndex);
    const filename = path.substring(lastSeparatorIndex + 1);
    
    // If the full path is short enough, show it all
    if (path.length <= 80) {
      return path;
    }
    
    // If directory is short enough, show directory + truncated filename
    if (directory.length <= 50) {
      const maxFilenameLength = 80 - directory.length - 1; // -1 for "/"
      if (filename.length <= maxFilenameLength) {
        return `${directory}/${filename}`;
      } else {
        return `${directory}/${filename.substring(0, maxFilenameLength - 3)}...`;
      }
    }
    
    // For longer paths, show more of the directory structure
    const maxDirLength = 45;
    const startLength = Math.floor(maxDirLength / 2);
    const endLength = maxDirLength - startLength - 3; // -3 for "..."
    
    const truncatedDir = directory.length > maxDirLength 
      ? `${directory.substring(0, startLength)}...${directory.substring(directory.length - endLength)}`
      : directory;
    
    // Add filename if there's space
    const remainingSpace = 80 - truncatedDir.length - 1; // -1 for "/"
    if (remainingSpace > 3) {
      return `${truncatedDir}/${filename.length > remainingSpace ? filename.substring(0, remainingSpace - 3) + '...' : filename}`;
    }
    
    return `${truncatedDir}/...`;
  };

  const formatTitle = (title: string) => {
    if (!title) return '';
    
    // If title is short enough, return as is
    if (title.length <= 40) {
      return title;
    }
    
    // For longer titles, truncate to prevent awkward third-line display
    return title.length > 60 ? title.substring(0, 60) + '...' : title;
  };

  const getLibraryRoot = (currentPath: string): string | null => {
    if (!currentPath || libraries.length === 0) return null;
    
    // Find the library root that matches the current path
    for (const library of libraries) {
      if (currentPath.startsWith(library.path)) {
        return library.path;
      }
    }
    return null;
  };

  const getBreadcrumbs = (currentPath: string): BreadcrumbItem[] => {
    if (!currentPath) return [];
    
    const libraryRoot = getLibraryRoot(currentPath);
    if (!libraryRoot) return [{ name: 'Unknown', path: currentPath }];
    
    // Get the relative path from library root
    const relativePath = currentPath.substring(libraryRoot.length);
    const pathParts = relativePath.split('/').filter(part => part.length > 0);
    
    const breadcrumbs: BreadcrumbItem[] = [];
    
    // Use library name as root
    const libraryName = libraryRoot.split('/').pop() || libraryRoot;
    breadcrumbs.push({ name: libraryName, path: libraryRoot });
    
    // Build breadcrumbs for each path level within the library
    let accumulatedPath = libraryRoot;
    pathParts.forEach((part, index) => {
      accumulatedPath += '/' + part;
      breadcrumbs.push({
        name: part,
        path: accumulatedPath
      });
    });
    
    return breadcrumbs;
  };

  const getParentPath = (currentPath: string): string => {
    if (!currentPath) return '';
    
    const libraryRoot = getLibraryRoot(currentPath);
    if (!libraryRoot) return '';
    
    // Don't allow navigation above library root
    if (currentPath === libraryRoot) return '';
    
    // Split path but keep leading slash for absolute paths
    const pathParts = currentPath.split('/');
    const libraryParts = libraryRoot.split('/').filter(part => part.length > 0);
    
    // Filter out empty parts but keep structure
    const filteredPathParts = pathParts.filter(part => part.length > 0);
    
    if (filteredPathParts.length <= libraryParts.length) return '';
    
    // Reconstruct absolute path
    const parentParts = filteredPathParts.slice(0, -1);
    return '/' + parentParts.join('/');
  };

  const handleBackClick = () => {
    const parentPath = getParentPath(path || '');
    if (parentPath) {
      router.push(`/folder-viewer?path=${parentPath}`);
    } else {
      router.push('/folder-viewer');
    }
  };

  const handleBreadcrumbClick = (breadcrumbPath: string) => {
    if (breadcrumbPath === '') {
      router.push('/folder-viewer');
    } else {
      router.push(`/folder-viewer?path=${breadcrumbPath}`);
    }
  };

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

  const handleVideoClick = (item: FileSystemItem) => {
    if (item.type === 'video' && item.id) {
      setIsVideoLoading(true);
      setSelectedVideo(item);
      setIsPlayerOpen(true);
      // Reset loading state after a short delay to allow player to initialize
      setTimeout(() => setIsVideoLoading(false), 500);
    }
  };

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

  const handlePhotoClick = (item: FileSystemItem, index: number) => {
    if (item.type === 'photo' && item.id) {
      setSelectedPhoto(item);
      setCurrentPhotoIndex(index);
      setIsPhotoViewerOpen(true);
    }
  };

  const handleClosePhotoViewer = () => {
    setIsPhotoViewerOpen(false);
    setSelectedPhoto(null);
  };

  const handleNextPhoto = () => {
    const photoItems = items.filter(item => item.type === 'photo' && item.id);
    if (photoItems.length > 0) {
      const nextIndex = (currentPhotoIndex + 1) % photoItems.length;
      setCurrentPhotoIndex(nextIndex);
      setSelectedPhoto(photoItems[nextIndex]);
    }
  };

  const handlePrevPhoto = () => {
    const photoItems = items.filter(item => item.type === 'photo' && item.id);
    if (photoItems.length > 0) {
      const prevIndex = (currentPhotoIndex - 1 + photoItems.length) % photoItems.length;
      setCurrentPhotoIndex(prevIndex);
      setSelectedPhoto(photoItems[prevIndex]);
    }
  };

  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">
              {/* Back Button */}
              <div className="flex items-center gap-4 mb-4">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleBackClick}
                  className="text-zinc-400 hover:text-white hover:bg-zinc-800/50 transition-colors"
                  disabled={!getParentPath(path || '')}
                  title={getParentPath(path || '') ? 'Go to parent directory' : 'Already at library root'}
                >
                  <ChevronLeft className="h-4 w-4 mr-2" />
                  Back
                </Button>
              </div>

              {/* Breadcrumb Navigation */}
              <nav className="flex items-center flex-wrap gap-2 text-sm font-medium text-zinc-400 mb-4">
                {getBreadcrumbs(path || '').map((breadcrumb, index) => (
                  <div key={breadcrumb.path} className="flex items-center gap-2">
                    {index > 0 && <span className="text-zinc-600">/</span>}
                    <button
                      onClick={() => handleBreadcrumbClick(breadcrumb.path)}
                      className={`hover:text-white transition-colors ${
                        index === getBreadcrumbs(path || '').length - 1 
                          ? 'text-white font-semibold cursor-default' 
                          : 'hover:underline cursor-pointer'
                      }`}
                      disabled={index === getBreadcrumbs(path || '').length - 1}
                      title={breadcrumb.path}
                    >
                      {index === 0 ? (
                        <div className="flex items-center gap-1">
                          <Home className="h-3 w-3" />
                          <span>{breadcrumb.name}</span>
                        </div>
                      ) : (
                        breadcrumb.name
                      )}
                    </button>
                  </div>
                ))}
              </nav>

              {/* Current Directory Title */}
              <h1 className="text-3xl font-bold text-white tracking-tight">
                {path ? path.split('/').pop() : 'Libraries'}
              </h1>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
              {error && (
                <div className="col-span-full text-center py-12">
                  <div className="max-w-sm mx-auto">
                    <div className="w-16 h-16 bg-red-900/20 rounded-2xl flex items-center justify-center mx-auto mb-4">
                      <Folder className="h-8 w-8 text-red-500" />
                    </div>
                    <h3 className="text-lg font-semibold text-red-400 mb-2">Error Loading Directory</h3>
                    <p className="text-sm text-red-500 mb-4">{error}</p>
                    <Button
                      onClick={() => path && fetchItems(path)}
                      variant="outline"
                      size="sm"
                      className="border-red-500 text-red-500 hover:bg-red-500/10"
                    >
                      Try Again
                    </Button>
                  </div>
                </div>
              )}
              
              {!error && Array.isArray(items) && 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 min-h-[240px] ${(item.type === 'video' || item.type === 'photo') ? 'cursor-pointer' : ''}`}>
                  <Link href={item.isDirectory ? `/folder-viewer?path=${item.path}` : '#'} 
                        className="block h-full flex flex-col"
                        onClick={(e) => {
                          if (item.type === 'video' && item.id) {
                            e.preventDefault();
                            handleVideoClick(item);
                          } else if (item.type === 'photo' && item.id) {
                            e.preventDefault();
                            const photoIndex = items.filter(i => i.type === 'photo' && i.id).findIndex(i => i.id === item.id);
                            handlePhotoClick(item, photoIndex);
                          }
                        }}>
                    <div className="aspect-[4/3] 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 overflow-hidden aspect-[4/3] bg-black rounded-t-xl">
                          <img
                            src={item.thumbnail || (item.type === 'video' ? '/placeholder-video.svg' : '/placeholder-photo.svg')}
                            alt={item.name}
                            className="w-full h-full object-contain transition-transform duration-300 group-hover:scale-105"
                          />
                          {item.type === 'video' && (
                            <>
                              <div className="absolute top-2 right-2 bg-black/60 text-white rounded-full p-1">
                                <Play className="h-3 w-3" />
                              </div>
                              {isVideoLoading && selectedVideo?.id === item.id && (
                                <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
                                  <div className="animate-spin rounded-full h-6 w-6 border-2 border-white border-t-transparent"></div>
                                </div>
                              )}
                            </>
                          )}
                          {item.type === 'photo' && (
                            <div className="absolute top-2 right-2 bg-black/60 text-white rounded-full p-1">
                              <Image className="h-3 w-3" />
                            </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-2.5 flex flex-col flex-1 bg-slate-50 dark:bg-slate-800/50 border-t border-slate-200 dark:border-slate-700">
                      <p className="text-sm font-semibold text-slate-900 dark:text-slate-100 line-clamp-2 leading-tight mb-1 min-h-[2rem]" title={item.name}>{formatTitle(item.name)}</p>
                      
                      <div className="flex items-center justify-between text-xs mb-1">
                        <span className="text-slate-600 dark:text-slate-400">{formatFileSize(item.size)}</span>
                        {isMediaFile(item) && (item.avg_rating || 0) > 0 && (
                          <StarRating 
                            rating={item.avg_rating || 0}
                            count={item.star_count || 0}
                            size="xs"
                            showCount={false}
                          />
                        )}
                      </div>
                      
                      <p 
                        className="text-xs text-slate-500 dark:text-slate-400 line-clamp-2 leading-tight cursor-help flex-1"
                        title={item.path}
                      >
                        {formatFilePath(item.path)}
                      </p>
                    </div>
                  </Link>
                </div>
              ))}
            </div>
            
            {items.length === 0 && !loading && !error && (
              <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>

      {/* Photo Viewer */}
      <PhotoViewer
        photo={selectedPhoto!}
        isOpen={isPhotoViewerOpen}
        onClose={handleClosePhotoViewer}
        onNext={handleNextPhoto}
        onPrev={handlePrevPhoto}
        showNavigation={items.filter(item => item.type === 'photo' && item.id).length > 1}
        showBookmarks={false}
        showRatings={false}
        formatFileSize={formatFileSize}
      />

      {/* Video Viewer */}
      <VideoViewer
        video={selectedVideo!}
        isOpen={isPlayerOpen}
        onClose={handleClosePlayer}
        showBookmarks={false}
        showRatings={false}
        formatFileSize={formatFileSize}
      />
    </div>
  );
};

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

export default FolderViewerPageWrapper;
