import { Link, useLocation } from 'react-router-dom'
import { useEffect, useState } from 'react'
import './Navbar.scss'
import * as DropdownMenu from '@radix-ui/react-dropdown-menu'
import { ChevronDown, LogOut, Menu, Moon, Pencil, Sun, UserRound } from 'lucide-react'
import type { Employee } from '../../entities/employee/model/types'
import { useTheme } from '../../shared/theme/useTheme'
import {
  useDeferredModalPayload,
} from '../../shared/lib/lazyMount'
import { AddEmployeeModal } from '../../pages/EmployeesPage/components/AddEmployeeModal/AddEmployeeModal'
import { authService } from '../../features/auth/api/authService'
import {
  getEmployeeFullName,
  getEmployeeRoleLabel,
} from '../../pages/EmployeesPage/lib/employeeFormatters'

function getPageTitle(location: ReturnType<typeof useLocation>) {
  const { pathname } = location

  if (pathname === '/machines' || pathname.startsWith('/machines/')) return 'Парк АТТ'
  if (pathname === '/users' || pathname === '/employees') return 'Пользователи'

  return 'Парк АТТ'
}

function getPageTitleLink(location: ReturnType<typeof useLocation>) {
  const { pathname } = location

  if (pathname.startsWith('/machines/')) return '/machines'
  if (pathname === '/employees') return '/users'

  return undefined
}

async function handleLogout() {
  authService.logout()
}

type NavbarProps = {
  breadcrumbs?: NavbarBreadcrumb[]
  isScrolled?: boolean
  onOpenSidebar?: () => void
}

export type NavbarBreadcrumb = {
  label: string
  to?: string
}

export function Navbar({
  breadcrumbs = [],
  isScrolled = false,
  onOpenSidebar,
}: NavbarProps) {
  const { isDark, toggleTheme } = useTheme()
  const [currentUser, setCurrentUser] = useState<Employee | null>(null)

  useEffect(() => {
    let isMounted = true

    async function syncCurrentUser() {
      const user = await authService.getCurrentUser()

      if (isMounted) {
        setCurrentUser(user)
      }
    }

    syncCurrentUser()

    window.addEventListener('auth:change', syncCurrentUser)
    window.addEventListener('users:change', syncCurrentUser)

    return () => {
      isMounted = false
      window.removeEventListener('auth:change', syncCurrentUser)
      window.removeEventListener('users:change', syncCurrentUser)
    }
  }, [])

  const location = useLocation()
  const title = getPageTitle(location)
  const titleLink = getPageTitleLink(location)
  const [editingEmployee, setEditingEmployee] = useState<Employee | null>(null)
  const renderEditingEmployee = useDeferredModalPayload(editingEmployee)
  const userRole = getEmployeeRoleLabel(currentUser?.role ?? 'ADMIN')
  const currentUserName = currentUser ? getEmployeeFullName(currentUser) : ''
  const currentUserLogin = currentUser?.login ?? currentUser?.username ?? ''

  return (
    <header className={`navbar ${isScrolled ? 'navbar--scrolled' : ''}`}>
      <div className="back-navbar"></div>
      <div className="navbar-content">
        <div className="navbar__main">
          <button
            className="navbar__icon-btn navbar__menu-btn"
            type="button"
            aria-label="Открыть меню"
            onClick={onOpenSidebar}
          >
            <Menu size={20} />
          </button>

          <h1>
            {titleLink ? (
              <Link className="navbar__title-link" to={titleLink}>
                {title}
              </Link>
            ) : (
              <span className="navbar__title-text">{title}</span>
            )}
            {breadcrumbs.length > 0 && (
              <nav className="navbar-breadcrumbs" aria-label="Хлебные крошки">
                {breadcrumbs.map((breadcrumb) => (
                  <span className="navbar-breadcrumbs__item" key={breadcrumb.label}>
                    <span className="navbar-breadcrumbs__separator">/</span>

                    {breadcrumb.to ? (
                      <Link to={breadcrumb.to}>{breadcrumb.label}</Link>
                    ) : (
                      <span>{breadcrumb.label}</span>
                    )}
                  </span>
                ))}
              </nav>
            )}
          </h1>
        </div>

        <div className="navbar__actions">
          <button
            className={`navbar__theme-button ${isDark ? 'is-dark' : 'is-light'}`}
            type="button"
            aria-label={isDark ? 'Включить светлую тему' : 'Включить тёмную тему'}
            aria-pressed={isDark}
            onClick={(event) => toggleTheme(event.currentTarget)}
          >
            {isDark ? <Moon size={17} /> : <Sun size={17} />}
          </button>

          <DropdownMenu.Root>
            <DropdownMenu.Trigger asChild>
              <button className="navbar-user" type="button">
                <span className="navbar-user__avatar">
                  {currentUser?.avatarUrl ? (
                    <img src={currentUser.avatarUrl} alt={currentUserName} />
                  ) : (
                    <UserRound size={22} />
                  )}
                </span>

                <span className="navbar-user__role">
                  {currentUserName || 'Пользователь'}
                </span>

                <ChevronDown className="navbar-user__chevron" size={16} />
              </button>
            </DropdownMenu.Trigger>

            <DropdownMenu.Portal>
              <DropdownMenu.Content
                className="navbar-dropdown"
                align="end"
                sideOffset={8}
              >
                <div className="navbar-dropdown__user">
                  <span>Имя пользователя</span>
                  <b>@{currentUserLogin || 'user'}</b>
                </div>
                <div className="navbar-dropdown__user">
                  <span>Текущая роль</span>
                  <b>{userRole}</b>
                </div>
                <DropdownMenu.Item
                  className="navbar-dropdown__item"
                  onSelect={() => {
                    if (!currentUser) return

                    setEditingEmployee(currentUser)
                  }}
                >
                  <Pencil size={16} />
                  Редактировать профиль
                </DropdownMenu.Item>

                <DropdownMenu.Separator className="navbar-dropdown__separator" />

                <DropdownMenu.Item
                  className="navbar-dropdown__item navbar-dropdown__item--danger"
                  onSelect={handleLogout}
                >
                  <LogOut size={16} />
                  Выйти
                </DropdownMenu.Item>
              </DropdownMenu.Content>
            </DropdownMenu.Portal>
          </DropdownMenu.Root>
        </div>

        <AddEmployeeModal
          open={Boolean(editingEmployee)}
          mode="edit"
          employee={editingEmployee ?? renderEditingEmployee}
          canChangeRole={authService.isAdmin(currentUser)}
          onOpenChange={(open) => {
            if (!open) {
              setEditingEmployee(null)
            }
          }}
          onSuccess={async () => {
            setCurrentUser(await authService.getCurrentUser())
          }}
        />
      </div>
    </header>
  )
}
