'use client'

import { useState } from 'react'
import Link from 'next/link'
import { usePathname, useSearchParams } from 'next/navigation'
import { cn } from '@/lib/utils'
import { StickyNote, Bell, Archive, Trash2, Tag, Settings, User, Shield, LogOut, Heart, Clock, Sparkles, X } from 'lucide-react'
import { useLabels } from '@/context/LabelContext'
import { NotebooksList } from './notebooks-list'
import { useSession, signOut } from 'next-auth/react'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { useRouter } from 'next/navigation'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { useLanguage } from '@/lib/i18n'
import { LABEL_COLORS } from '@/lib/types'

export function Sidebar({ className, user }: { className?: string, user?: any }) {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const router = useRouter()
  const { labels, getLabelColor } = useLabels()
  const [isLabelsExpanded, setIsLabelsExpanded] = useState(false)
  const { data: session } = useSession()
  const { t } = useLanguage()

  const currentUser = user || session?.user

  const currentLabels = searchParams.get('labels')?.split(',').filter(Boolean) || []
  const currentSearch = searchParams.get('search')
  const currentNotebookId = searchParams.get('notebook')

  // Show first 5 labels by default, or all if expanded
  const displayedLabels = isLabelsExpanded ? labels : labels.slice(0, 5)
  const hasMoreLabels = labels.length > 5

  const userRole = (currentUser as any)?.role || 'USER'
  const userInitials = currentUser?.name
    ? currentUser.name.split(' ').map((n: string) => n[0]).join('').toUpperCase().substring(0, 2)
    : 'U'

  const NavItem = ({ href, icon: Icon, label, active, onClick, iconColorClass, count }: any) => (
    <Link
      href={href}
      onClick={onClick}
      className={cn(
        "flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200",
        active
          ? "bg-[#EFB162] text-amber-900 shadow-lg shadow-amber-500/20"
          : "text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:translate-x-1"
      )}
    >
      <Icon className={cn("h-5 w-5", active && "text-amber-900", !active && "group-hover:text-amber-600 dark:group-hover:text-amber-400 transition-colors", !active && iconColorClass)} />
      <span className={cn("text-sm font-medium", active && "font-semibold")}>{label}</span>
      {count && (
        <span className="ml-auto text-[10px] font-medium bg-amber-900/20 px-1.5 py-0.5 rounded text-amber-900">
          {count}
        </span>
      )}
    </Link>
  )

  return (
    <aside className={cn(
      "w-72 bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl border-r border-white/20 dark:border-slate-700/50 flex-shrink-0 hidden lg:flex flex-col h-full z-20 shadow-[4px_0_24px_-12px_rgba(0,0,0,0.1)] relative transition-all duration-300",
      className
    )}>
      {/* Logo Section */}
      <div className="h-20 flex items-center px-6">
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-yellow-400 to-amber-500 flex items-center justify-center text-white shadow-lg shadow-yellow-500/30 transform hover:rotate-6 transition-transform duration-300">
            <StickyNote className="h-5 w-5" />
          </div>
          <div className="flex flex-col">
            <span className="text-lg font-bold tracking-tight text-slate-900 dark:text-white leading-none">Memento</span>
            <span className="text-[10px] font-medium text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-1">{t('nav.workspace')}</span>
          </div>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto px-4 py-2 space-y-8 scroll-smooth">
        {/* Quick Access Section */}
        <div>
          <p className="px-2 text-[11px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-3">{t('nav.quickAccess')}</p>
          <div className="grid grid-cols-2 gap-3">
            {/* Favorites - Coming Soon */}
            <button className="flex flex-col items-start p-3 rounded-2xl bg-white dark:bg-slate-800 shadow-sm hover:shadow-md border border-slate-100 dark:border-slate-700/50 group transition-all duration-200 hover:-translate-y-1 opacity-60 cursor-not-allowed">
              <div className="w-8 h-8 rounded-lg bg-rose-50 dark:bg-rose-900/20 text-rose-500 flex items-center justify-center mb-2">
                <Heart className="h-4 w-4" />
              </div>
              <span className="text-xs font-semibold text-slate-600 dark:text-slate-300">{t('nav.favorites') || 'Favorites'}</span>
            </button>

            {/* Recent - Coming Soon */}
            <button className="flex flex-col items-start p-3 rounded-2xl bg-white dark:bg-slate-800 shadow-sm hover:shadow-md border border-slate-100 dark:border-slate-700/50 group transition-all duration-200 hover:-translate-y-1 opacity-60 cursor-not-allowed">
              <div className="w-8 h-8 rounded-lg bg-amber-50 dark:bg-amber-900/20 text-amber-500 flex items-center justify-center mb-2">
                <Clock className="h-4 w-4" />
              </div>
              <span className="text-xs font-semibold text-slate-600 dark:text-slate-300">{t('nav.recent') || 'Recent'}</span>
            </button>
          </div>
        </div>

        {/* My Library Section */}
        <nav className="space-y-1">
          <p className="px-2 text-[11px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-2">{t('nav.myLibrary') || 'My Library'}</p>
          <NavItem
            href="/"
            icon={StickyNote}
            label={t('nav.notes')}
            active={pathname === '/' && currentLabels.length === 0 && !currentSearch && !currentNotebookId}
          />
          <NavItem
            href="/reminders"
            icon={Bell}
            label={t('nav.reminders')}
            active={pathname === '/reminders'}
          />
          <NavItem
            href="/archive"
            icon={Archive}
            label={t('nav.archive')}
            active={pathname === '/archive'}
          />
          <NavItem
            href="/trash"
            icon={Trash2}
            label={t('nav.trash')}
            active={pathname === '/trash'}
          />
        </nav>

        {/* Notebooks Section */}
        <NotebooksList />

        {/* Labels Section - Contextual per notebook */}
        {currentNotebookId && (
          <nav className="space-y-1">
            <p className="px-2 text-[11px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-2">{t('labels.title')}</p>
            {displayedLabels.map(label => {
              const colorName = getLabelColor(label.name)
              const colorClass = LABEL_COLORS[colorName]?.icon

              return (
                <NavItem
                  key={label.id}
                  href={`/?labels=${encodeURIComponent(label.name)}&notebook=${encodeURIComponent(currentNotebookId)}`}
                  icon={Tag}
                  label={label.name}
                  active={currentLabels.includes(label.name)}
                  iconColorClass={colorClass}
                />
              )
            })}
            {hasMoreLabels && (
              <button
                onClick={() => setIsLabelsExpanded(!isLabelsExpanded)}
                className="flex items-center gap-3 px-3 py-2.5 text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 rounded-xl transition-all duration-200 hover:translate-x-1 w-full"
              >
                <Tag className="h-5 w-5" />
                <span className="text-sm font-medium">
                  {isLabelsExpanded ? t('labels.showLess') : t('labels.showMore')}
                </span>
              </button>
            )}
          </nav>
        )}
      </div>

      {/* User Profile Section */}
      <div className="p-4 mt-auto bg-white/50 dark:bg-slate-800/30 backdrop-blur-sm border-t border-slate-200 dark:border-slate-800">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <button className="flex items-center gap-3 p-2 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800 cursor-pointer transition-colors group w-full">
              <div className="relative">
                <Avatar className="h-9 w-9">
                  <AvatarImage src={currentUser?.image || ''} alt={currentUser?.name || ''} />
                  <AvatarFallback className="bg-gradient-to-tr from-amber-400 to-orange-500 text-white text-xs font-bold shadow-sm">
                    {userInitials}
                  </AvatarFallback>
                </Avatar>
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-bold text-slate-800 dark:text-white truncate">{currentUser?.name}</p>
                <p className="text-[10px] text-slate-500 truncate">{t('nav.proPlan') || 'Pro Plan'}</p>
              </div>
              <Settings className="text-slate-400 group-hover:text-indigo-600 transition-colors h-5 w-5" />
            </button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="start" className="w-56" forceMount>
            <DropdownMenuLabel className="font-normal">
              <div className="flex flex-col space-y-1">
                <p className="text-sm font-medium leading-none">{currentUser?.name}</p>
                <p className="text-xs leading-none text-muted-foreground">
                  {currentUser?.email}
                </p>
              </div>
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuGroup>
              <DropdownMenuItem onClick={() => router.push('/settings/profile')}>
                <User className="mr-2 h-4 w-4" />
                <span>{t('nav.profile')}</span>
              </DropdownMenuItem>
              {userRole === 'ADMIN' && (
                <DropdownMenuItem onClick={() => router.push('/admin')}>
                  <Shield className="mr-2 h-4 w-4" />
                  <span>{t('nav.adminDashboard')}</span>
                </DropdownMenuItem>
              )}
              <DropdownMenuItem onClick={() => router.push('/settings')}>
                <Settings className="mr-2 h-4 w-4" />
                <span>{t('nav.diagnostics')}</span>
              </DropdownMenuItem>
            </DropdownMenuGroup>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={() => signOut({ callbackUrl: '/login' })}>
              <LogOut className="mr-2 h-4 w-4" />
              <span>{t('nav.logout')}</span>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </aside>
  )
}
