'use client';

import { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { useWallet } from '@solana/wallet-adapter-react';
import { WalletMultiButton } from '@solana/wallet-adapter-react-ui';
import { Connection, PublicKey } from '@solana/web3.js';
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
import Image from 'next/image';
import '@solana/wallet-adapter-react-ui/styles.css';
import { CLUSTER_URL } from '../shared';
import { DINO_TOKEN_ADDRESS } from '../constants';

export interface HeaderRef {
  refreshBalance: () => Promise<void>;
}

const Header = forwardRef<HeaderRef>((props, ref) => {
  const { publicKey } = useWallet();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isScrolled, setIsScrolled] = useState(false);
  const [dinoBalance, setDinoBalance] = useState<number | null>(null);
  const [isLoadingBalance, setIsLoadingBalance] = useState(false);

  const fetchDinoBalance = async () => {
    if (!publicKey) {
      setDinoBalance(null);
      return;
    }

    setIsLoadingBalance(true);
    try {
      const connection = new Connection(CLUSTER_URL);
      const tokenMint = new PublicKey(DINO_TOKEN_ADDRESS);
      
      // Get token accounts for the user
      const tokenAccounts = await connection.getParsedTokenAccountsByOwner(
        publicKey,
        { mint: tokenMint }
      );

      if (tokenAccounts.value.length > 0) {
        const balance = tokenAccounts.value[0].account.data.parsed.info.tokenAmount.uiAmount;
        setDinoBalance(balance);
      } else {
        setDinoBalance(0);
      }
    } catch (error) {
      console.error('Error fetching DINO balance:', error);
      setDinoBalance(null);
    } finally {
      setIsLoadingBalance(false);
    }
  };

  // Expose refreshBalance function to parent component
  useImperativeHandle(ref, () => ({
    refreshBalance: fetchDinoBalance
  }));

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 10);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  useEffect(() => {
    fetchDinoBalance();
  }, [publicKey]);

  const handleBuyDino = () => {
    // Redirect to DexScreener - you can update this URL to the actual $DINO token page
    window.open('https://dexscreener.com/solana', '_blank');
  };

  const formatBalance = (balance: number | null) => {
    if (balance === null) return '0';
    if (balance === 0) return '0';
    if (balance < 0.0001) return '< 0.0001';
    return balance.toFixed(4);
  };

  return (
    <header className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${
      isScrolled 
        ? 'bg-white/95 backdrop-blur-xl shadow-xl shadow-gray-200/50 border-b border-gray-200/40' 
        : 'bg-white/80 backdrop-blur-lg shadow-lg shadow-gray-100/30 border-b border-gray-200/20'
    }`}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center h-20">
          {/* Logo and Title */}
          <div className="flex items-center">
            <div className="flex items-center space-x-3 group cursor-pointer">
              <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-emerald-600 rounded-xl flex items-center justify-center shadow-lg shadow-green-500/25 transition-all duration-300 group-hover:scale-110 group-hover:shadow-xl group-hover:shadow-green-500/40 overflow-hidden">
                <Image
                  src="/dino_icon.jpg"
                  alt="DINO Token Icon"
                  width={40}
                  height={40}
                  className="w-full h-full object-cover"
                />
              </div>
              <h1 className="text-3xl font-extrabold bg-gradient-to-r from-gray-900 via-gray-800 to-gray-900 bg-clip-text text-transparent transition-all duration-300 group-hover:from-green-600 group-hover:to-emerald-600">
                DINO
              </h1>
            </div>
          </div>

          {/* Desktop Navigation Links */}
          <nav className="hidden md:flex items-center space-x-10">
            <a 
              href="#support" 
              className="relative text-gray-700 hover:text-green-600 transition-all duration-300 font-semibold text-lg group"
            >
              Support
              <span className="absolute -bottom-1 left-0 w-0 h-0.5 bg-gradient-to-r from-green-500 to-emerald-600 transition-all duration-300 group-hover:w-full"></span>
            </a>
            <a 
              href="#whitepaper" 
              className="relative text-gray-700 hover:text-green-600 transition-all duration-300 font-semibold text-lg group"
            >
              Whitepaper
              <span className="absolute -bottom-1 left-0 w-0 h-0.5 bg-gradient-to-r from-green-500 to-emerald-600 transition-all duration-300 group-hover:w-full"></span>
            </a>
            <div className="flex items-center space-x-6">
              <a 
                href="https://x.com" 
                target="_blank" 
                rel="noopener noreferrer"
                className="w-10 h-10 bg-gray-100 hover:bg-green-100 rounded-full flex items-center justify-center transition-all duration-300 group hover:scale-110 hover:shadow-lg hover:shadow-green-500/25 hover:-translate-y-1"
              >
                <svg className="w-5 h-5 text-gray-600 group-hover:text-green-600 transition-colors duration-300" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
                </svg>
              </a>
              <a 
                href="https://t.me" 
                target="_blank" 
                rel="noopener noreferrer"
                className="w-10 h-10 bg-gray-100 hover:bg-green-100 rounded-full flex items-center justify-center transition-all duration-300 group hover:scale-110 hover:shadow-lg hover:shadow-green-500/25 hover:-translate-y-1"
              >
                <svg className="w-5 h-5 text-gray-600 group-hover:text-green-600 transition-colors duration-300" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/>
                </svg>
              </a>
            </div>
          </nav>

          {/* Buy $DINO Button and Wallet Connect - Desktop */}
          <div className="hidden md:flex items-center space-x-4">
            <button
              onClick={handleBuyDino}
              className="bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white font-bold py-3 px-6 rounded-xl shadow-lg shadow-orange-500/25 hover:shadow-xl hover:shadow-orange-500/30 transition-all duration-300 hover:scale-105 hover:-translate-y-0.5 flex items-center space-x-2"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
              </svg>
              <span>Buy $DINO</span>
            </button>
            
            {publicKey ? (
              <div className="flex items-center space-x-4">
                {/* DINO Balance Display */}
                <div className="bg-gradient-to-r from-green-100 to-emerald-50 rounded-full px-4 py-2 border border-green-200 shadow-sm">
                  <div className="flex items-center space-x-2">
                    <div className="w-3 h-3 bg-gradient-to-br from-green-500 to-emerald-600 rounded-full"></div>
                    <span className="text-sm text-green-700 font-mono font-medium">
                      {isLoadingBalance ? (
                        <div className="flex items-center space-x-1">
                          <div className="w-3 h-3 border-2 border-green-500 border-t-transparent rounded-full animate-spin"></div>
                          <span>Loading...</span>
                        </div>
                      ) : (
                        `${formatBalance(dinoBalance)} $DINO`
                      )}
                    </span>
                  </div>
                </div>
                
                <WalletMultiButton className="!bg-gradient-to-r !from-green-600 !to-emerald-600 hover:!from-green-700 hover:!to-emerald-700 !text-white !rounded-xl !px-6 !py-3 !text-sm !font-semibold !shadow-lg !shadow-green-500/25 hover:!shadow-xl hover:!shadow-green-500/30 transition-all duration-300 hover:!scale-105 hover:!-translate-y-0.5" />
              </div>
            ) : (
              <WalletMultiButton className="!bg-gradient-to-r !from-green-600 !to-emerald-600 hover:!from-green-700 hover:!to-emerald-700 !text-white !rounded-xl !px-6 !py-3 !text-sm !font-semibold !shadow-lg !shadow-green-500/25 hover:!shadow-xl hover:!shadow-green-500/30 transition-all duration-300 hover:!scale-105 hover:!-translate-y-0.5" />
            )}
          </div>

          {/* Mobile Menu Button */}
          <div className="md:hidden flex items-center space-x-3">
            <button
              onClick={handleBuyDino}
              className="bg-gradient-to-r from-orange-500 to-red-500 text-white font-bold py-2 px-4 rounded-lg shadow-lg shadow-orange-500/25 text-sm"
            >
              Buy $DINO
            </button>
            <WalletMultiButton className="!bg-gradient-to-r !from-green-600 !to-emerald-600 !text-white !rounded-lg !px-4 !py-2 !text-sm !font-semibold !shadow-lg !shadow-green-500/25" />
            <button
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              className="w-10 h-10 bg-gray-100 hover:bg-green-100 rounded-lg flex items-center justify-center transition-all duration-300 hover:scale-105"
            >
              <svg className="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                {isMobileMenuOpen ? (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                ) : (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                )}
              </svg>
            </button>
          </div>
        </div>

        {/* Mobile Menu */}
        {isMobileMenuOpen && (
          <div className="md:hidden border-t border-gray-200/60 bg-white/95 backdrop-blur-sm animate-in slide-in-from-top-2 duration-300">
            <div className="px-2 pt-2 pb-3 space-y-1">
              <a 
                href="#support" 
                className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:text-green-600 hover:bg-green-50 transition-colors duration-200"
              >
                Support
              </a>
              <a 
                href="#whitepaper" 
                className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:text-green-600 hover:bg-green-50 transition-colors duration-200"
              >
                Whitepaper
              </a>
              <div className="flex items-center space-x-4 px-3 py-2">
                <span className="text-sm text-gray-500 font-medium">Socials:</span>
                <a 
                  href="https://x.com" 
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="w-8 h-8 bg-gray-100 hover:bg-green-100 rounded-full flex items-center justify-center transition-all duration-300 hover:scale-110"
                >
                  <svg className="w-4 h-4 text-gray-600" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
                  </svg>
                </a>
                <a 
                  href="https://t.me" 
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="w-8 h-8 bg-gray-100 hover:bg-green-100 rounded-full flex items-center justify-center transition-all duration-300 hover:scale-110"
                >
                  <svg className="w-4 h-4 text-gray-600" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/>
                  </svg>
                </a>
              </div>
              {publicKey && (
                <div className="px-3 py-2">
                  <div className="bg-gradient-to-r from-green-100 to-emerald-50 rounded-lg px-3 py-2 border border-green-200 shadow-sm">
                    <div className="flex items-center space-x-2">
                      <div className="w-3 h-3 bg-gradient-to-br from-green-500 to-emerald-600 rounded-full"></div>
                      <span className="text-sm text-green-700 font-mono font-medium">
                        {isLoadingBalance ? (
                          <div className="flex items-center space-x-1">
                            <div className="w-3 h-3 border-2 border-green-500 border-t-transparent rounded-full animate-spin"></div>
                            <span>Loading...</span>
                          </div>
                        ) : (
                          `${formatBalance(dinoBalance)} $DINO`
                        )}
                      </span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </header>
  );
});

export default Header;
