"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { LogOut } from "lucide-react"; // Menggunakan ikon dari Lucide

export default function Header() {
  const router = useRouter();
  const [user, setUser] = useState<any>(null);

  // Ambil data user yang sedang login dari localStorage
  useEffect(() => {
    const userData = localStorage.getItem("user");
    if (userData) {
      setUser(JSON.parse(userData));
    }
  }, []);

  // Fungsi untuk membersihkan sesi dan kembali ke login
  const handleLogout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("user");
    router.push("/login");
  };

  return (
    <header className="sticky top-0 z-40 flex w-full bg-white drop-shadow-1 dark:bg-boxdark dark:drop-shadow-none">
      {/* justify-end agar isinya merapat ke kanan */}
      <div className="flex grow items-center justify-end px-4 py-4 shadow-2 md:px-6 2xl:px-11">
        
        {/* User Area */}
        <div className="flex items-center gap-3 2xsm:gap-7">
          <div className="flex items-center gap-4">
            
            <span className="hidden text-right lg:block">
              {/* Nama dinamis, jika kosong tampilkan 'Admin S-CLASS' */}
              <span className="block text-sm font-bold text-black">
                {user?.full_name || "Admin S-CLASS"}
              </span>
              {/* Role dinamis */}
              <span className="block text-xs font-medium text-gray-500 capitalize">
                {user?.role || "Administrator"}
              </span>
            </span>
            
            {/* Avatar Bulat Dinamis (Mengambil inisial nama depan) */}
            <div className="h-10 w-10 rounded-full bg-blue-100 border border-blue-200 overflow-hidden flex items-center justify-center">
              <span className="text-blue-600 font-bold text-lg">
                {user?.full_name ? user.full_name.charAt(0).toUpperCase() : "A"}
              </span>
            </div>

          </div>

          {/* Garis Pembatas (Opsional untuk estetika) */}
          <div className="h-8 w-px bg-gray-200"></div>

          {/* Tombol Keluar */}
          <button 
            onClick={handleLogout}
            className="flex items-center gap-2 text-sm font-medium text-red-500 hover:text-red-700 hover:bg-red-50 px-3 py-2 rounded-lg transition-colors"
          >
            <LogOut size={18} />
            <span className="hidden sm:block">Keluar</span>
          </button>

        </div>
      </div>
    </header>
  );
}