'use client';

import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { logoutAction } from '../app/actions';

type Props = {
  name: string;
  email: string;
  roleName: string;
};

function getInitial(name: string, email: string) {
  const source = name.trim() || email.trim() || 'A';
  return source.charAt(0).toUpperCase();
}

export function ProfileMenu({ name, email, roleName }: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!isOpen) {
      return;
    }

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setIsOpen(false);
      }
    };

    const onPointerDown = (event: PointerEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    window.addEventListener('keydown', onKeyDown);
    window.addEventListener('pointerdown', onPointerDown);
    return () => {
      window.removeEventListener('keydown', onKeyDown);
      window.removeEventListener('pointerdown', onPointerDown);
    };
  }, [isOpen]);

  return (
    <div className="profile-menu" ref={menuRef}>
      <button
        type="button"
        className="dashboard-profile profile-menu-trigger"
        aria-label="Open profile menu"
        aria-expanded={isOpen}
        onClick={() => setIsOpen((value) => !value)}
      >
        <div>
          <strong>{name}</strong>
          <span>{roleName}</span>
        </div>
        <div className="dashboard-avatar">{getInitial(name, email)}</div>
      </button>

      {isOpen ? (
        <section className="profile-menu-panel" aria-label="Profile menu">
          <div className="profile-menu-head">
            <div className="dashboard-avatar">{getInitial(name, email)}</div>
            <div>
              <strong>{name}</strong>
              <span>{email}</span>
              <small>{roleName}</small>
            </div>
          </div>
          <div className="profile-menu-list">
            <Link href="/dashboard/profile" onClick={() => setIsOpen(false)}>
              <span className="material-symbols-outlined">account_circle</span>
              My Profile
            </Link>
            <Link href="/dashboard/settings/security" onClick={() => setIsOpen(false)}>
              <span className="material-symbols-outlined">shield</span>
              Security
            </Link>
            <Link href="/dashboard/settings/audit-trail" onClick={() => setIsOpen(false)}>
              <span className="material-symbols-outlined">history</span>
              Login Activity
            </Link>
          </div>
          <form action={logoutAction} className="profile-menu-logout">
            <button type="submit">
              <span className="material-symbols-outlined">logout</span>
              Log out
            </button>
          </form>
        </section>
      ) : null}
    </div>
  );
}
