'use client';

import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth';
import { useTranslation } from '@/hooks/useTranslation';
import { useSidebar } from '@/hooks/useSidebar';
import { LanguageSwitcher } from './LanguageSwitcher';
import { RegionSwitcher } from './RegionSwitcher';
import { useState } from 'react';
import Image from 'next/image';
import { getEnvBannerVariant } from '@/lib/env-banner';
import { brand } from '@/lib/brand';

export function TopNavbar() {
  const router = useRouter();
  const { user, logout } = useAuth();
  const { t } = useTranslation();
  const { collapsed, setCollapsed } = useSidebar();
  const [searchQuery, setSearchQuery] = useState('');
  const [showUserMenu, setShowUserMenu] = useState(false);
  const envBannerVariant = getEnvBannerVariant();

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    // TODO: 实现搜索功能
    console.log('Search:', searchQuery);
  };

  const handleLogout = () => {
    logout();
    router.push('/login');
  };

  const envBannerContent = envBannerVariant
    ? {
        title:
          envBannerVariant === 'uat'
            ? t.common.envBannerUatTitle
            : t.common.envBannerDevTitle,
        description:
          envBannerVariant === 'uat'
            ? t.common.envBannerUatDesc
            : t.common.envBannerDevDesc,
      }
    : null;

  return (
    <div className="fixed top-0 left-0 right-0 z-50">
      {envBannerContent && (
        <div
          className="h-7 px-6 flex items-center justify-center text-xs font-medium"
          style={{ backgroundColor: '#FF7D00', color: '#FFFFFF' }}
          data-testid="env-banner"
        >
          <span className="mr-2">{envBannerContent.title}</span>
          <span className="opacity-90">{envBannerContent.description}</span>
        </div>
      )}
      <div
        className="h-16 bg-white border-b flex items-center"
        style={{
          borderColor: 'var(--border-color)',
        }}
      >
      {/* Left Side: Logo in Sidebar area */}
      <div 
        className={`flex items-center transition-all duration-200 ${collapsed ? 'w-16 justify-center' : 'w-64'}`}
      >
        {/* Logo - 始终在 64px 区域居中，点击可展开/折叠侧边栏 */}
        <button 
          onClick={() => setCollapsed(!collapsed)}
          className="w-16 flex items-center justify-center flex-shrink-0 group"
          title={collapsed ? 'Expand menu' : 'Collapse menu'}
        >
          <div className="h-10 w-10 rounded-lg flex items-center justify-center bg-white p-2 border shadow-sm transition-all duration-200 group-hover:shadow-md group-hover:border-blue-300" style={{ borderColor: 'var(--border-color)' }}>
            <Image
              src={brand.logoPath}
              alt={`${brand.appTitle} Logo`}
              width={40}
              height={40}
              className="w-full h-full object-contain"
            />
          </div>
        </button>
        
        {/* Brand Name - 仅在展开时显示 */}
        {!collapsed && (
          <div className="flex-1 pl-1">
            <h1 className="text-base font-semibold" style={{ color: 'var(--text-primary)' }}>{t.nav.sidebar.brandName}</h1>
            <p className="text-[10px] whitespace-nowrap" style={{ color: 'var(--text-tertiary)' }}>{t.nav.sidebar.officeAutomation}</p>
          </div>
        )}
      </div>

      {/* Right Side: Search + Actions */}
      <div className="flex-1 flex items-center justify-between px-6">

      {/* Center: Search Bar */}
      <div className="flex-1 max-w-2xl mx-8">
        <form onSubmit={handleSearch}>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg className="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
            </div>
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="block w-full pl-10 pr-3 py-2 border border-gray-200 rounded-lg text-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
              placeholder={`${t.common.search}...`}
              style={{ 
                backgroundColor: 'var(--bg-secondary)',
                borderColor: 'var(--border-color)',
              }}
            />
          </div>
        </form>
      </div>

      {/* Right Side Actions */}
      <div className="flex items-center gap-1 ml-6">
        {/* Region Switcher - 暂时隐藏 */}
        {/* <RegionSwitcher variant="compact" /> */}
        
        {/* Language Switcher */}
        <div className="mr-1">
          <LanguageSwitcher />
        </div>

        {/* Notifications */}
        <button
          onClick={() => router.push('/notifications')}
          className="relative p-2 rounded-lg hover:bg-gray-100 transition-colors"
          style={{ color: 'var(--text-secondary)' }}
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
          </svg>
          {/* Notification Badge */}
          <span className="absolute top-1 right-1 h-2 w-2 bg-red-500 rounded-full"></span>
        </button>

        {/* Help */}
        <button
          onClick={() => router.push('/help')}
          className="p-2 rounded-lg hover:bg-gray-100 transition-colors"
          style={{ color: 'var(--text-secondary)' }}
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </button>

        {/* Settings */}
        <button
          onClick={() => router.push('/settings')}
          className="p-2 rounded-lg hover:bg-gray-100 transition-colors"
          style={{ color: 'var(--text-secondary)' }}
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          </svg>
        </button>

        {/* User Avatar & Dropdown */}
        <div className="relative ml-2">
          <button
            onClick={() => setShowUserMenu(!showUserMenu)}
            className="flex items-center space-x-2 p-1.5 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <div 
              className="h-8 w-8 rounded-full flex items-center justify-center text-white font-semibold text-sm"
              style={{ background: 'var(--lark-blue)' }}
            >
              {(user?.displayName || user?.username)?.charAt(0).toUpperCase()}
            </div>
            <svg 
              className={`w-4 h-4 transition-transform duration-200 ${showUserMenu ? 'rotate-180' : ''}`}
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
              style={{ color: 'var(--text-secondary)' }}
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>

          {/* Dropdown Menu */}
          {showUserMenu && (
            <>
              {/* Backdrop */}
              <div 
                className="fixed inset-0 z-40" 
                onClick={() => setShowUserMenu(false)}
              />
              
              {/* Menu */}
              <div 
                className="absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border z-50 py-2"
                style={{ borderColor: 'var(--border-color)' }}
              >
                {/* User Info */}
                <div className="px-4 py-3 border-b" style={{ borderColor: 'var(--border-color)' }}>
                  <div className="flex items-center space-x-3">
                    <div 
                      className="h-10 w-10 rounded-full flex items-center justify-center text-white font-semibold"
                      style={{ background: 'var(--lark-blue)' }}
                    >
                      {(user?.displayName || user?.username)?.charAt(0).toUpperCase()}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium truncate" style={{ color: 'var(--text-primary)' }}>
                        {user?.displayName || user?.username}
                      </p>
                      <p className="text-xs truncate" style={{ color: 'var(--text-tertiary)' }}>
                        {user?.email}
                      </p>
                    </div>
                  </div>
                </div>

                {/* Menu Items */}
                <div className="py-1">
                  <button
                    onClick={() => {
                      setShowUserMenu(false);
                      router.push('/profile');
                    }}
                    className="w-full flex items-center px-4 py-2 text-sm hover:bg-gray-50 transition-colors"
                    style={{ color: 'var(--text-secondary)' }}
                  >
                    <svg className="w-4 h-4 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                    </svg>
                    {t.common.profile || '个人资料'}
                  </button>
                  
                  <button
                    onClick={() => {
                      setShowUserMenu(false);
                      router.push('/settings');
                    }}
                    className="w-full flex items-center px-4 py-2 text-sm hover:bg-gray-50 transition-colors"
                    style={{ color: 'var(--text-secondary)' }}
                  >
                    <svg className="w-4 h-4 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    {t.common.settings || '设置'}
                  </button>
                </div>

                {/* Logout */}
                <div className="border-t py-1" style={{ borderColor: 'var(--border-color)' }}>
                  <button
                    onClick={handleLogout}
                    className="w-full flex items-center px-4 py-2 text-sm hover:bg-red-50 transition-colors text-red-600"
                  >
                    <svg className="w-4 h-4 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                    </svg>
                    {t.common.logout}
                  </button>
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
    </div>
    </div>
  );
}
