'use client'

import React, { useState } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { usePathname } from 'next/navigation'
import { motion, AnimatePresence, useReducedMotion } from 'framer-motion'
import { useSession, signOut } from 'next-auth/react'
import { Button } from '@/components/ui'
import './NavBar.css'

const NAV_LINKS = [
  { href: '/spots', label: 'Spots' },
  { href: '/mapa', label: 'Mapa' },
  { href: '/zonas-anac', label: 'Zonas ANAC' },
  { href: '/notams', label: 'NOTAMs' },
  { href: '/comunidade', label: 'Comunidade' },
] as const

export function NavBar() {
  const pathname = usePathname()
  const shouldReduceMotion = useReducedMotion()
  const [mobileOpen, setMobileOpen] = useState(false)
  const { data: session, status } = useSession()
  const isLoggedIn = status === 'authenticated'
  const userName = session?.user?.name ?? session?.user?.email ?? 'Piloto'

  const navbarMotion = shouldReduceMotion
    ? { initial: { opacity: 1, y: 0 }, animate: { opacity: 1, y: 0 } }
    : {
        initial: { y: -80, opacity: 0 },
        animate: { y: 0, opacity: 1 },
        transition: { duration: 0.4, ease: [0.22, 0.61, 0.36, 1] },
      }

  const drawerMotion = shouldReduceMotion
    ? { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } }
    : {
        initial: { x: '100%' },
        animate: { x: 0 },
        exit: { x: '100%' },
        transition: { duration: 0.28, ease: [0.22, 0.61, 0.36, 1] },
      }

  const backdropMotion = shouldReduceMotion
    ? { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } }
    : { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 }, transition: { duration: 0.2 } }

  function isActive(href: string) {
    if (href === '/') return pathname === '/'
    return pathname.startsWith(href)
  }

  return (
    <>
      <motion.header className="ov-navbar" role="banner" {...navbarMotion}>
        <div className="ov-navbar__inner">
          {/* Logo */}
          <Link href="/" className="ov-navbar__logo" aria-label="OndeVoar.pt — Início">
            <Image
              src="/brand/png/ondevoar-logo-lockup-navy-hires.png"
              alt="OndeVoar.pt"
              width={208}
              height={54}
              priority
            />
          </Link>

          {/* Desktop nav links */}
          <nav className="ov-navbar__nav" aria-label="Navegação principal">
            <ul className="ov-navbar__links" role="list">
              {NAV_LINKS.map(({ href, label }) => (
                <li key={href}>
                  <Link
                    href={href}
                    className="ov-navbar__link"
                    aria-current={isActive(href) ? 'page' : undefined}
                    data-active={isActive(href) ? 'true' : undefined}
                  >
                    {label}
                  </Link>
                </li>
              ))}
            </ul>
          </nav>

          {/* Auth actions */}
          <div className="ov-navbar__actions">
            {isLoggedIn ? (
              <>
                <Link href="/perfil" className="ov-navbar__user">
                  <span className="ov-navbar__user-avatar" aria-hidden="true">
                    {userName.charAt(0).toUpperCase()}
                  </span>
                  <span className="ov-navbar__user-name">{userName.split(' ')[0]}</span>
                </Link>
                <Button variant="ghost" size="sm" onClick={() => signOut({ callbackUrl: '/' })}>
                  Sair
                </Button>
              </>
            ) : (
              <>
                <Button variant="ghost" size="sm" href="/auth/login">
                  Entrar
                </Button>
                <Button variant="primary" size="sm" href="/auth/register">
                  Registar
                </Button>
              </>
            )}
          </div>

          {/* Hamburger toggle (mobile) */}
          <button
            className="ov-navbar__hamburger"
            aria-label={mobileOpen ? 'Fechar menu' : 'Abrir menu'}
            aria-expanded={mobileOpen}
            aria-controls="ov-mobile-drawer"
            onClick={() => setMobileOpen((v) => !v)}
          >
            <span className="ov-navbar__hamburger-icon" data-open={mobileOpen ? 'true' : 'false'} aria-hidden="true">
              <span />
              <span />
              <span />
            </span>
          </button>
        </div>
      </motion.header>

      {/* Mobile drawer */}
      <AnimatePresence>
        {mobileOpen && (
          <>
            {/* Backdrop */}
            <motion.div
              className="ov-navbar__backdrop"
              aria-hidden="true"
              onClick={() => setMobileOpen(false)}
              {...backdropMotion}
            />

            {/* Drawer panel */}
            <motion.div
              id="ov-mobile-drawer"
              className="ov-navbar__drawer"
              role="dialog"
              aria-label="Menu de navegação"
              {...drawerMotion}
            >
              <nav aria-label="Navegação móvel">
                <ul className="ov-navbar__drawer-links" role="list">
                  {NAV_LINKS.map(({ href, label }) => (
                    <li key={href}>
                      <Link
                        href={href}
                        className="ov-navbar__drawer-link"
                        data-active={isActive(href) ? 'true' : undefined}
                        onClick={() => setMobileOpen(false)}
                      >
                        {label}
                      </Link>
                    </li>
                  ))}
                </ul>
              </nav>

              <div className="ov-navbar__drawer-actions">
                {isLoggedIn ? (
                  <>
                    <Link href="/perfil" className="ov-navbar__drawer-user" onClick={() => setMobileOpen(false)}>
                      <span className="ov-navbar__user-avatar" aria-hidden="true">
                        {userName.charAt(0).toUpperCase()}
                      </span>
                      <span>{userName.split(' ')[0]}</span>
                    </Link>
                    <Button variant="ghost" onClick={() => { setMobileOpen(false); signOut({ callbackUrl: '/' }) }}>
                      Sair
                    </Button>
                  </>
                ) : (
                  <>
                    <Button variant="ghost" href="/auth/login" onClick={() => setMobileOpen(false)}>
                      Entrar
                    </Button>
                    <Button variant="primary" href="/auth/register" onClick={() => setMobileOpen(false)}>
                      Registar
                    </Button>
                  </>
                )}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  )
}
