import { useEffect, useRef, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useAuth } from '../auth/AuthContext'
import { formatMemberRoles, memberAvatarGlyph } from '../lib/memberRole'
import { ThemeToggle } from './ThemeToggle'

export function MemberMenu() {
  const navigate = useNavigate()
  const { member, logout } = useAuth()
  const [open, setOpen] = useState(false)
  const [busy, setBusy] = useState(false)
  const rootRef = useRef<HTMLDivElement>(null)

  const email = member?.email ?? ''
  const displayName = member?.display_name?.trim()
  const roleLabel = formatMemberRoles(member?.roles)
  const avatarGlyph = memberAvatarGlyph(member)
  const shortLabel = displayName || '會員'

  useEffect(() => {
    if (!open) return
    const onPointer = (event: MouseEvent) => {
      if (!rootRef.current?.contains(event.target as Node)) setOpen(false)
    }
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') setOpen(false)
    }
    document.addEventListener('mousedown', onPointer)
    document.addEventListener('keydown', onKey)
    return () => {
      document.removeEventListener('mousedown', onPointer)
      document.removeEventListener('keydown', onKey)
    }
  }, [open])

  async function handleLogout() {
    setBusy(true)
    try {
      await logout()
      setOpen(false)
      navigate('/login', { replace: true })
    } finally {
      setBusy(false)
    }
  }

  return (
    <div ref={rootRef} className="ac-member-menu-wrap relative">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="ac-member-trigger"
        aria-expanded={open}
        aria-haspopup="menu"
        aria-label={`會員：${email || shortLabel}`}
      >
        <span className="ac-member-avatar" aria-hidden>
          {avatarGlyph}
        </span>
        <span className="ac-member-trigger-text hidden min-w-0 max-w-[6.5rem] truncate sm:inline">
          {shortLabel}
        </span>
        <span className="ac-account-trigger-chevron" aria-hidden>
          {open ? '▴' : '▾'}
        </span>
      </button>

      {open ? (
        <div role="menu" className="ac-member-menu">
          <p className="ac-account-menu-title">已登入</p>
          <div className="ac-member-menu-body">
            <div className="ac-member-menu-hero">
              <span className="ac-member-avatar ac-member-avatar--lg">{avatarGlyph}</span>
              <div className="min-w-0 flex-1">
                {displayName ? (
                  <p className="truncate text-sm font-bold text-ink">{displayName}</p>
                ) : null}
                <p className="truncate text-sm text-ink-secondary">{email || '—'}</p>
              </div>
            </div>
            <span className="ac-member-menu-pill">{roleLabel}</span>
            <Link
              to="/profile"
              role="menuitem"
              className="ac-member-menu-link"
              onClick={() => setOpen(false)}
            >
              會員資料
            </Link>
            <div className="ac-member-menu-theme">
              <span className="text-sm font-semibold text-ink-secondary">外觀</span>
              <ThemeToggle compact />
            </div>
          </div>
          <div className="ac-account-menu-footer">
            <button
              type="button"
              role="menuitem"
              disabled={busy}
              onClick={handleLogout}
              className="ac-member-logout-btn"
            >
              {busy ? '登出中…' : '登出'}
            </button>
          </div>
        </div>
      ) : null}
    </div>
  )
}