'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { Menu, ShoppingCart, User, X } from 'lucide-react'
import { useEffect, useState } from 'react'
import { useApp } from '@/components/providers/AppProvider'
import { BrandLogo } from '@/components/shared/BrandLogo'
import { BRAND_NAME } from '@/lib/brand'
import { backend, type BackendSiteConsultingDirection } from '@/lib/backend'

const nav = [
  { label: '首页', href: '/' },
  { label: '关于我们', href: '/about' },
  {
    label: '规划咨询',
    href: '/consulting',
  },
  { label: '新闻资讯', href: '/news' },
  { label: '活动报名', href: '/events' },
  {
    label: '产品服务',
    href: '/courses',
    children: [
      { label: '课程培训', href: '/courses' },
      { label: '智能体产品', href: '/agents' },
      { label: '数据服务', href: '/data' },
    ],
  },
  { label: '会员权益', href: '/membership' },
]

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

export function Header() {
  const pathname = usePathname()
  const [openMenu, setOpenMenu] = useState<string | null>(null)
  const [mobileOpen, setMobileOpen] = useState(false)
  const [consultingDirections, setConsultingDirections] = useState<BackendSiteConsultingDirection[]>([])
  const { cartCount, user } = useApp()
  const needsOnboarding = Boolean(user && !user.onboardingCompleted)
  const visibleCartCount = user && !needsOnboarding ? cartCount : 0
  const cartHref = needsOnboarding ? '/onboarding?redirect=%2Fcart' : '/cart'
  const accountHref = needsOnboarding ? '/onboarding?redirect=%2Faccount%2Fmembership' : '/account'
  const showExpertJoin = !user?.expertProfileStatus && (!user?.expertApplicationStatus || ['rejected', 'withdrawn'].includes(user.expertApplicationStatus))
  const showUtilityBar = !(pathname === '/account' || pathname.startsWith('/account/'))
  useEffect(() => {
    void backend.siteConsulting()
      .then((site) => setConsultingDirections(site.directions))
      .catch(() => setConsultingDirections([]))
  }, [])

  const dynamicNav = nav.map((item) => item.href === '/consulting'
    ? {
        ...item,
        children: consultingDirections.map((direction) => ({
          label: direction.title,
          href: `/consulting/${direction.slug}`,
        })),
      }
    : item)
  const navItems = [
    ...dynamicNav.slice(0, 4),
    {
      label: '专家平台',
      href: '/experts',
      children: [
        { label: '专家资源', href: '/experts' },
        ...(showExpertJoin ? [{ label: '加入我们', href: '/experts/join' }] : []),
      ],
    },
    ...dynamicNav.slice(4),
  ]

  if (pathname.startsWith('/admin') || pathname.startsWith('/staff')) return null

  return (
    <>
      {showUtilityBar && (
        <div className="hidden md:block bg-brand-dark text-white/65 text-xs">
          <div className="mx-auto flex h-9 max-w-[1280px] items-center justify-between px-6">
            <div className="flex items-center gap-2">
              <Link href="/about" className="hover:text-white">{BRAND_NAME}</Link>
              <span className="text-white/30">·</span>
              <Link href="/about#qualifications" className="hover:text-white">资质荣誉</Link>
              <span className="text-white/30">·</span>
              <Link href="/about#partners" className="hover:text-white">合作伙伴</Link>
            </div>
            <div className="flex items-center gap-5">
              <Link href="/about#contact" className="hover:text-white">联系我们</Link>
            </div>
          </div>
        </div>
      )}

      <header className="sticky top-0 z-50 border-b border-line bg-white">
        <div className="mx-auto flex h-[70px] max-w-[1280px] items-center px-6">
          <Link href="/" className="mr-8 flex shrink-0 items-center gap-3">
            <BrandLogo className="h-11 w-11 rounded-full" />
            <div className="leading-none">
              <div className="text-[15px] font-bold text-ink">{BRAND_NAME}</div>
            </div>
          </Link>

          <nav className="hidden h-full flex-1 items-center xl:flex">
            {navItems.map((item) => (
              <div
                key={item.label}
                className="relative flex h-full items-center"
                onMouseEnter={() => item.children && setOpenMenu(item.label)}
                onMouseLeave={() => setOpenMenu(null)}
              >
                <Link
                  href={item.href}
                  className={`relative flex h-full items-center px-3 text-sm transition-colors after:absolute after:bottom-0 after:left-3 after:right-3 after:h-0.5 after:origin-center after:bg-brand after:transition-transform ${
                    isActive(pathname, item.href)
                      ? 'font-bold text-brand after:scale-x-100'
                      : 'text-text-body after:scale-x-0 hover:text-brand hover:after:scale-x-100'
                  }`}
                >
                  {item.label}
                </Link>
                {item.children && openMenu === item.label && (
                  <div className="absolute left-0 top-full min-w-36 border border-line bg-white py-1 shadow-[0_12px_32px_rgba(0,0,0,0.10)]">
                    {item.children.map((child) => (
                      <Link
                        key={child.href}
                        href={child.href}
                        className="block whitespace-nowrap px-4 py-2 text-[13px] text-text-body hover:bg-brand-light hover:text-brand"
                      >
                        {child.label}
                      </Link>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </nav>

          <div className="ml-auto hidden items-center gap-4 xl:flex">
            {user ? (
              <>
                <Link href={cartHref} className="relative inline-flex items-center gap-1.5 text-[13px] text-muted hover:text-brand">
                  <ShoppingCart className="h-4 w-4" />
                  购物车
                  {visibleCartCount > 0 && (
                    <span className="absolute -right-2 -top-1.5 h-2 w-2 rounded-full bg-brand" aria-label="购物车有商品" />
                  )}
                </Link>
                <Link href={accountHref} className="inline-flex items-center gap-1.5 text-[13px] text-muted hover:text-brand">
                  <User className="h-4 w-4" />
                  个人中心
                </Link>
              </>
            ) : (
              <Link href="/login" className="inline-flex items-center gap-1.5 bg-brand px-5 py-2 text-[13px] font-bold text-white hover:bg-brand-dark">
                <User className="h-4 w-4" />
                注册登录
              </Link>
            )}
          </div>

          <button
            type="button"
            className="ml-auto grid h-10 w-10 place-items-center border border-line text-text-body xl:hidden"
            onClick={() => setMobileOpen((value) => !value)}
            aria-label="打开导航菜单"
          >
            {mobileOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
          </button>
        </div>

        {mobileOpen && (
          <div className="border-t border-line bg-white xl:hidden">
            <div className="mx-auto max-w-[1280px] px-6 py-3">
              {navItems.map((item) => (
                <div key={item.label} className="border-b border-line last:border-b-0">
                  <Link
                    href={item.href}
                    className="block py-3 text-sm font-medium text-ink"
                    onClick={() => setMobileOpen(false)}
                  >
                    {item.label}
                  </Link>
                  {item.children && (
                    <div className="grid grid-cols-2 gap-2 pb-3">
                      {item.children.map((child) => (
                        <Link
                          key={child.href}
                          href={child.href}
                          className="bg-bg px-3 py-2 text-xs text-text-body"
                          onClick={() => setMobileOpen(false)}
                        >
                          {child.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              ))}
              {user ? (
                <div className="mt-4 grid grid-cols-2 gap-3">
                  <Link href={cartHref} className="border border-line py-2 text-center text-sm" onClick={() => setMobileOpen(false)}>购物车</Link>
                  <Link href={accountHref} className="bg-brand py-2 text-center text-sm font-bold text-white" onClick={() => setMobileOpen(false)}>个人中心</Link>
                </div>
              ) : (
                <div className="mt-4 grid gap-3">
                  <Link href="/login" className="block bg-brand py-2 text-center text-sm font-bold text-white" onClick={() => setMobileOpen(false)}>注册登录</Link>
                </div>
              )}
            </div>
          </div>
        )}
      </header>

    </>
  )
}
