import * as React from 'react'

import { useMediaQuery } from '../../../hooks/responsiveHooks'
import { type MobileTabsOptionsProps } from '../MobileTabs/MobileTabsOptions'
import MobileRouterTabs from './Mobile/MobileRouterTabs'
import DesktopRouterTabsNew from './Desktop/DesktopRouterTabsNew'

type BaseRouteConfig = {
  /** The label that will display for the link label */
  label: string
  /** The route link */
  link: string
}

export type RouteConfig = BaseRouteConfig & {
  /** Array of the BaseRouteConfig objects. Object includes label and link. */
  subrows?: BaseRouteConfig[]
}

type RouterTabsBaseProps = {
  /** Multiple children. Typically in the form of NavLink components */
  children: React.ReactNode[]
  /** Determines the style of the tabs. If true, the subtabs style will be applied. */
  subtabs?: boolean
  /** Current path from the router */
  currentPath: string
  /** Refresh router tab animation */
  refreshRouterTabs?: boolean
  /** Optional prop to add a test id to the RouterTabs for QA testing */
  qaTestId?: string
}

type RouterTabsWithMobile = RouterTabsBaseProps & {
  /** Array of the RouteConfig object. Needed to render the tab options for mobile. */
  mobileConfig: RouteConfig[]
  /** Pass in a navigate function (useHistory, useNavigate, or other functions) depending on the router the app is using. */
  navigate: MobileTabsOptionsProps['navigate']
}

type RouterTabsWithoutMobile = RouterTabsBaseProps & {
  mobileConfig?: never
  navigate?: never
}

export type RouterTabsProps = RouterTabsWithMobile | RouterTabsWithoutMobile

export default function RouterTabs({
  children,
  subtabs = false,
  mobileConfig,
  navigate,
  currentPath,
  refreshRouterTabs = false,
  qaTestId = 'router-tabs',
}: RouterTabsProps): React.JSX.Element {
  const isMobile = useMediaQuery({ type: 'max', breakpoint: 'md' })

  if (isMobile && mobileConfig) {
    return (
      <MobileRouterTabs
        mobileConfig={mobileConfig}
        navigate={navigate}
        currentPath={currentPath}
        qaTestId={`${qaTestId}-mobile`}
      />
    )
  }

  if (isMobile && subtabs) {
    return <></>
  }

  return (
    <DesktopRouterTabsNew
      subtabs={subtabs}
      currentPath={currentPath}
      refreshRouterTabs={refreshRouterTabs}
      qaTestId={qaTestId}
    >
      {children}
    </DesktopRouterTabsNew>
  )
}
