import { Link, useLocation } from 'react-router-dom'
import { BrandSwitcher } from './BrandSwitcher'
import { TopicSwitcher } from './TopicSwitcher'
import {
  PLACEMENT_FLOW,
  detectPlacementFlowStep,
  placementFlowPath,
  type PlacementFlowStepKey,
} from '../lib/placementFlow'
import type { BrandData } from '../types/brand'
import type { PlacementTopicData } from '../types/placementTopic'

type TopicNavProps = {
  topicId: string
  topics: PlacementTopicData[]
  onTopicChange: (id: string) => void
  topicLoading?: boolean
  brandId?: never
  brands?: never
  onBrandChange?: never
  brandLoading?: never
}

type BrandNavProps = {
  brandId: string
  brands: BrandData[]
  onBrandChange: (id: string) => void
  brandLoading?: boolean
  topicId?: never
  topics?: never
  onTopicChange?: never
  topicLoading?: never
}

type Props = (TopicNavProps | BrandNavProps) & {
  active?: PlacementFlowStepKey
}

export function PlacementFlowNav(props: Props) {
  const { active } = props
  const { pathname } = useLocation()
  const current = active ?? detectPlacementFlowStep(pathname) ?? 'research'
  const topicMode = 'topics' in props && props.topics !== undefined

  const flowId = topicMode ? props.topicId : props.brandId
  const flowScope = topicMode ? 'topic' : 'brand'

  return (
    <nav className="ac-persona-flow-nav" aria-label="找 TA 工作流">
      <div className="ac-persona-flow-nav__head">
        <p className="display-en text-[10px] font-bold tracking-[0.16em] text-brand uppercase">
          找 TA
        </p>
        {topicMode ? (
          <TopicSwitcher
            topicId={props.topicId}
            topics={props.topics}
            onChange={props.onTopicChange}
            disabled={props.topicLoading}
          />
        ) : (
          <BrandSwitcher
            brandId={props.brandId}
            brands={props.brands}
            onChange={props.onBrandChange}
            disabled={props.brandLoading}
          />
        )}
      </div>
      <ol className="ac-persona-flow-nav__steps">
        {PLACEMENT_FLOW.map((step) => {
          const isActive = step.key === current
          return (
            <li key={step.key}>
              <Link
                to={placementFlowPath(step.path, flowId, flowScope)}
                className={`ac-persona-flow-nav__step ${isActive ? 'ac-persona-flow-nav__step--active' : ''}`}
                aria-current={isActive ? 'step' : undefined}
              >
                <span className="ac-persona-flow-nav__eyebrow">{step.step}</span>
                <span className="ac-persona-flow-nav__label">{step.shortLabel}</span>
              </Link>
            </li>
          )
        })}
      </ol>
    </nav>
  )
}