import { useEffect, useState } from 'react'
import { NavLink, useLocation, useNavigate } from 'react-router-dom'
import { PLACEMENT_FLOW, isPlacementFlowPath, placementFlowPath, topicIdFromSearch } from '../lib/placementFlow'
import { getActiveTopicId } from '../lib/brandContext'
import { onboardingGlowClass, onboardingNavApps, shouldGlowNav } from '../lib/onboarding'
import { useAuth } from '../auth/AuthContext'
import { isAdminMember } from '../lib/memberRole'
import { useOnboarding } from '../onboarding/OnboardingContext'
import { AcIcon } from './AcIcon'

const fullMobileTabs = [
  { to: '/matrix', label: '拷貝', icon: 'jobs' as const, matchPrefix: '/matrix' },
  { to: '/placement/topics', label: '找TA', icon: 'threads' as const, matchPrefix: '/placement' },
] as const

const onboardingMobileTabs = [
  { to: '/personas', label: '人設', icon: 'persona' as const, matchPrefix: '/personas' },
  { to: '/settings', label: '設定', icon: 'settings' as const },
] as const

function isMoreActive(pathname: string, routes: { to: string }[]) {
  return routes.some((r) => pathname === r.to || pathname.startsWith(`${r.to}/`))
}

export function MobileBottomNav() {
  const { member } = useAuth()
  const { isComplete, nextStep } = useOnboarding()
  const [moreOpen, setMoreOpen] = useState(false)
  const location = useLocation()
  const navigate = useNavigate()
  const isAdmin = isAdminMember(member)
  const mobileTabs = isComplete ? fullMobileTabs : onboardingMobileTabs
  const navApps = onboardingNavApps(isComplete, isAdmin)
  const moreRoutes = navApps.filter((n) => !mobileTabs.some((t) => t.to === n.to))
  const activeTopicId = topicIdFromSearch(location.search) || getActiveTopicId()
  const resolveTo = (to: string) =>
    isPlacementFlowPath(to) ? placementFlowPath(to, activeTopicId) : to
  useEffect(() => {
    setMoreOpen(false)
  }, [location.pathname])

  useEffect(() => {
    if (!moreOpen) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setMoreOpen(false)
    }
    document.addEventListener('keydown', onKey)
    document.body.style.overflow = 'hidden'
    return () => {
      document.removeEventListener('keydown', onKey)
      document.body.style.overflow = ''
    }
  }, [moreOpen])

  const goMore = (to: string) => {
    setMoreOpen(false)
    navigate(resolveTo(to))
  }

  return (
    <>
      <nav className="ac-dock mobile-bottom-nav fixed inset-x-0 bottom-0 z-30 lg:hidden" aria-label="主要導覽">
        <div
          className={`mx-auto grid max-w-lg px-2 pt-1 ${isComplete ? 'grid-cols-3' : 'grid-cols-2'}`}
        >
          {mobileTabs.map((tab) => {
            const guideGlow = shouldGlowNav(nextStep, tab.to, location.pathname)
            return (
              <NavLink
                key={tab.to}
                to={resolveTo(tab.to)}
                end={'end' in tab ? !!(tab as { end?: boolean }).end : false}
                className={({ isActive }) => {
                  const prefixActive =
                    'matchPrefix' in tab && location.pathname.startsWith(tab.matchPrefix)
                  const findTAActive =
                    tab.to === '/placement/topics' && isPlacementFlowPath(location.pathname)
                  const active = isActive || prefixActive || findTAActive
                  return `ac-dock-btn relative flex min-h-[3.5rem] flex-col items-center justify-center gap-1 py-2 text-center text-[11px] font-semibold ${
                    active ? 'ac-dock-btn--active' : ''
                  } ${onboardingGlowClass(guideGlow)}`
                }}
              >
                {guideGlow ? (
                  <span className="hx-guide-badge" aria-hidden>
                    下一步
                  </span>
                ) : null}
                <AcIcon app={tab.icon} size="sm" />
                <span>{tab.label}</span>
              </NavLink>
            )
          })}
          {isComplete ? (
            <button
              type="button"
              onClick={() => setMoreOpen(true)}
              className={`ac-dock-btn flex min-h-[3.5rem] flex-col items-center justify-center gap-1 py-2 text-center text-[11px] font-semibold ${
                isMoreActive(location.pathname, moreRoutes) ? 'ac-dock-btn--active' : ''
              }`}
              aria-expanded={moreOpen}
              aria-haspopup="dialog"
            >
              <AcIcon app="more" size="sm" />
              <span>更多</span>
            </button>
          ) : null}
        </div>
      </nav>

      {isComplete && moreOpen ? (
        <div className="fixed inset-0 z-40 lg:hidden" role="presentation">
          <button
            type="button"
            className="absolute inset-0 bg-ink/40"
            aria-label="關閉選單"
            onClick={() => setMoreOpen(false)}
          />
          <div
            role="dialog"
            aria-modal="true"
            aria-label="更多功能"
            className="mobile-more-sheet ac-dialog absolute inset-x-2 bottom-0 max-h-[min(85vh,34rem)] overflow-y-auto rounded-b-none"
          >
            <div className="ac-title-bar flex items-center justify-between">
              <span>更多</span>
              <button
                type="button"
                onClick={() => setMoreOpen(false)}
                className="ac-btn-secondary rounded-[var(--radius-pill)] px-3 py-1 text-xs"
              >
                關閉
              </button>
            </div>

            <div className="border-b border-border/60 px-4 pb-3 pt-1">
              <p className="mb-2 text-[10px] font-bold tracking-[0.12em] text-brand uppercase">找 TA 子步驟</p>
              <div className="grid grid-cols-3 gap-2">
                {PLACEMENT_FLOW.map((step) => {
                  const active = location.pathname === step.path || location.pathname.startsWith(`${step.path}/`)
                  return (
                    <button
                      key={step.path}
                      type="button"
                      onClick={() => goMore(step.path)}
                      className={`ac-app-tile text-left ${active ? 'ac-app-tile--active' : ''}`}
                    >
                      <span className="text-[10px] font-bold text-brand">{step.step}</span>
                      <span className="text-xs leading-snug">{step.shortLabel}</span>
                    </button>
                  )
                })}
              </div>
            </div>

            <div className="grid grid-cols-3 gap-2 p-4">
              {moreRoutes.map((item) => {
                const active = location.pathname === item.to
                return (
                  <button
                    key={item.to}
                    type="button"
                    onClick={() => goMore(item.to)}
                    className={`ac-app-tile ${active ? 'ac-app-tile--active' : ''}`}
                  >
                    <AcIcon app={item.icon} size="md" />
                    <span>{item.label}</span>
                  </button>
                )
              })}
            </div>
          </div>
        </div>
      ) : null}
    </>
  )
}