import {useIsFetching, useQuery} from '@tanstack/react-query'
import {usePrivy} from '@privy-io/react-auth'
import type {ReactNode} from 'react'
import {useState} from 'react'
import {Link} from 'react-router-dom'

import {NavItem} from '..'
import useApiUrlStore from '../../../app/store/apiStore'
import {UserClient} from '../../../generated/ManagingApi'
import Logo from '../../../assets/img/logo.png'
import {Loader} from '../../atoms'
import useCookie from '../../../hooks/useCookie'

const navigation = [
  { href: '/bots', name: 'Bots' },
  { href: '/backtest', name: 'Backtest' },
  { href: '/scenarios', name: 'Scenarios' },
  { href: '/tools', name: 'Tools' },
  { href: '/settings', name: 'Settings' },
]

function navItems(isMobile = false) {
  return navigation.map((item) => (
    <NavItem key={item.name} href={item.href} isMobile={isMobile}>
      {item.name}
    </NavItem>
  ))
}

function PrimaryNavbar() {
  return (
    <div className="flex">
      <Link className="btn btn-ghost text-xl normal-case" to={'/'}>
        <img src={Logo} className="App-logo" alt="logo" />
      </Link>
      {/* <NavItem href="#" /> */}
      <div className="md:flex items-center hidden space-x-1">{navItems()}</div>
    </div>
  )
}

const GlobalLoader = () => {
  const isFetching = useIsFetching()
  return isFetching ? <Loader size="xs"></Loader> : null
}

// Custom Privy wallet button component
const PrivyWalletButton = () => {
  const { login, logout, authenticated, user } = usePrivy()
  const { apiUrl } = useApiUrlStore()
  const { getCookie } = useCookie()
  const api = new UserClient({}, apiUrl)
  
  // Get JWT token from cookies
  const jwtToken = getCookie('token')
  
  // Fetch user information from the API
  const { data: userInfo } = useQuery({
    queryKey: ['user'],
    queryFn: () => api.user_GetCurrentUser(),
    enabled: authenticated && !!jwtToken, // Only fetch when authenticated AND JWT token exists
  })
  
  if (!authenticated) {
    return (
      <button 
        onClick={login}
        className="btn btn-primary btn-sm"
      >
        Connect Wallet
      </button>
    )
  }
  
  // Display username (agentName) or fallback to wallet address
  const displayName = userInfo?.name || (user?.wallet?.address 
    ? `${user.wallet.address.slice(0, 6)}...${user.wallet.address.slice(-4)}`
    : 'Connected')
  
  const walletAddress = user?.wallet?.address
  
  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text)
      // You could add a toast notification here if you have a toast system
    } catch (err) {
      console.error('Failed to copy to clipboard:', err)
    }
  }
  
  return (
    <div className="dropdown dropdown-end">
      <label tabIndex={0} className="btn btn-primary btn-sm">
        {displayName}
      </label>
      <ul tabIndex={0} className="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-52">
        <li>
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              {userInfo?.avatarUrl && (
                <img 
                  src={userInfo.avatarUrl} 
                  alt="User Avatar" 
                  className="w-6 h-6 rounded-full object-cover"
                  onError={(e) => {
                    // Fallback to a default avatar if image fails to load
                    e.currentTarget.style.display = 'none'
                  }}
                />
              )}
            
                          </div>
              {userInfo?.agentName && (
                <span className="text-xs opacity-70 font-semibold">
                  {userInfo.agentName}
                </span>
              )}
            </div>
        </li>
        {user?.linkedAccounts && user.linkedAccounts.length > 0 && (
          <>
            <li className="text-xs opacity-70 font-semibold">Linked Accounts:</li>
            {user.linkedAccounts.map((account, index) => (
              <li key={index} className="text-xs opacity-70">
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-2">
                    <span className="capitalize">{account.type}</span>
                    {account.type === 'wallet' && account.address && (
                      <span className="opacity-60">
                        {account.address.slice(0, 4)}...{account.address.slice(-4)}
                      </span>
                    )}
                    {account.type === 'twitter_oauth' && (
                      <span className="opacity-60">Twitter Connected</span>
                    )}
                    {account.type === 'google_oauth' && (
                      <span className="opacity-60">Google Connected</span>
                    )}
                    {account.type === 'email' && account.address && (
                      <span className="opacity-60">{account.address}</span>
                    )}
                  </div>
                  {(account.type === 'wallet' && account.address) || (account.type === 'email' && account.address) ? (
                    <button 
                      onClick={() => copyToClipboard(account.address)}
                      className="btn btn-xs btn-ghost"
                      title="Copy to clipboard"
                    >
                      📋
                    </button>
                  ) : null}
                </div>
              </li>
            ))}
          </>
        )}
        <li><a onClick={logout}>Disconnect</a></li>
      </ul>
    </div>
  )
}

export function SecondaryNavbar() {
  const { environment, prepareEnvironmentChange } = useApiUrlStore()
  const { logout } = usePrivy()

  const handleEnvironmentChange = async (newEnv: 'local' | 'sandbox' | 'production') => {
    prepareEnvironmentChange(newEnv)
    
    if (logout) {
      await logout()
    }
    window.location.reload()
  }

  return (
    <div className="md:flex items-center hidden space-x-3">
      <GlobalLoader />
      <div className="form-control">
        <select
          className="select select-bordered select-sm"
          value={environment}
          onChange={(e) => handleEnvironmentChange(e.target.value as 'local' | 'sandbox' | 'production')}
        >
          <option value="local">Local</option>
          <option value="sandbox">Sandbox</option>
          <option value="production">Production</option>
        </select>
      </div>
      <PrivyWalletButton />
    </div>
  )
}

type MobileMenuButtonProps = {
  onClick: VoidFunction
}

function MobileMenuButton({ onClick }: MobileMenuButtonProps) {
  return (
    <div className="md:hidden flex items-center">
      <button className="mobile-menu-button outline-none" onClick={onClick}>
        <svg
          className=" hover:text-primary text-accent w-6 h-6"
          x-show="!showMenu"
          fill="none"
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth="2"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path d="M4 6h16M4 12h16M4 18h16" />
        </svg>
      </button>
    </div>
  )
}
type MobileMenuProps = {
  isOpen: boolean
}

function MobileMenu({ isOpen }: MobileMenuProps) {
  return (
    <div className={isOpen ? 'mobile-menu' : 'hidden mobile-menu'}>
      <ul>{navItems(true)}</ul>
    </div>
  )
}
type NavContainerProps = {
  children: ReactNode
  isMenuOpen: boolean
}

function NavContainer({ children, isMenuOpen }: NavContainerProps) {
  return (
    <nav className="bg-base-300 shadow-lg">
      <div className="max-w-6xl px-4 mx-auto">
        <div className="flex justify-between">{children}</div>
      </div>

      <MobileMenu isOpen={isMenuOpen} />
    </nav>
  )
}
export default function NavBar() {
  const [isMenuOpen, setIsMenuOpen] = useState<boolean>(false)

  return (
    <NavContainer isMenuOpen={isMenuOpen}>
      <PrimaryNavbar />
      <SecondaryNavbar />
      <MobileMenuButton onClick={() => setIsMenuOpen(!isMenuOpen)} />
    </NavContainer>
  )
}
