import React, { useContext } from 'react'
import { Link, useNavigate, useLocation } from 'react-router-dom'
import { AuthContext } from '../context/AuthContext'
import { CartContext } from '../context/CartContext'
import SearchBar from './SearchBar'
import '../styles/global.css'

export default function Navbar() {
  const { user, token, logout } = useContext(AuthContext)
  const { cart } = useContext(CartContext)
  const navigate = useNavigate()
  const location = useLocation()

  const handleLogout = () => {
    logout()
    navigate('/')
  }

  const isActive = (path) => {
    return location.pathname === path ? 'active' : ''
  }

  return (
    <nav className="navbar">
      <div className="navbar-container">
        <Link to="/" className="navbar-logo">
          <span className="logo-icon">👟</span> Brand Master
        </Link>

        <div className="navbar-center">
          <SearchBar />
        </div>

        <ul className="navbar-menu">
          <li><Link to="/" className={isActive('/')}>Home</Link></li>
          <li><Link to="/products" className={isActive('/products')}>Shop</Link></li>
          <li><Link to="/sales" className={isActive('/sales')}>Sales</Link></li>
          <li><Link to="/about" className={isActive('/about')}>About</Link></li>
          <li><Link to="/contact" className={isActive('/contact')}>Contact</Link></li>
          {user?.is_admin && (
            <li><Link to="/admin" className={`admin-link ${isActive('/admin')}`}>Admin</Link></li>
          )}
        </ul>

        <div className="navbar-icons">
          {token ? (
            <>
              <Link to="/wishlist" className="icon-btn" title="Wishlist">
                ❤️
              </Link>
              <Link to="/cart" className="icon-btn cart-btn" title="Cart">
                🛒
                {cart.length > 0 && <span className="cart-count">{cart.length}</span>}
              </Link>
              <Link to="/profile" className="icon-btn" title="Profile">
                👤
              </Link>
              <button onClick={handleLogout} className="btn btn-small">
                Logout
              </button>
            </>
          ) : (
            <>
              <Link to="/cart" className="icon-btn cart-btn" title="Cart">
                🛒
                {cart.length > 0 && <span className="cart-count">{cart.length}</span>}
              </Link>
              <Link to="/login" className="btn btn-small">
                Login
              </Link>
              <Link to="/register" className="btn btn-small btn-secondary">
                Sign Up
              </Link>
            </>
          )}
        </div>
      </div>
    </nav>
  )
}
