import { useEffect, useMemo, useState } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { AnimatePresence, motion } from 'framer-motion'
import { Building2, Globe, Menu, X } from 'lucide-react'
import { COMPANY_INFO, NAVIGATION_MENU } from '../lib/constants'
import {
  DEFAULT_LOCALE,
  getLocaleFromPathname,
  stripLocalePrefix,
  toOppositeLocale,
  withLocalePath,
} from '../lib/i18n'

type NavLabel = {
  zh: string
  en: string
}

const navLabelMap: Record<string, NavLabel> = {
  home: { zh: '首页', en: 'Home' },
  about: { zh: '集团概况', en: 'About' },
  scope: { zh: '服务范围', en: 'Services' },
  cases: { zh: '服务案例', en: 'Cases' },
  news: { zh: '新闻中心', en: 'News' },
  learning: { zh: '培训学习', en: 'Learning' },
  assistant: { zh: 'AI智能助手', en: 'AI Assistant' },
  contact: { zh: '联系我们', en: 'Contact' },
}

export const Header: React.FC = () => {
  const [isScrolled, setIsScrolled] = useState(false)
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
  const location = useLocation()
  const navigate = useNavigate()

  const locale = useMemo(() => getLocaleFromPathname(location.pathname), [location.pathname])

  useEffect(() => {
    const handleScroll = () => setIsScrolled(window.scrollY > 20)
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  useEffect(() => {
    setIsMobileMenuOpen(false)
  }, [location.pathname])

  const navItems = useMemo(
    () =>
      NAVIGATION_MENU.map((item) => ({
        ...item,
        label: locale === 'en' ? navLabelMap[item.id]?.en ?? item.label : navLabelMap[item.id]?.zh ?? item.label,
        to: withLocalePath(locale, item.path),
      })),
    [locale],
  )

  const isActive = (to: string) => {
    const current = stripLocalePrefix(location.pathname)
    const target = stripLocalePrefix(to)
    if (target === '/') return current === '/'
    return current.startsWith(target)
  }

  const handleToggleLocale = () => {
    const next = toOppositeLocale(locale)
    const nextPath = withLocalePath(next, stripLocalePrefix(location.pathname))

    try {
      localStorage.setItem('preferredLocale', next)
    } catch {
      // ignore
    }

    navigate(nextPath)
  }

  useEffect(() => {
    if (getLocaleFromPathname(location.pathname) !== DEFAULT_LOCALE) return

    try {
      const preferred = localStorage.getItem('preferredLocale')
      if (preferred === 'en') {
        navigate(withLocalePath('en', stripLocalePrefix(location.pathname)), { replace: true })
      }
    } catch {
      // ignore
    }
  }, [location.pathname, navigate])

  return (
    <motion.header
      className={`fixed left-0 right-0 z-50 transition-all duration-300 border-b ${
        isScrolled ? 'top-0 bg-white/90 shadow-sm border-gray-100' : 'top-0 bg-white/70 border-transparent'
      }`}
      style={{
        backdropFilter: 'blur(16px) saturate(140%)',
        WebkitBackdropFilter: 'blur(16px) saturate(140%)',
      }}
      initial={{ y: -24, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      transition={{ duration: 0.25 }}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          <Link
            to={withLocalePath(locale, '/')}
            className="flex items-center gap-3"
            aria-label={locale === 'en' ? 'Go to homepage' : '返回首页'}
          >
            <div className="flex items-center justify-center w-10 h-10 rounded-lg bg-primary text-white">
              <Building2 size={22} />
            </div>
            <div className="hidden sm:block">
              <div className="text-base font-semibold text-primary-dark leading-tight">
                {locale === 'en' ? COMPANY_INFO.nameEn : COMPANY_INFO.name}
              </div>
              <div className="text-[11px] tracking-wider text-gray-500">{COMPANY_INFO.nameEn.toUpperCase()}</div>
            </div>
          </Link>

          <nav className="hidden lg:flex items-center gap-1" aria-label={locale === 'en' ? 'Main navigation' : '主导航'}>
            {navItems.map((item) => (
              <Link
                key={item.id}
                to={item.to}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                  isActive(item.to) ? 'text-primary bg-primary/5' : 'text-gray-700 hover:bg-gray-50 hover:text-primary'
                }`}
                aria-current={isActive(item.to) ? 'page' : undefined}
              >
                {item.label}
              </Link>
            ))}
          </nav>

          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={handleToggleLocale}
              className="hidden md:inline-flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-gray-700 hover:bg-gray-50"
              aria-label={locale === 'en' ? 'Switch language' : '切换语言'}
            >
              <Globe size={16} />
              <span>{locale === 'en' ? '中文' : 'English'}</span>
            </button>

            <button
              type="button"
              onClick={() => setIsMobileMenuOpen((v) => !v)}
              className="lg:hidden inline-flex items-center justify-center w-10 h-10 rounded-lg text-gray-700 hover:bg-gray-50"
              aria-label={isMobileMenuOpen ? (locale === 'en' ? 'Close menu' : '关闭菜单') : locale === 'en' ? 'Open menu' : '打开菜单'}
              aria-expanded={isMobileMenuOpen}
            >
              {isMobileMenuOpen ? <X size={20} /> : <Menu size={20} />}
            </button>
          </div>
        </div>
      </div>

      <AnimatePresence>
        {isMobileMenuOpen && (
          <motion.nav
            className="lg:hidden border-t border-gray-100 bg-white/95"
            style={{
              backdropFilter: 'blur(16px) saturate(140%)',
              WebkitBackdropFilter: 'blur(16px) saturate(140%)',
            }}
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.2 }}
            aria-label={locale === 'en' ? 'Mobile navigation' : '移动端导航'}
          >
            <div className="px-4 py-4 space-y-2">
              {navItems.map((item) => (
                <Link
                  key={item.id}
                  to={item.to}
                  className={`block px-4 py-3 rounded-xl text-sm font-medium transition-colors ${
                    isActive(item.to) ? 'bg-primary/5 text-primary' : 'text-gray-700 hover:bg-gray-50'
                  }`}
                  aria-current={isActive(item.to) ? 'page' : undefined}
                >
                  {item.label}
                </Link>
              ))}

              <button
                type="button"
                onClick={handleToggleLocale}
                className="w-full mt-2 flex items-center justify-between px-4 py-3 rounded-xl text-sm font-medium text-gray-700 hover:bg-gray-50"
              >
                <span>{locale === 'en' ? 'Language' : '语言'}</span>
                <span className="text-gray-500">{locale === 'en' ? '中文' : 'English'}</span>
              </button>
            </div>
          </motion.nav>
        )}
      </AnimatePresence>
    </motion.header>
  )
}

export default Header
