import { useState, useRef, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
import { auth } from "../api";
import LoginButton from "./LoginButton";
import LoginModal from "./LoginModal";
import "./Header.css";

interface Props {
  mapTitle: string | null;
}

export default function Header({ mapTitle }: Props) {
  const { user, authLoading, setUser } = useAuth();
  const navigate = useNavigate();
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  /** Display name: first name if set, otherwise username */
  const displayName = user ? user.first_name?.trim() || user.username : null;

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

  async function handleLogout() {
    setDropdownOpen(false);
    await auth.logout();
    setUser(null);
    navigate("/map");
  }

  return (
    <header className="app-header">
      <div
        className="app-brand"
        onClick={() => navigate("/map")}
        style={{ cursor: "pointer" }}
      >
        <span>SIREN</span>
      </div>

      <div className="app-header-center">
        {mapTitle && <span className="header-map-name">{mapTitle}</span>}
      </div>

      <div className="app-auth">
        {!authLoading &&
          (user ? (
            <div className="account-dropdown-wrapper" ref={dropdownRef}>
              <button
                className="header-btn"
                onClick={() => setDropdownOpen((o) => !o)}
                aria-haspopup="true"
                aria-expanded={dropdownOpen}
                title="Account"
              >
                {displayName}
              </button>

              {dropdownOpen && (
                <div className="account-dropdown">
                  <button
                    className="account-dropdown-item"
                    onClick={() => {
                      navigate("/account");
                      setDropdownOpen(false);
                    }}
                  >
                    Account
                  </button>

                  {user.role === "admin" && (
                    <button
                      className="account-dropdown-item"
                      onClick={() => {
                        navigate("/admin");
                        setDropdownOpen(false);
                      }}
                    >
                      Admin Dashboard
                    </button>
                  )}

                  <div className="account-dropdown-divider" />

                  <button
                    className="account-dropdown-item account-dropdown-logout"
                    onClick={handleLogout}
                  >
                    Log Out
                  </button>
                </div>
              )}
            </div>
          ) : (
            <LoginButton
              className="header-btn"
              onClick={() => setShowLoginModal(true)}
            />
          ))}
      </div>

      {showLoginModal && (
        <LoginModal
          onClose={() => setShowLoginModal(false)}
          onLogin={(u) => {
            setUser(u);
            setShowLoginModal(false);
          }}
        />
      )}
    </header>
  );
}
