import logo from '@shared/assets/logo-full-white.png'
import styles from './WalletHeader.module.css'
import { NavLink } from 'react-router-dom'
import { ROUTES } from '@shared/config/routes'
import { useEffect, useRef, useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { logout } from '@features/auth/api/registrationApi'
import { AUTH_QUERY_KEY, useMe } from '@features/auth'
import { tokenStore } from '@shared/api/tokenStore'
import { Notification } from '@shared/ui'

const capitalize = (s: string | null) => (s ? s[0].toUpperCase() + s.slice(1).toLowerCase() : '')

const NAV_ITEMS = [
  { to: ROUTES.PROFILE, label: 'Личный кабинет' },
  { to: ROUTES.WALLET, label: 'Кошелёк' },
  { to: ROUTES.STAKING, label: 'Стейкинг' },
  { to: ROUTES.POOLS, label: 'Пулы' },
]

export function WalletHeader() {
  const [open, setOpen] = useState(false)
  const [menuOpen, setMenuOpen] = useState(false)
  const [error, setError] = useState(false)
  const ref = useRef<HTMLDivElement>(null)
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const { data: me } = useMe()
  const fullName = me
    ? [me.first_name, me.middle_name].filter(Boolean).map(capitalize).join(' ')
    : ''

  const { mutate: logoutMutate } = useMutation({
    mutationFn: logout,
    onSuccess: () => {
      tokenStore.clear()
      queryClient.clear()
      queryClient.setQueryData(AUTH_QUERY_KEY, null)
      navigate(ROUTES.HOME)
    },
    onError: () => setError(true),
  })

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  // Блокируем прокрутку фона, когда открыто мобильное меню
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : ''
    return () => {
      document.body.style.overflow = ''
    }
  }, [menuOpen])

  function handleLogout() {
    logoutMutate()
    setOpen(false)
    setMenuOpen(false)
  }

  return (
    <>
      <nav className={styles.nav}>
        <a href="/" className={styles.logo}>
          <img src={logo} alt="ЭКСА" />
        </a>

        <div className={styles.menu}>
          {NAV_ITEMS.map((item) => (
            <NavLink
              key={item.to}
              to={item.to}
              className={({ isActive }) =>
                `${styles.menuLink} ${isActive ? styles.menuLinkActive : ''}`
              }
            >
              {item.label}
            </NavLink>
          ))}
        </div>

        <div className={styles.right}>
          <div className={styles.accountWrapper} ref={ref}>
            <button className={styles.account} onClick={() => setOpen((v) => !v)}>
              {me?.avatar_link ? (
                <img src={me.avatar_link} alt="" className={styles.avatar} />
              ) : (
                <div className={styles.avatar} />
              )}
              <span>{fullName || me?.legal_entity?.name || 'Test account'}</span>
            </button>
            {open && (
              <div className={styles.dropdown}>
                <button
                  className={`${styles.dropdownItem} ${styles.danger}`}
                  onClick={handleLogout}
                >
                  Выйти
                </button>
              </div>
            )}
          </div>

          <button
            className={`${styles.burger} ${menuOpen ? styles.burgerOpen : ''}`}
            onClick={() => setMenuOpen((v) => !v)}
            aria-label="Меню"
            aria-expanded={menuOpen}
          >
            <span />
            <span />
            <span />
          </button>
        </div>
      </nav>

      <div className={`${styles.mobileMenu} ${menuOpen ? styles.mobileMenuOpen : ''}`}>
        {NAV_ITEMS.map((item, i) => (
          <NavLink
            key={item.to}
            to={item.to}
            onClick={() => setMenuOpen(false)}
            style={{ transitionDelay: menuOpen ? `${0.08 + i * 0.05}s` : '0s' }}
            className={({ isActive }) =>
              `${styles.mobileLink} ${isActive ? styles.mobileLinkActive : ''}`
            }
          >
            {item.label}
          </NavLink>
        ))}
        <button
          className={`${styles.mobileLink} ${styles.danger}`}
          style={{ transitionDelay: menuOpen ? `${0.08 + NAV_ITEMS.length * 0.05}s` : '0s' }}
          onClick={handleLogout}
        >
          Выйти
        </button>
      </div>

      {error && (
        <Notification
          status="error"
          message="Произошла ошибка сервера"
          onClose={() => setError(false)}
        />
      )}
    </>
  )
}
