import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Menu, Bell, MessageSquare, ChevronDown, User, KeyRound, LogOut } from 'lucide-react'
import { PasswordResetModal } from '@meshkee/dashboard-ui'
import { useAuth } from '../context/AuthContext'
import { changePassword } from '../services/profileService'
import styles from './Header.module.css'

export function Header() {
  const navigate = useNavigate()
  const { user, logout } = useAuth()
  const [menuOpen, setMenuOpen] = useState(false)
  const [passwordModalOpen, setPasswordModalOpen] = useState(false)
  const menuRef = useRef<HTMLDivElement>(null)

  const displayName =
    [user?.firstName, user?.lastName].filter(Boolean).join(' ') ||
    user?.cellNumber ||
    'Super Admin'

  useEffect(() => {
    if (!menuOpen) return

    function handleClickOutside(e: MouseEvent) {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setMenuOpen(false)
      }
    }

    function handleEscape(e: KeyboardEvent) {
      if (e.key === 'Escape') setMenuOpen(false)
    }

    document.addEventListener('mousedown', handleClickOutside)
    document.addEventListener('keydown', handleEscape)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
      document.removeEventListener('keydown', handleEscape)
    }
  }, [menuOpen])

  function handleLogout() {
    logout()
    navigate('/login')
  }

  function openPasswordModal() {
    setMenuOpen(false)
    setPasswordModalOpen(true)
  }

  const profileMenuItems = [
    { icon: User, label: 'Profile', action: () => { setMenuOpen(false); navigate('/profile') } },
    { icon: KeyRound, label: 'Password reset', action: openPasswordModal },
    { icon: LogOut, label: 'Logout', action: handleLogout },
  ]

  return (
    <>
      <header className={styles.header}>
        <div className={styles.left}>
          <button className={styles.menuBtn} aria-label="Toggle menu">
            <Menu size={22} />
          </button>
          <h1 className={styles.title}>Super Admin Dashboard</h1>
        </div>

        <div className={styles.right}>
          <button className={styles.iconBtn} aria-label="Messages">
            <MessageSquare size={20} />
            <span className={styles.badge}>5</span>
          </button>

          <button className={styles.iconBtn} aria-label="Notifications">
            <Bell size={20} />
            <span className={styles.badge}>3</span>
          </button>

          <div className={styles.profileWrap} ref={menuRef}>
            <button
              type="button"
              className={styles.profile}
              data-card-hover
              data-card-hover-active={menuOpen ? 'true' : undefined}
              onClick={() => setMenuOpen((open) => !open)}
              aria-expanded={menuOpen}
              aria-haspopup="menu"
            >
              <div className={styles.profileInfo}>
                <span className={styles.name}>{displayName}</span>
                <span className={styles.role}>Super Administrator</span>
              </div>
              <ChevronDown
                size={16}
                className={`${styles.chevron} ${menuOpen ? styles.chevronOpen : ''}`}
              />
            </button>

            {menuOpen && (
              <div className={styles.dropdown} role="menu">
                {profileMenuItems.map(({ icon: Icon, label, action }) => (
                  <button
                    key={label}
                    type="button"
                    className={styles.dropdownItem}
                    role="menuitem"
                    onClick={action}
                  >
                    <Icon size={16} />
                    <span>{label}</span>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      </header>

      <PasswordResetModal
        open={passwordModalOpen}
        onClose={() => setPasswordModalOpen(false)}
        onChangePassword={changePassword}
      />
    </>
  )
}
