import { Link, useLocation } from 'react-router-dom'
import { useScroll } from 'ahooks'
import { twMerge } from 'tailwind-merge'
import { Moon, Sun, Menu, X } from 'lucide-react'
import { Button, Avatar, Dropdown } from '@heroui/react'
import { useState } from 'react'
import { useSession, signOut } from '../lib/auth-client'

function isBrowser() {
  return !!(typeof window !== 'undefined' && window.document && window.document.createElement)
}

export function SiteNavbar() {
  const scroll = useScroll(isBrowser() ? document : null)
  const location = useLocation()
  const pathname = location.pathname
  const { data: session } = useSession()
  const [isMenuOpen, setIsMenuOpen] = useState(false)
  
  const [theme, setTheme] = useState<'light' | 'dark'>(() => {
    if (typeof window !== 'undefined') {
      const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null
      if (savedTheme) return savedTheme
      return document.documentElement.classList.contains('dark') ? 'dark' : 'light'
    }
    return 'light'
  })

  const toggleTheme = () => {
    const nextTheme = theme === 'dark' ? 'light' : 'dark'
    document.documentElement.classList.remove('light', 'dark')
    document.documentElement.classList.add(nextTheme)
    document.documentElement.setAttribute('data-theme', nextTheme)
    localStorage.setItem('theme', nextTheme)
    setTheme(nextTheme)
  }

  const menuItems = [
    { name: '主页', href: '/' },
    { name: '击杀生成', href: '/demo' },
    { name: '关于', href: '/about' },
  ]

  const shouldShow = pathname !== '/' || (scroll?.top || 0) > 140

  return (
    <>
      <nav
        className={twMerge(
          'sticky top-0 z-30 w-full bg-white/75 dark:bg-black/70 backdrop-blur-xl transition-all duration-300',
          shouldShow 
            ? 'opacity-100 translate-y-0 border-b border-zinc-100 dark:border-zinc-800 h-auto' 
            : 'opacity-0 h-0 -translate-y-1/4 pointer-events-none'
        )}
      >
        <div className="flex items-center justify-between w-full max-w-screen-lg gap-4 px-8 py-4 mx-auto">
          <Link to="/">
            <h4 className="font-bold whitespace-nowrap text-xl text-foreground">HLAE中文站</h4>
          </Link>

          <ul className="hidden sm:flex items-center gap-6">
            {menuItems.map((item) => (
              <Link 
                key={item.href} 
                to={item.href} 
                className={twMerge(
                  "font-semibold text-zinc-900 dark:text-zinc-100 text-md hover:text-primary transition-colors",
                  pathname === item.href && "text-primary"
                )}
              >
                {item.name}
              </Link>
            ))}
            
            <Button size="sm" isIconOnly variant="ghost" onPress={toggleTheme}>
              {theme == 'dark' ? <Sun size={20} /> : <Moon size={20} />}
            </Button>

            {session ? (
              <Dropdown>
                <Dropdown.Trigger>
                  <Button isIconOnly variant="ghost" className="rounded-full">
                    <Avatar size="sm">
                      <Avatar.Image src={session.user.image || ''} alt={session.user.name || 'User'} />
                      <Avatar.Fallback>{(session.user.name || 'U').slice(0, 2).toUpperCase()}</Avatar.Fallback>
                    </Avatar>
                  </Button>
                </Dropdown.Trigger>
                <Dropdown.Menu aria-label="Profile Actions">
                  <Dropdown.Item key="profile" textValue="Profile" href="/profile">
                    <div className="flex flex-col">
                      <span className="font-semibold">{session.user.name || '个人资料'}</span>
                      <span className="text-tiny text-default-500">{session.user.email}</span>
                    </div>
                  </Dropdown.Item>
                  <Dropdown.Item key="logout" textValue="Logout" variant="danger" onPress={() => signOut()}>
                    退出登录
                  </Dropdown.Item>
                </Dropdown.Menu>
              </Dropdown>
            ) : (
              <div className="flex items-center gap-2">
                <Link to="/login">
                  <Button size="sm" variant="ghost">登录</Button>
                </Link>
                <Link to="/register">
                  <Button size="sm" variant="primary">注册</Button>
                </Link>
              </div>
            )}
          </ul>

          <Button size="sm" isIconOnly variant="ghost" className="sm:hidden" onPress={() => setIsMenuOpen(true)} aria-label="打开菜单">
            <Menu size={20} />
          </Button>
        </div>
      </nav>

      {/* Mobile Menu */}
      <>
        <div
          className={twMerge(
            'fixed inset-0 z-40 bg-black/50 backdrop-blur-sm sm:hidden transition-opacity duration-300',
            isMenuOpen ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'
          )}
          onClick={() => setIsMenuOpen(false)}
          aria-hidden={!isMenuOpen}
        />
        <div
          className={twMerge(
            'fixed top-0 right-0 z-50 w-64 h-full bg-white dark:bg-zinc-900 shadow-xl sm:hidden transition-transform duration-300 ease-in-out',
            isMenuOpen ? 'translate-x-0' : 'translate-x-full'
          )}
        >
          <div className="flex flex-col h-full">
            <div className="flex items-center justify-between p-6 border-b border-zinc-200 dark:border-zinc-800">
              <h4 className="font-bold whitespace-nowrap text-lg">菜单</h4>
              <Button size="sm" isIconOnly variant="ghost" onPress={() => setIsMenuOpen(false)} aria-label="关闭菜单">
                <X size={20} />
              </Button>
            </div>
            <nav className="flex-1 overflow-y-auto p-6">
              <ul className="flex flex-col gap-4">
                {menuItems.map((item, index) => (
                  <li key={`${item.href}-${index}`}>
                    <Link
                      to={item.href}
                      className={twMerge(
                        'block font-semibold text-zinc-900 dark:text-zinc-100 text-lg py-2 transition-colors',
                        pathname === item.href && 'text-primary'
                      )}
                      onClick={() => setIsMenuOpen(false)}
                    >
                      {item.name}
                    </Link>
                  </li>
                ))}
                <li>
                  <Button size="sm" variant="ghost" isIconOnly onPress={toggleTheme} aria-label="切换主题">
                    {theme == 'dark' ? <Sun size={20} /> : <Moon size={20} />}
                  </Button>
                </li>
                
                {session ? (
                   <>
                       <div className="h-px bg-zinc-200 dark:bg-zinc-800 my-2"></div>
                       <li>
                           <Link to="/profile" className="flex items-center gap-2 py-2" onClick={() => setIsMenuOpen(false)}>
                               <Avatar size="sm">
                                 <Avatar.Image src={session.user.image || ''} alt={session.user.name || 'User'} />
                                 <Avatar.Fallback>{(session.user.name || 'U').slice(0, 2).toUpperCase()}</Avatar.Fallback>
                               </Avatar>
                               <span className="font-semibold">{session.user.name}</span>
                           </Link>
                       </li>
                       <li>
                           <Button size="sm" variant="danger" onPress={() => { signOut(); setIsMenuOpen(false); }} fullWidth>退出登录</Button>
                       </li>
                   </>
                ) : (
                   <>
                       <div className="h-px bg-zinc-200 dark:bg-zinc-800 my-2"></div>
                       <li>
                           <Link to="/login" onClick={() => setIsMenuOpen(false)}>
                               <Button fullWidth variant="ghost">登录</Button>
                           </Link>
                       </li>
                       <li>
                           <Link to="/register" onClick={() => setIsMenuOpen(false)}>
                               <Button fullWidth variant="primary">注册</Button>
                           </Link>
                       </li>
                   </>
                )}
              </ul>
            </nav>
          </div>
        </div>
      </>
    </>
  )
}
