import React, { useState, useRef, useCallback } from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { FiUser, FiMenu, FiX, FiLogOut } from 'react-icons/fi';
import { useUser } from '../contexts/UserContext';
import toast from 'react-hot-toast';
import clsx from 'clsx';

const logoSrc = '/assets/logo.png';

const ADMIN_TOKEN = 'shumengya520';

const Header = () => {
  const { user, isLoggedIn, logout } = useUser();
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [showAdminModal, setShowAdminModal] = useState(false);
  const [adminInput, setAdminInput] = useState('');
  const navigate = useNavigate();
  const location = useLocation();

  const clickCountRef = useRef(0);
  const clickTimerRef = useRef(null);

  const handleLogoClick = useCallback((e) => {
    e.preventDefault();
    clickCountRef.current += 1;
    clearTimeout(clickTimerRef.current);

    if (clickCountRef.current >= 5) {
      clickCountRef.current = 0;
      if (localStorage.getItem('admin_token') === ADMIN_TOKEN) {
        navigate('/admin');
      } else {
        setAdminInput('');
        setShowAdminModal(true);
      }
      return;
    }

    clickTimerRef.current = setTimeout(() => {
      clickCountRef.current = 0;
    }, 2000);

    navigate('/');
  }, [navigate]);

  const handleAdminSubmit = () => {
    if (adminInput === ADMIN_TOKEN) {
      localStorage.setItem('admin_token', ADMIN_TOKEN);
      setShowAdminModal(false);
      toast.success('管理员验证通过');
      navigate('/admin');
    } else {
      toast.error('令牌错误');
      setAdminInput('');
    }
  };

  const isActive = (path) => location.pathname.startsWith(path);

  const handleLogout = async () => {
    await logout();
    setIsMenuOpen(false);
    navigate('/');
  };

  return (
    <>
      <header
        className={[
          'sticky top-0 z-[1000] text-white py-3',
          'bg-[linear-gradient(135deg,rgba(129,199,132,0.62)_0%,rgba(102,187,106,0.62)_100%)]',
          '[backdrop-filter:blur(16px)_saturate(125%)]',
          'shadow-[0_2px_16px_rgba(0,0,0,0.08)]',
          'border-b border-white/35',
        ].join(' ')}
      >
        <div className="max-w-[1200px] mx-auto px-4 flex items-center justify-between">
          {/* Logo */}
          <div
            onClick={handleLogoClick}
            className="flex items-center text-xl font-bold text-white cursor-pointer select-none"
          >
            <img
              src={logoSrc}
              alt="InfoGenie Logo"
              className="mr-2 w-9 h-9 object-cover md:w-[30px] md:h-[30px]"
            />
            万象口袋
          </div>

          {/* Desktop Nav */}
          <nav className="hidden md:flex items-center gap-6">
            {[
              { to: '/60sapi', label: '60sAPI' },
              { to: '/smallgame', label: '休闲游戏' },
              { to: '/toolbox', label: '工具箱' },
              { to: '/aimodel', label: 'AI应用' },
              { to: '/profile', label: '个人中心' },
            ].map(({ to, label }) => (
              <Link
                key={to}
                to={to}
                className={clsx(
                  'no-underline px-[18px] py-2.5 rounded-xl transition-all duration-300 relative',
                  isActive(to)
                    ? 'text-white font-semibold bg-white/20 shadow-[0_4px_12px_rgba(0,0,0,0.15)] -translate-y-px'
                    : 'text-white/90 font-medium hover:bg-white/15 hover:text-white hover:-translate-y-0.5 hover:shadow-[0_6px_20px_rgba(0,0,0,0.2)]',
                )}
              >
                {label}
              </Link>
            ))}
          </nav>

          {/* User Section */}
          <div className="flex items-center gap-3">
            {isLoggedIn && user ? (
              <>
                <div className="flex items-center gap-2 bg-white/10 text-white px-3 py-1.5 rounded-md">
                  {user.avatarUrl ? (
                    <img
                      src={user.avatarUrl}
                      alt="头像"
                      className="w-6 h-6 rounded-full border-2 border-white/30 object-cover"
                      onError={(e) => { e.target.style.display = 'none'; }}
                    />
                  ) : null}
                  <FiUser style={{ display: user.avatarUrl ? 'none' : 'inline' }} />
                  <span className="hidden md:inline">{user.username || user.account}</span>
                </div>
                <button
                  onClick={handleLogout}
                  className="flex items-center gap-2 bg-white/10 text-white px-4 py-2 rounded-md transition-all hover:bg-white/20"
                >
                  <FiLogOut size={16} />
                  <span className="hidden md:inline">退出</span>
                </button>
              </>
            ) : (
              <Link
                to="/login"
                className="flex items-center gap-2 bg-white/10 text-white px-4 py-2 rounded-md transition-all hover:bg-white/20"
              >
                <FiUser />
                <span className="hidden md:inline">登录</span>
              </Link>
            )}

            <button
              onClick={() => setIsMenuOpen(!isMenuOpen)}
              className="md:hidden bg-transparent border-none text-white text-2xl cursor-pointer"
            >
              <FiMenu />
            </button>
          </div>
        </div>
      </header>

      {/* Mobile Menu Overlay */}
      <div
        className={clsx(
          'fixed inset-0 bg-black/50 z-[2000] md:hidden',
          isMenuOpen ? 'block' : 'hidden',
        )}
        onClick={() => setIsMenuOpen(false)}
      >
        <div
          className={clsx(
            'absolute top-0 right-0 w-72 h-screen overflow-y-auto p-5',
            'backdrop-blur-[10px] transition-transform duration-300',
            'bg-[linear-gradient(135deg,rgba(255,240,245,0.95)_0%,rgba(255,253,240,0.95)_35%,rgba(240,255,240,0.95)_70%,rgba(248,250,252,0.95)_100%)]',
            isMenuOpen ? 'translate-x-0' : 'translate-x-full',
          )}
          onClick={(e) => e.stopPropagation()}
        >
          <div className="flex justify-between items-center mb-6 pb-4 border-b border-gray-200">
            <h3 className="text-gray-800 m-0">菜单</h3>
            <button
              onClick={() => setIsMenuOpen(false)}
              className="bg-transparent border-none text-2xl text-gray-500 cursor-pointer"
            >
              <FiX />
            </button>
          </div>

          {[
            { to: '/', label: '首页', exact: true },
            { to: '/60sapi', label: '60sAPI' },
            { to: '/smallgame', label: '休闲游戏' },
            { to: '/toolbox', label: '工具箱' },
            { to: '/aimodel', label: 'AI应用' },
            { to: '/profile', label: '个人中心' },
          ].map(({ to, label, exact }) => {
            const active = exact ? location.pathname === to : isActive(to);
            return (
              <Link
                key={to}
                to={to}
                onClick={() => setIsMenuOpen(false)}
                className={clsx(
                  'block no-underline px-5 py-4 my-1 rounded-xl',
                  'transition-all duration-300 font-medium relative',
                  active
                    ? 'text-[#4ade80] font-semibold bg-[rgba(74,222,128,0.1)] translate-x-2'
                    : 'text-gray-700 hover:text-[#4ade80] hover:bg-[rgba(74,222,128,0.08)] hover:translate-x-3',
                )}
              >
                {active && (
                  <span className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-[60%] bg-gradient-to-b from-[#4ade80] to-[#22c55e] rounded-r-sm" />
                )}
                {label}
              </Link>
            );
          })}

          {isLoggedIn && user && (
            <>
              <div className="flex items-center gap-3 py-3 border-b border-gray-100">
                {user.avatarUrl ? (
                  <img src={user.avatarUrl} alt="头像" className="w-8 h-8 rounded-full" />
                ) : (
                  <FiUser size={24} color="#666" />
                )}
                <span className="text-gray-700 font-medium">{user.username || user.account}</span>
              </div>
              <button
                className="block w-full text-left px-5 py-4 my-1 rounded-xl text-red-500 font-medium bg-transparent border-none cursor-pointer hover:bg-red-50"
                onClick={() => { handleLogout(); setIsMenuOpen(false); }}
              >
                🚪 退出登录
              </button>
            </>
          )}
        </div>
      </div>

      {/* Admin Modal */}
      {showAdminModal && (
        <div
          className="fixed inset-0 bg-black/60 flex items-center justify-center z-[10000] backdrop-blur-[4px]"
          onClick={() => setShowAdminModal(false)}
        >
          <div
            className="bg-gradient-to-br from-[#e8f5e8] to-[#f1f8e9] p-8 rounded-[18px] w-[340px] max-w-[90vw] shadow-[0_20px_40px_rgba(0,0,0,0.25)] text-center"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="m-0 mb-2 text-xl text-[#1b5e20]">🔐 管理员验证</h3>
            <p className="m-0 mb-5 text-sm text-gray-500">请输入管理员令牌以进入后台</p>
            <input
              type="password"
              placeholder="请输入管理员令牌"
              value={adminInput}
              onChange={(e) => setAdminInput(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleAdminSubmit()}
              autoFocus
              className="w-full px-4 py-3 border-2 border-gray-200 rounded-[10px] text-[15px] font-[inherit] transition-colors focus:border-[#4ade80] focus:outline-none"
            />
            <button
              onClick={handleAdminSubmit}
              className="w-full mt-3.5 py-3 border-none rounded-[10px] bg-gradient-to-br from-[#4ade80] to-[#22c55e] text-white text-[15px] font-semibold cursor-pointer transition-transform hover:-translate-y-px"
            >
              验证并进入
            </button>
            <button
              onClick={() => setShowAdminModal(false)}
              className="w-full mt-2 py-2.5 border-none rounded-[10px] bg-transparent text-gray-500 text-sm cursor-pointer hover:text-gray-700"
            >
              取消
            </button>
          </div>
        </div>
      )}
    </>
  );
};

export default Header;
