import { Link, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import logo from "../../assets/images/logo_plain.png";

export default function AdminNavbar() {
  const navigate = useNavigate();
  const [adminName, setAdminName] = useState("");

  const API_URL = import.meta.env.VITE_API_URL;

  useEffect(() => {
    const name = localStorage.getItem("adminName");
    if (name) setAdminName(name);
  }, []);

  const handleLogout = async () => {
    try {
      await fetch(`${API_URL}/api/adminlogout`, {
        method: "POST",
        credentials: "include",
      });

      localStorage.removeItem("adminToken");
      localStorage.removeItem("adminName");
      navigate("/admin/login");
    } catch (error) {
      alert("Logout failed");
    }
  };

  return (
    <nav className="w-full h-16 bg-white flex items-center justify-between px-8 shadow-sm sticky top-0 z-50">
      {/* Left side — Logo + Name */}
      <div className="flex items-center gap-4">
        <Link to="/" className="flex items-center gap-2">
          <img src={logo} alt="Logo" className="w-9 h-9 object-contain" />
          <div className="flex flex-col leading-tight">
            <span className="font-bold text-2xl bg-gradient-to-r from-orange-600 to-yellow-400 bg-clip-text text-transparent">
              ESAHAKARA
            </span>
            <span className="text-sm font-semibold text-gray-500">
              Products
            </span>
          </div>
        </Link>
      </div>

      {/* Center — Admin name */}
      <div className="text-gray-700 font-medium text-lg">
        {adminName ? `Hi, ${adminName}` : ""}
      </div>

      {/* Right side — Logout */}
      <button
        onClick={handleLogout}
        className="bg-orange-600 text-white py-2 px-4 rounded-lg hover:bg-orange-500 transition duration-200 font-semibold text-sm"
      >
        Logout
      </button>
    </nav>
  );
}
