import React, { useState } from 'react';
import { useWeb3 } from '../context/Web3Context';
import { Wallet, TrendingUp, Compass, PieChart, PlusCircle, Droplet, ShieldAlert } from 'lucide-react';

interface NavbarProps {
  activeTab: string;
  setActiveTab: (tab: string) => void;
}

export const WebNavbar: React.FC<NavbarProps> = ({ activeTab, setActiveTab }) => {
  const { account, wusdBalance, isCorrectNetwork, connectWallet, switchNetwork, refreshBalance, getCollateralContract } = useWeb3();
  const [faucetLoading, setFaucetLoading] = useState(false);

  const handleQuickFaucet = async () => {
    if (!account) return;
    try {
      setFaucetLoading(true);
      const collateral = getCollateralContract();
      if (!collateral) return;
      const tx = await collateral.mint(account, "100000000000000000000000000"); // 100M WUSD
      await tx.wait();
      refreshBalance();
      alert('🎉 成功领取 100,000,000 WUSD 测试金！');
    } catch (e: any) {
      alert('领水失败: ' + (e.message || e));
    } finally {
      setFaucetLoading(false);
    }
  };

  const navs = [
    { id: 'explore', label: '🔥 市场探索', icon: Compass },
    { id: 'trade', label: '⚡ 交易终端', icon: TrendingUp },
    { id: 'create', label: '🚀 创建市场', icon: PlusCircle },
    { id: 'portfolio', label: '💼 持仓与金库', icon: PieChart },
  ];

  return (
    <header className="bg-[#0c0e17]/90 backdrop-blur-md border-b border-slate-800/80 sticky top-0 z-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
        {/* Logo & Navigation */}
        <div className="flex items-center space-x-8">
          <div className="flex items-center space-x-3 cursor-pointer" onClick={() => setActiveTab('explore')}>
            <div className="w-9 h-9 bg-gradient-to-tr from-cyan-400 via-indigo-500 to-purple-600 rounded-xl flex items-center justify-center font-black text-white shadow-lg shadow-cyan-500/20">
              W
            </div>
            <div className="flex items-baseline space-x-1.5">
              <span className="font-extrabold text-xl text-white tracking-wider bg-clip-text text-transparent bg-gradient-to-r from-white to-slate-300">
                WTFX
              </span>
              <span className="text-[10px] font-mono font-bold px-1.5 py-0.5 rounded bg-gradient-to-r from-cyan-500/20 to-purple-500/20 text-cyan-300 border border-cyan-500/30">
                TESTNET
              </span>
            </div>
          </div>

          <nav className="flex space-x-1">
            {navs.map((item) => {
              const Icon = item.icon;
              const isActive = activeTab === item.id;
              return (
                <button
                  key={item.id}
                  onClick={() => setActiveTab(item.id)}
                  className={`flex items-center space-x-2 px-3.5 py-2 rounded-xl text-xs sm:text-sm font-semibold transition-all ${
                    isActive
                      ? 'bg-slate-800/80 text-white shadow-sm border border-slate-700/80'
                      : 'text-slate-400 hover:text-slate-200 hover:bg-slate-800/40'
                  }`}
                >
                  <Icon className={`w-4 h-4 ${isActive ? 'text-cyan-400' : 'text-slate-500'}`} />
                  <span>{item.label}</span>
                </button>
              );
            })}
          </nav>
        </div>

        {/* Right Section / Faucet & Wallet */}
        <div className="flex items-center space-x-3">
          {account && (
            <button
              onClick={handleQuickFaucet}
              disabled={faucetLoading}
              className="flex items-center space-x-1.5 px-3 py-1.5 bg-cyan-950/60 hover:bg-cyan-900/60 text-cyan-400 border border-cyan-800/50 rounded-xl text-xs font-bold transition-colors"
            >
              <Droplet className="w-3.5 h-3.5" />
              <span>{faucetLoading ? '领水中...' : '全民领水 1 亿'}</span>
            </button>
          )}

          {account ? (
            <div className="flex items-center space-x-3">
              {!isCorrectNetwork ? (
                <button
                  onClick={switchNetwork}
                  className="flex items-center space-x-1.5 bg-amber-500/10 text-amber-400 border border-amber-500/30 px-3 py-1.5 rounded-lg text-xs font-medium hover:bg-amber-500/20"
                >
                  <ShieldAlert className="w-4 h-4" />
                  <span>切换测试网</span>
                </button>
              ) : (
                <div className="hidden sm:flex items-center space-x-2 bg-slate-900/80 border border-slate-800 px-3 py-1.5 rounded-xl">
                  <span className="text-xs text-slate-400">可用:</span>
                  <span className="text-xs font-mono font-bold text-emerald-400">
                    {Number(wusdBalance).toLocaleString(undefined, { maximumFractionDigits: 2 })} WUSD
                  </span>
                </div>
              )}

              <div className="flex items-center space-x-2 bg-slate-900 border border-slate-800 px-3.5 py-1.5 rounded-xl">
                <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></div>
                <span className="font-mono text-xs font-medium text-slate-200">
                  {account.slice(0, 6)}...{account.slice(-4)}
                </span>
              </div>
            </div>
          ) : (
            <button
              onClick={connectWallet}
              className="flex items-center space-x-2 bg-gradient-to-r from-cyan-500 to-indigo-600 hover:from-cyan-400 hover:to-indigo-500 text-white px-5 py-2 rounded-xl text-sm font-bold shadow-lg shadow-cyan-500/25 transition-all"
            >
              <Wallet className="w-4 h-4" />
              <span>连接钱包</span>
            </button>
          )}
        </div>
      </div>
    </header>
  );
};
