
"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import {
  ChevronLeft,
  ChevronRight,
  Home,
  Settings,
  Video,
  Image,
  Folder,
  Film,
  Image as ImageIcon,
  Play,
  FolderOpen,
} from "lucide-react";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { cn } from "@/lib/utils";
import { Suspense } from "react";

const SidebarContent = () => {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [libraries, setLibraries] = useState<{ id: number; path: string }[]>([]);
  const pathname = usePathname();
  const searchParams = useSearchParams();

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

  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 toggleSidebar = () => {
    setIsCollapsed(!isCollapsed);
  };

  const navItems = [
    { href: "/", label: "Home", icon: Home },
    { href: "/videos", label: "Videos", icon: Film },
    { href: "/photos", label: "Photos", icon: ImageIcon },
    { href: "/settings", label: "Settings", icon: Settings },
  ];

  return (
    <div
      className={cn(
        "flex flex-col bg-card border-r border-border transition-all duration-300 ease-in-out shadow-lg",
        isCollapsed ? "w-16" : "w-64"
      )}
    >
      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b border-border">
        {!isCollapsed && (
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-gradient-to-br from-primary to-primary/80 rounded-lg flex items-center justify-center shadow-lg">
              <Play className="h-4 w-4 text-primary-foreground" />
            </div>
            <h1 className="text-lg font-bold text-foreground tracking-tight">NextAV</h1>
          </div>
        )}
        <Button 
          onClick={toggleSidebar} 
          variant="ghost" 
          size="icon"
          className="h-8 w-8 text-muted-foreground hover:text-foreground hover:bg-muted rounded-lg transition-colors"
        >
          {isCollapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronLeft className="h-4 w-4" />}
        </Button>
      </div>

      {/* Navigation */}
      <nav className="flex-1 px-3 py-4 space-y-1">
        {navItems.map((item) => (
          <Link key={item.href} href={item.href} passHref>
            <Button
              variant="ghost"
              className={cn(
                "w-full justify-start h-10 text-muted-foreground hover:text-foreground hover:bg-muted/50 rounded-lg transition-all group",
                pathname === item.href && "bg-primary/10 text-primary border border-primary/20 shadow-sm"
              )}
            >
              <item.icon className={cn(
                "h-4 w-4 transition-colors",
                pathname === item.href ? "text-primary" : "text-muted-foreground group-hover:text-foreground"
              )} />
              {!isCollapsed && <span className="ml-3 font-medium text-sm">{item.label}</span>}
            </Button>
          </Link>
        ))}

        {/* Libraries Section */}
        {libraries.length > 0 && (
          <div className="pt-6">
            <div className={cn(
              "flex items-center gap-2 px-3 mb-3",
              isCollapsed && "justify-center"
            )}>
              <FolderOpen className="h-4 w-4 text-muted-foreground" />
              {!isCollapsed && (
                <h2 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                  Libraries
                </h2>
              )}
            </div>
            <div className="space-y-1">
              {libraries.map((lib) => (
                <Link
                  href={`/folder-viewer?path=${lib.path}`}
                  key={lib.id}
                  passHref
                >
                  <Button
                    variant="ghost"
                    className={cn(
                      "w-full justify-start h-9 text-muted-foreground hover:text-foreground hover:bg-muted/50 rounded-lg transition-all group text-sm",
                      pathname === "/folder-viewer" &&
                      searchParams.get("path") === lib.path &&
                      "bg-accent text-accent-foreground border border-accent/20"
                    )}
                  >
                    <Folder className="h-3.5 w-3.5 text-muted-foreground group-hover:text-foreground" />
                    {!isCollapsed && (
                      <span className="ml-3 truncate text-xs">
                        {lib.path.split('/').pop() || lib.path}
                      </span>
                    )}
                  </Button>
                </Link>
              ))}
            </div>
          </div>
        )}
      </nav>

      {/* Footer */}
      <div className="p-4 border-t border-border">
        <div className={cn(
          "text-center text-xs text-muted-foreground",
          isCollapsed && "text-[10px]"
        )}
        >
          {!isCollapsed ? "NextAV v1.0" : "v1.0"}
        </div>
      </div>
    </div>
  );
};

const Sidebar = () => {
  return (
    <Suspense fallback={<div className="w-16 bg-card border-r border-border" />}>
      <SidebarContent />
    </Suspense>
  );
};

export default Sidebar;
