import React, { useState, useEffect, useRef } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Bars3Icon, XMarkIcon } from "@heroicons/react/24/solid";
import { logout } from "../../auth";

export const Header: React.FC = () => {
  const navigate = useNavigate();
  const [username, setUsername] = useState<string | null>(localStorage.getItem("user_name"));
  const [menuOpen, setMenuOpen] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const dropdownRef = useRef<HTMLDivElement>(null);

  // Listen for localStorage changes to update username dynamically
  useEffect(() => {
    const handleStorage = () => setUsername(localStorage.getItem("user_name"));
    // This catches changes from OTHER tabs
    window.addEventListener("storage", handleStorage);
  
    // This catches changes in the CURRENT tab if you use dispatchEvent
    window.addEventListener("local-storage-update", handleStorage); 

    return () => {
      window.removeEventListener("storage", handleStorage);
      window.removeEventListener("local-storage-update", handleStorage);
    };
  }, []);

  const handleLogout = async () => {
    try {
      await logout();
      localStorage.removeItem("user_id");
      localStorage.removeItem("user_name");
      setUsername(null);
      navigate("/login");
    } catch (err) {
      console.error(err);
    }
  };

  // Close dropdown on click outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  return (
    <header className="w-full bg-white shadow-md sticky top-0 left-0 z-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between h-16 items-center">

          {/* Logo */}
          <div className="flex-shrink-0">
            <Link to="/" className="text-xl font-bold text-gray-800 hover:text-blue-600">
              NyanimeDB
            </Link>
          </div>

          {/* Navigation (desktop) */}
          <nav className="hidden md:flex space-x-4">
            <Link to="/titles" className="text-gray-700 hover:text-blue-600">Titles</Link>
            <Link to="/users" className="text-gray-700 hover:text-blue-600">Users</Link>
            <Link to="/about" className="text-gray-700 hover:text-blue-600">About</Link>
          </nav>

          {/* Profile / login */}
          <div className="hidden md:flex items-center space-x-4" ref={dropdownRef}>
            {username ? (
              <div className="relative">
                <button
                  onClick={() => setDropdownOpen(!dropdownOpen)}
                  className="text-gray-700 hover:text-blue-600 font-medium"
                >
                  {username}
                </button>
                {dropdownOpen && (
                  <div className="absolute right-0 mt-2 w-40 bg-white border rounded shadow-md z-50">
                    <Link to="/profile" className="block px-4 py-2 hover:bg-gray-100" onClick={() => setDropdownOpen(false)}>Profile</Link>
                    <button onClick={handleLogout} className="w-full text-left px-4 py-2 hover:bg-gray-100">Logout</button>
                  </div>
                )}
              </div>
            ) : (
              <Link to="/login" className="text-gray-700 hover:text-blue-600 font-medium">Login</Link>
            )}
          </div>

          {/* Mobile burger */}
          <div className="md:hidden flex items-center">
            <button onClick={() => setMenuOpen(!menuOpen)} className="p-2 rounded-md hover:bg-gray-200 transition">
              {menuOpen ? <XMarkIcon className="w-6 h-6 text-gray-800" /> : <Bars3Icon className="w-6 h-6 text-gray-800" />}
            </button>
          </div>

        </div>
      </div>

      {/* Mobile menu */}
      {menuOpen && (
        <div className="md:hidden bg-white border-t border-gray-200 shadow-md">
          <nav className="flex flex-col p-4 space-y-2">
            <Link to="/titles" className="text-gray-700 hover:text-blue-600" onClick={() => setMenuOpen(false)}>Titles</Link>
            <Link to="/users" className="text-gray-700 hover:text-blue-600" onClick={() => setMenuOpen(false)}>Users</Link>
            <Link to="/about" className="text-gray-700 hover:text-blue-600" onClick={() => setMenuOpen(false)}>About</Link>
            {username ? (
              <>
                <Link to="/profile" className="text-gray-700 hover:text-blue-600 font-medium" onClick={() => setMenuOpen(false)}>Profile</Link>
                <button onClick={handleLogout} className="text-gray-700 hover:text-blue-600 font-medium text-left">Logout</button>
              </>
            ) : (
              <Link to="/login" className="text-gray-700 hover:text-blue-600 font-medium" onClick={() => setMenuOpen(false)}>Login</Link>
            )}
          </nav>
        </div>
      )}
    </header>
  );
};
