import { useEffect, useRef, useState } from "react"
import { useNavigate } from "react-router-dom"
import { useAuth } from "../../../context/AuthContext"
import LoginModal from "../../Auth/LoginModal"

export default function UserInfo() {
  const { user, isAuthenticated, logout } = useAuth()
  const [menuOpen, setMenuOpen] = useState(false)
  const [showModal, setShowModal] = useState(false)
  const navigate = useNavigate()
  const menuRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    if (!menuOpen) return

    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setMenuOpen(false)
    }

    const onMouseDown = (e: MouseEvent) => {
      const target = e.target
      if (!(target instanceof Node)) return
      if (menuRef.current && !menuRef.current.contains(target)) {
        setMenuOpen(false)
      }
    }

    document.addEventListener("keydown", onKeyDown)
    document.addEventListener("mousedown", onMouseDown)
    return () => {
      document.removeEventListener("keydown", onKeyDown)
      document.removeEventListener("mousedown", onMouseDown)
    }
  }, [menuOpen])

  const goToAccount = () => {
    setMenuOpen(false)
    navigate("/account")
  }

  const goToProfile = () => {
    if (!user?.username) return
    setMenuOpen(false)
    navigate(`/user/${user.username}`)
  }

  const handleLogout = () => {
    logout()
    setMenuOpen(false)
  }

  const avatarSrc =
    user?.avatarUrl || `${import.meta.env.BASE_URL}placeholders/placeholder-profile.png`

  return (
    <div className="relative flex items-center gap-3" ref={menuRef}>
      {isAuthenticated && user ? (
        <div className="relative">
          <button
            type="button"
            onClick={() => setMenuOpen((prev) => !prev)}
            className={`rounded-full focus:outline-none focus:ring-2 focus:ring-[var(--color-primary-ring)] ${
              menuOpen ? "ring-2 ring-[var(--color-primary-ring)]" : ""
            }`}
            aria-haspopup="menu"
            aria-expanded={menuOpen}
          >
            <img
              src={avatarSrc}
              alt={user.username}
              className="w-8 h-8 rounded-full border border-border hover:border-[var(--color-primary)] transition"
            />
          </button>

          {menuOpen && (
            <div
              className="absolute right-0 mt-2 w-56 bg-surface border border-border rounded-xl shadow-lg z-50 overflow-hidden"
              role="menu"
            >
              {/* Entire row clickable */}
              <button
                type="button"
                onClick={goToProfile}
                className="w-full text-left px-4 py-3 border-b border-border hover:bg-surface-2 transition"
                role="menuitem"
              >
                <span className="text-sm text-text font-semibold leading-tight">
                  {user.username}
                </span>
              </button>

              <div className="py-1">
                <button
                  type="button"
                  onClick={goToAccount}
                  className="w-full text-left px-4 py-2.5 text-sm text-text hover:bg-surface-2 transition"
                  role="menuitem"
                >
                  Ayarlar
                </button>

                <button
                  type="button"
                  onClick={handleLogout}
                  className="w-full text-left px-4 py-2.5 text-sm text-danger hover:bg-surface-2 transition"
                  role="menuitem"
                >
                  Çıkış yap
                </button>
              </div>
            </div>
          )}
        </div>
      ) : (
        <>
          <button
            type="button"
            onClick={() => setShowModal(true)}
            className="bg-[var(--color-primary)] text-white px-4 py-2 rounded-lg hover:bg-[var(--color-primary-hover)] transition-colors"
          >
            Giriş yap
          </button>
        </>
      )}

      {showModal && <LoginModal onClose={() => setShowModal(false)} />}
    </div>
  )
}
