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

function displayUserName(
  user: {
    firstName: string | null
    lastName: string | null
    firstNameEn?: string | null
    lastNameEn?: string | null
    cellNumber: string
  } | null,
  locale: 'en' | 'fa',
  fallback: string,
) {
  if (!user) return fallback
  const localized =
    locale === 'en'
      ? [user.firstNameEn, user.lastNameEn].filter(Boolean).join(' ')
      : [user.firstName, user.lastName].filter(Boolean).join(' ')
  const other =
    locale === 'en'
      ? [user.firstName, user.lastName].filter(Boolean).join(' ')
      : [user.firstNameEn, user.lastNameEn].filter(Boolean).join(' ')
  return localized || other || user.cellNumber || fallback
}

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

  const displayName = displayUserName(user, locale, t('app.userFallback'))
  const roleLabel =
    user?.roleLabel ??
    (user?.isSuperAdmin || user?.roles.includes('super_admin')
      ? t('role.superAdmin')
      : user?.businesses[0]?.isOwner
        ? t('role.owner')
        : user?.businesses[0]?.teamRole ?? t('role.staff'))

  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()
    setMenuOpen(false)
    navigate('/login')
  }

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

  return (
    <>
      <header className={styles.header}>
        <div className={styles.left}>
          <button className={styles.menuBtn} aria-label={t('header.toggleMenu')}>
            <Menu size={22} />
          </button>
        </div>

        <div className={styles.right}>
          <LanguageSelect />

          <button className={styles.iconBtn} aria-label={t('header.messages')}>
            <MessageSquare size={20} />
            <span className={styles.badge}>0</span>
          </button>

          <button className={styles.iconBtn} aria-label={t('header.notifications')}>
            <Bell size={20} />
            <span className={styles.badge}>0</span>
          </button>

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

            {menuOpen && (
              <div className={styles.dropdown} role="menu">
                <Link
                  to="/profile"
                  className={styles.dropdownItem}
                  role="menuitem"
                  onClick={() => setMenuOpen(false)}
                >
                  <User size={16} />
                  <span>{t('header.profile')}</span>
                </Link>
                <Link
                  to="/settings"
                  className={styles.dropdownItem}
                  role="menuitem"
                  onClick={() => setMenuOpen(false)}
                >
                  <Settings size={16} />
                  <span>{t('header.setting')}</span>
                </Link>
                <button
                  type="button"
                  className={styles.dropdownItem}
                  role="menuitem"
                  onClick={openPasswordModal}
                >
                  <KeyRound size={16} />
                  <span>{t('header.changePassword')}</span>
                </button>
                <button
                  type="button"
                  className={styles.dropdownItem}
                  role="menuitem"
                  onClick={handleLogout}
                >
                  <LogOut size={16} />
                  <span>{t('nav.logout')}</span>
                </button>
              </div>
            )}
          </div>
        </div>
      </header>

      <PasswordResetModal
        open={passwordModalOpen}
        onClose={() => setPasswordModalOpen(false)}
        onChangePassword={changePassword}
        title={t('header.changePassword')}
      />
    </>
  )
}
