import { 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 goToAccount = () => {
    setMenuOpen(false)
    navigate("/account")
  }

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

  return (
    <div className="relative flex items-center gap-3">
      {isAuthenticated && user ? (
        <div className="relative">
          <img
            src={user.avatarUrl || `${import.meta.env.BASE_URL}placeholders/placeholder-profile.png`}
            alt={user.username}
            className="w-8 h-8 rounded-full cursor-pointer border border-gray-400 hover:border-orange-500 transition"
            onClick={() => setMenuOpen((prev) => !prev)}
          />

          {menuOpen && (
            <div className="absolute right-0 mt-2 w-44 bg-surface border border-border rounded-lg shadow-md py-2 z-50">
              <p className="px-4 py-2 text-sm text-text font-semibold">{user.username}</p>
              <button
                onClick={goToAccount}
                className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
              >
                Profilim
              </button>
              <button
                onClick={handleLogout}
                className="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100"
              >
                Çıkış yap
              </button>
            </div>
          )}
        </div>
      ) : (
        <button
          onClick={() => setShowModal(true)}
          className="bg-orange-600 text-white px-4 py-2 rounded-md hover:bg-orange-700 transition-colors"
        >
          Giriş yap
        </button>
      )}

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