"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import {
    LayoutDashboard,
    Users,
    CalendarCheck,
    CreditCard,
    Settings,
    LogOut,
    Brain,
} from "lucide-react";
import { UserButton, useUser } from "@clerk/nextjs";

interface Recommendation {
    id: string;
    status: string;
}

export function Sidebar() {
    const pathname = usePathname();
    const { user } = useUser();
    const [pendingCount, setPendingCount] = useState(0);

    useEffect(() => {
        const fetchPending = async () => {
            try {
                const res = await fetch("/api/recommendations");
                if (res.ok) {
                    const data = await res.json();
                    const pending = (data.recommendations || []).filter(
                        (r: Recommendation) => r.status === "pending"
                    );
                    setPendingCount(pending.length);
                }
            } catch (e) {
                console.error("Failed to fetch pending recommendations", e);
            }
        };
        fetchPending();
    }, []);

    const menuItems = [
        { icon: LayoutDashboard, label: "Dashboard", href: "/" },
        { icon: Users, label: "Users", href: "/users" },
        {
            icon: Brain,
            label: (
                <span className="flex items-center">
                    AI Recommendations
                    {pendingCount > 0 && (
                        <span className="ml-2 inline-block bg-red-600 text-xs rounded-full px-2 py-0.5">
                            {pendingCount}
                        </span>
                    )}
                </span>
            ),
            href: "/recommendations",
        },
        { icon: CalendarCheck, label: "Attendance", href: "/attendance" },
        { icon: CreditCard, label: "Payments", href: "/payments" },
        { icon: Settings, label: "Settings", href: "/settings" },
    ];

    return (
        <aside className="w-64 bg-gradient-to-b from-slate-900 via-slate-900 to-slate-950 text-white h-screen fixed left-0 top-0 flex flex-col border-r border-slate-800/50 shadow-2xl">
            {/* Logo Section */}
            <div className="p-6 border-b border-slate-800/50">
                <div className="flex items-center gap-3 justify-center">
                    <img 
                        src="/nextform-logo.png" 
                        alt="NextForm" 
                        className="h-16 w-16 object-contain"
                    />
                    <div>
                        <h1 className="text-lg font-black bg-gradient-to-r from-blue-400 via-cyan-400 to-blue-300 bg-clip-text text-transparent">
                            NextForm
                        </h1>
                    </div>
                </div>
            </div>

            {/* Navigation */}
            <nav className="flex-1 p-4 space-y-1 overflow-y-auto">
                {menuItems.map((item) => {
                    const Icon = item.icon;
                    const isActive = pathname === item.href;
                    const label = typeof item.label === "string" ? item.label : item.label;
                    return (
                        <Link
                            key={item.href}
                            href={item.href}
                            className={`flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 group relative overflow-hidden ${isActive
                                ? "bg-gradient-to-r from-blue-600 to-cyan-600 text-white shadow-lg shadow-blue-900/30"
                                : "text-slate-400 hover:bg-slate-800/40 hover:text-white"}`}
                        >
                            {isActive && <div className="absolute inset-0 bg-white/10 blur-xl"></div>}
                            <Icon size={20} className={`${isActive ? "text-white" : "text-slate-500 group-hover:text-white"} relative z-10`} />
                            <span className="font-semibold relative z-10">{label}</span>
                        </Link>
                    );
                })}
            </nav>

            {/* User Section */}
            <div className="p-4 border-t border-slate-800/50 bg-slate-800/20">
                <div className="flex items-center gap-3 px-3 py-3 rounded-xl bg-slate-800/50 hover:bg-slate-800/70 transition-colors">
                    <div className="h-10 w-10 rounded-full bg-gradient-to-br from-blue-500 to-cyan-500 flex-shrink-0 overflow-hidden">
                        <UserButton afterSignOutUrl="/" />
                    </div>
                    <div className="flex-1 min-w-0">
                        <p className="text-sm font-semibold text-white truncate">
                            {user?.fullName || "Admin"}
                        </p>
                        <p className="text-xs text-slate-400 truncate">
                            {user?.emailAddresses[0]?.emailAddress || "admin@fitai.com"}
                        </p>
                    </div>
                </div>
            </div>
        </aside>
    );
}
