import { useEffect, useRef, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { Menu, Bell, MessageSquare, ChevronDown, User, KeyRound, LogOut, LayoutDashboard } from 'lucide-react'
import { LanguageSelect, PasswordResetModal, useLocale } from '@meshkee/dashboard-ui'
import { useAuth } from '../context/AuthContext'
import { useTenantBranding } from '../context/TenantBrandingContext'
import { useT } from '../i18n/useT'
import { getActiveBusinessId } from '../lib/businessContext'
import { getBusinessDashboardUrl } from '../lib/config'
import { changePassword } from '../services/authService'
import meshkeeLogo from '../assets/meshkee-logo.png'
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
}

interface HeaderProps {
  /** Hide the mobile sidebar hamburger (e.g. full-width flows without a sidebar). */
  hideMenu?: boolean
  /** Show website logo + name on the start side (visual right in RTL). */
  showBrand?: boolean
}

export function Header({ hideMenu = false, showBrand = false }: HeaderProps) {
  const navigate = useNavigate()
  const { user, logout } = useAuth()
  const { locale } = useLocale()
  const { businessName, businessNameEn, logoUrl } = useTenantBranding()
  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.role.customer'))
  const brandTitle = locale === 'en'
    ? businessNameEn || businessName
    : businessName || businessNameEn
  const brandSubtitle = locale === 'en'
    ? (businessName && businessName !== brandTitle ? businessName : '')
    : (businessNameEn && businessNameEn !== brandTitle ? businessNameEn : '')

  const activeBusinessId = getActiveBusinessId()
  const isSuperAdmin = Boolean(user?.isSuperAdmin || user?.roles.includes('super_admin'))
  const membership = user?.businesses.find(
    (business) => String(business.id) === String(activeBusinessId),
  )
  const adminBadgeLabel = isSuperAdmin
    ? t('app.role.superAdmin')
    : membership?.teamRole === 'admin'
      ? t('app.role.admin')
      : null
  const canOpenBusinessDashboard = Boolean(
    isSuperAdmin ||
      user?.businesses.some(
        (business) =>
          String(business.id) === String(activeBusinessId) &&
          (business.isOwner || Boolean(business.teamRole)),
      ),
  )

  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}>
          {showBrand ? (
            <div className={styles.brand}>
              <img
                src={logoUrl || meshkeeLogo}
                alt=""
                className={styles.brandLogo}
              />
              <div className={styles.brandText}>
                <span className={styles.brandTitle}>{brandTitle || t('app.storeFallback')}</span>
                {brandSubtitle ? (
                  <span className={styles.brandSubtitle}>{brandSubtitle}</span>
                ) : null}
              </div>
            </div>
          ) : !hideMenu ? (
            <button className={styles.menuBtn} aria-label={t('header.toggleMenu')}>
              <Menu size={22} />
            </button>
          ) : null}
        </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}>
            {canOpenBusinessDashboard ? (
              <a
                className={styles.businessDashBtn}
                href={getBusinessDashboardUrl()}
                target="_blank"
                rel="noopener noreferrer"
                aria-label={t('header.openBusinessDashboard')}
                title={t('header.openBusinessDashboard')}
              >
                <LayoutDashboard size={18} />
              </a>
            ) : null}
            <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>
                {adminBadgeLabel ? (
                  <span className={styles.roleBadge}>{adminBadgeLabel}</span>
                ) : null}
              </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.myProfile')}</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')}
      />
    </>
  )
}
