'use client'

import Link from 'next/link'
import Image from 'next/image'
import { usePathname } from 'next/navigation'
import { useStore } from '@/lib/store'
import { 
  LayoutDashboard, 
  Eye, 
  Gavel,
  TrendingUp, 
  Settings,
  ChevronLeft,
  ChevronRight,
  LogOut,
  Crown,
  Zap,
  Shield,
  CreditCard,
  Menu,
  X,
  Sparkles,
  Tag,
} from 'lucide-react'
import { useState, useEffect } from 'react'
import clsx from 'clsx'

interface SidebarProps {
  collapsed?: boolean
  onCollapsedChange?: (collapsed: boolean) => void
}

export function Sidebar({ collapsed: controlledCollapsed, onCollapsedChange }: SidebarProps) {
  const pathname = usePathname()
  const { user, logout, subscription, domains } = useStore()
  
  // Internal state for uncontrolled mode
  const [internalCollapsed, setInternalCollapsed] = useState(false)
  const [mobileOpen, setMobileOpen] = useState(false)
  
  // Use controlled or uncontrolled state
  const collapsed = controlledCollapsed ?? internalCollapsed
  const setCollapsed = onCollapsedChange ?? setInternalCollapsed
  
  // Load collapsed state from localStorage
  useEffect(() => {
    const saved = localStorage.getItem('sidebar-collapsed')
    if (saved) {
      setCollapsed(saved === 'true')
    }
  }, [])

  // Close mobile menu on route change
  useEffect(() => {
    setMobileOpen(false)
  }, [pathname])
  
  // Save collapsed state
  const toggleCollapsed = () => {
    const newState = !collapsed
    setCollapsed(newState)
    localStorage.setItem('sidebar-collapsed', String(newState))
  }

  const tierName = subscription?.tier_name || subscription?.tier || 'Scout'
  const TierIcon = tierName === 'Tycoon' ? Crown : tierName === 'Trader' ? TrendingUp : Zap

  // Count available domains for notification badge
  const availableCount = domains?.filter(d => d.is_available).length || 0
  const isTycoon = tierName.toLowerCase() === 'tycoon'

  // SECTION 1: Discover - External market data
  const discoverItems = [
    { 
      href: '/terminal/market', 
      label: 'MARKET', 
      icon: Gavel,
      badge: null,
    },
    { 
      href: '/terminal/intel', 
      label: 'INTEL', 
      icon: TrendingUp,
      badge: null,
    },
  ]

  // SECTION 2: Manage - Your own assets and tools
  const manageItems: Array<{
    href: string
    label: string
    icon: any
    badge: number | null
    tycoonOnly?: boolean
  }> = [
    { 
      href: '/terminal/radar', 
      label: 'RADAR', 
      icon: LayoutDashboard,
      badge: null,
    },
    { 
      href: '/terminal/watchlist', 
      label: 'WATCHLIST', 
      icon: Eye,
      badge: availableCount || null,
    },
    { 
      href: '/terminal/listing', 
      label: 'LISTING', 
      icon: Tag,
      badge: null,
    },
  ]

  const bottomItems = [
    { href: '/terminal/settings', label: 'Settings', icon: Settings },
  ]

  const isActive = (href: string) => {
    if (href === '/terminal/radar') return pathname === '/terminal/radar' || pathname === '/terminal' || pathname === '/terminal/dashboard'
    return pathname.startsWith(href)
  }

  const SidebarContent = () => (
    <>
      {/* Logo Section */}
      <div className={clsx(
        "relative h-20 flex items-center border-b border-white/5",
        collapsed ? "justify-center px-2" : "px-4"
      )}>
        <Link href="/" className="flex items-center gap-3 group">
          <div className={clsx(
            "relative flex items-center justify-center transition-all duration-300",
            collapsed ? "w-10 h-10" : "w-12 h-12"
          )}>
            {/* Glow effect behind logo - Reduced intensity for cleanliness */}
            <div className="absolute inset-0 bg-emerald-500/10 blur-xl rounded-full scale-150 opacity-30 group-hover:opacity-60 transition-opacity" />
            <Image
              src="/pounce-puma.png"
              alt="pounce"
              width={48}
              height={48}
              className={clsx(
                "relative object-contain transition-all",
                collapsed ? "w-8 h-8" : "w-10 h-10"
              )}
            />
          </div>
          {!collapsed && (
            <div className="flex flex-col">
              <span 
                className="text-lg font-bold tracking-[0.12em] text-white group-hover:text-emerald-400 transition-colors"
                style={{ fontFamily: 'var(--font-display), Georgia, serif' }}
              >
                POUNCE
              </span>
              <span className="text-[10px] text-zinc-500 tracking-wider uppercase">
                Terminal
              </span>
            </div>
          )}
        </Link>
      </div>

      {/* Main Navigation */}
      <nav className="flex-1 py-6 px-3 overflow-y-auto scrollbar-hide">
        {/* SECTION 1: Discover */}
        <div className={clsx("mb-6", collapsed ? "px-1" : "px-2")}>
          {!collapsed && (
            <p className="text-[10px] font-bold text-zinc-600 uppercase tracking-widest mb-3 pl-2">
              Discover
            </p>
          )}
          {collapsed && <div className="h-px bg-white/5 mb-3 w-4 mx-auto" />}
          
          <div className="space-y-1">
            {discoverItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                onClick={() => setMobileOpen(false)}
                className={clsx(
                  "group relative flex items-center gap-3 px-3 py-2.5 rounded-lg transition-all duration-200",
                  isActive(item.href)
                    ? "text-emerald-400 bg-emerald-500/[0.08]"
                    : "text-zinc-400 hover:text-zinc-200 hover:bg-white/[0.03]"
                )}
                title={collapsed ? item.label : undefined}
              >
                {isActive(item.href) && (
                  <div className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-emerald-500 rounded-full shadow-[0_0_8px_rgba(16,185,129,0.5)]" />
                )}
                <item.icon className={clsx(
                  "w-4 h-4 transition-all duration-300",
                  isActive(item.href) 
                    ? "text-emerald-400" 
                    : "group-hover:text-zinc-200"
                )} />
                {!collapsed && (
                  <span className={clsx(
                    "text-xs font-semibold tracking-wide transition-colors",
                    isActive(item.href) ? "text-emerald-400" : "text-zinc-400 group-hover:text-zinc-200"
                  )}>
                    {item.label}
                  </span>
                )}
              </Link>
            ))}
          </div>
        </div>

        {/* SECTION 2: Manage */}
        <div className={clsx("", collapsed ? "px-1" : "px-2")}>
          {!collapsed && (
            <p className="text-[10px] font-bold text-zinc-600 uppercase tracking-widest mb-3 pl-2">
              Manage
            </p>
          )}
          {collapsed && <div className="h-px bg-white/5 mb-3 w-4 mx-auto" />}
          
          <div className="space-y-1">
            {manageItems.map((item) => {
              const isDisabled = item.tycoonOnly && !isTycoon
              const ItemWrapper = (isDisabled ? 'div' : Link) as any
              
              return (
                <ItemWrapper
                  key={item.href}
                  {...(!isDisabled && { href: item.href })}
                  onClick={() => !isDisabled && setMobileOpen(false)}
                  className={clsx(
                    "group relative flex items-center gap-3 px-3 py-2.5 rounded-lg transition-all duration-200",
                    isDisabled
                      ? "opacity-50 cursor-not-allowed"
                      : isActive(item.href)
                        ? "text-emerald-400 bg-emerald-500/[0.08]"
                        : "text-zinc-400 hover:text-zinc-200 hover:bg-white/[0.03]"
                  )}
                  title={isDisabled ? "Upgrade to Tycoon to unlock" : collapsed ? item.label : undefined}
                >
                  {!isDisabled && isActive(item.href) && (
                    <div className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-emerald-500 rounded-full shadow-[0_0_8px_rgba(16,185,129,0.5)]" />
                  )}
                  <div className="relative">
                    <item.icon className={clsx(
                      "w-4 h-4 transition-all duration-300",
                      isDisabled ? "text-zinc-600" : isActive(item.href) ? "text-emerald-400" : "group-hover:text-zinc-200"
                    )} />
                    {item.badge && typeof item.badge === 'number' && !isDisabled && (
                      <span className="absolute -top-1.5 -right-1.5 w-3.5 h-3.5 bg-emerald-500 text-black 
                                       text-[9px] font-bold rounded-full flex items-center justify-center
                                       shadow-[0_0_8px_rgba(16,185,129,0.4)]">
                        {item.badge > 9 ? '•' : item.badge}
                      </span>
                    )}
                  </div>
                  {!collapsed && (
                    <span className={clsx(
                      "text-xs font-semibold tracking-wide transition-colors flex-1",
                      isDisabled ? "text-zinc-600" : isActive(item.href) ? "text-emerald-400" : "text-zinc-400 group-hover:text-zinc-200"
                    )}>
                      {item.label}
                    </span>
                  )}
                  {isDisabled && !collapsed && <Crown className="w-3 h-3 text-amber-500/40" />}
                </ItemWrapper>
              )
            })}
          </div>
        </div>
      </nav>

      {/* Bottom Section */}
      <div className="border-t border-white/5 py-4 px-3 space-y-1">
        {/* Admin Link */}
        {user?.is_admin && (
          <Link
            href="/admin"
            onClick={() => setMobileOpen(false)}
            className="group flex items-center gap-3 px-3 py-2.5 rounded-lg text-amber-500/80 hover:text-amber-400 hover:bg-amber-500/10 transition-all"
            title={collapsed ? "Admin Panel" : undefined}
          >
            <Shield className="w-4 h-4" />
            {!collapsed && <span className="text-xs font-semibold tracking-wide">Admin</span>}
          </Link>
        )}
        
        {/* Settings */}
        {bottomItems.map((item) => (
          <Link
            key={item.href}
            href={item.href}
            onClick={() => setMobileOpen(false)}
            className={clsx(
              "group flex items-center gap-3 px-3 py-2.5 rounded-lg transition-all",
              isActive(item.href)
                ? "text-emerald-400 bg-emerald-500/[0.08]"
                : "text-zinc-400 hover:text-zinc-200 hover:bg-white/[0.03]"
            )}
            title={collapsed ? item.label : undefined}
          >
            <item.icon className="w-4 h-4" />
            {!collapsed && <span className="text-xs font-semibold tracking-wide">{item.label}</span>}
          </Link>
        ))}

        {/* User Card */}
        <div className={clsx(
          "mt-4 border border-white/5 rounded-xl bg-zinc-900/50",
          collapsed ? "p-2 bg-transparent border-none" : "p-3"
        )}>
          {collapsed ? (
            <div className="flex justify-center">
              <div className="w-8 h-8 rounded-lg bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center">
                <TierIcon className="w-4 h-4 text-emerald-400" />
              </div>
            </div>
          ) : (
            <>
              <div className="flex items-center gap-3 mb-3">
                <div className="w-9 h-9 rounded-lg bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center flex-shrink-0">
                  <TierIcon className="w-4 h-4 text-emerald-400" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-xs font-bold text-white truncate">
                    {user?.name || user?.email?.split('@')[0]}
                  </p>
                  <div className="flex items-center gap-1.5">
                    <span className={clsx(
                      "text-[10px] uppercase tracking-wider font-bold",
                      tierName === 'Tycoon' ? "text-amber-400" : 
                      tierName === 'Trader' ? "text-emerald-400" : 
                      "text-zinc-500"
                    )}>
                      {tierName}
                    </span>
                    {tierName === 'Tycoon' && <Sparkles className="w-2.5 h-2.5 text-amber-400" />}
                  </div>
                </div>
              </div>
              
              {/* Usage bar */}
              <div className="space-y-1.5">
                <div className="flex items-center justify-between text-[10px] font-medium text-zinc-500">
                  <span>Usage</span>
                  <span>{subscription?.domains_used || 0}/{subscription?.domain_limit || 5}</span>
                </div>
                <div className="h-1 bg-zinc-800 rounded-full overflow-hidden">
                  <div 
                    className="h-full bg-emerald-500 rounded-full transition-all duration-500"
                    style={{ 
                      width: `${Math.min(((subscription?.domains_used || 0) / (subscription?.domain_limit || 5)) * 100, 100)}%` 
                    }}
                  />
                </div>
              </div>
              
              {tierName === 'Scout' && (
                <Link 
                  href="/pricing" 
                  className="mt-3 flex items-center justify-center gap-2 w-full py-2 
                             bg-emerald-500 text-black text-[10px] font-bold uppercase tracking-wider rounded-lg
                             hover:bg-emerald-400 transition-colors"
                >
                  <CreditCard className="w-3 h-3" />
                  Upgrade
                </Link>
              )}
            </>
          )}
        </div>

        {/* Logout */}
        <button
          onClick={() => {
            logout()
            setMobileOpen(false)
          }}
          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-zinc-500 hover:text-red-400 hover:bg-red-500/10 transition-all"
          title={collapsed ? "Sign out" : undefined}
        >
          <LogOut className="w-4 h-4" />
          {!collapsed && <span className="text-xs font-semibold tracking-wide">Sign out</span>}
        </button>
      </div>

      {/* Collapse Toggle - Desktop only */}
      <button
        onClick={toggleCollapsed}
        className={clsx(
          "hidden lg:flex absolute -right-3 top-24 w-6 h-6 bg-zinc-900 border border-zinc-800 rounded-full",
          "items-center justify-center text-zinc-500 hover:text-white",
          "hover:border-zinc-700 transition-all shadow-xl z-50"
        )}
      >
        {collapsed ? <ChevronRight className="w-3 h-3" /> : <ChevronLeft className="w-3 h-3" />}
      </button>
    </>
  )

  return (
    <>
      {/* Mobile Menu Button */}
      <button
        onClick={() => setMobileOpen(true)}
        className="lg:hidden fixed top-4 left-4 z-50 w-10 h-10 bg-zinc-900/90 backdrop-blur border border-white/10
                   rounded-lg flex items-center justify-center text-zinc-400 hover:text-white
                   transition-all shadow-lg"
      >
        <Menu className="w-5 h-5" />
      </button>

      {/* Mobile Overlay */}
      {mobileOpen && (
        <div 
          className="lg:hidden fixed inset-0 z-40 bg-black/80 backdrop-blur-sm"
          onClick={() => setMobileOpen(false)}
        />
      )}

      {/* Mobile Sidebar */}
      <aside 
        className={clsx(
          "lg:hidden fixed left-0 top-0 bottom-0 z-50 w-[280px] flex flex-col",
          "bg-zinc-950 border-r border-white/5",
          "transition-transform duration-300 ease-out",
          mobileOpen ? "translate-x-0" : "-translate-x-full"
        )}
      >
        <button
          onClick={() => setMobileOpen(false)}
          className="absolute top-5 right-4 w-8 h-8 flex items-center justify-center 
                     text-zinc-500 hover:text-white transition-colors"
        >
          <X className="w-5 h-5" />
        </button>
        <SidebarContent />
      </aside>

      {/* Desktop Sidebar */}
      <aside 
        className={clsx(
          "hidden lg:flex fixed left-0 top-0 bottom-0 z-40 flex-col",
          "bg-zinc-950/95 backdrop-blur-xl", // Darker background
          "border-r border-white/5", // Thinner border
          "transition-all duration-300 ease-out",
          collapsed ? "w-[72px]" : "w-[240px]" // Slightly narrower
        )}
      >
        <SidebarContent />
      </aside>
    </>
  )
}
