import React, { useEffect, useState } from 'react'

import Button from '../../../Button/Button'
import Icon from '../../../Icons/Icon'
import { SideDrawer } from '../../../SideDrawer/SideDrawer'
import { type RouteConfig } from '../RouterTabs'
import MobileTabsOptions, {
  type MobileTabsOptionsProps,
} from '../../MobileTabs/MobileTabsOptions'
import styles from '../../MobileTabs/_mobile-tabs.module.scss'
import { c } from '../../../../translations/LibraryTranslationService'

type MobileRouterTabsProps = {
  /** Array of the RouteConfig object. Needed to render the tab options for mobile. */
  mobileConfig: RouteConfig[]
  navigate: MobileTabsOptionsProps['navigate']
  /** Current path from the router */
  currentPath: string
  /** Optional prop to add a test id to the MobileRouterTabs for QA testing */
  qaTestId?: string
}

const MobileRouterTabs = ({
  mobileConfig,
  navigate,
  currentPath,
  qaTestId,
}: MobileRouterTabsProps): React.JSX.Element => {
  const [active, setActive] = useState(mobileConfig[0].label)
  const [display, setDisplay] = useState(mobileConfig[0].label)
  const [isDrawerOpen, setIsDrawerOpen] = React.useState(false)

  useEffect(() => {
    mobileConfig.forEach((mc) => {
      if (mc.link === currentPath) {
        setActive(mc.label)
        setDisplay(mc.label)
      }

      if (mc.link === currentPath && mc.subrows) {
        setActive(mc.subrows[0]?.label)
        setDisplay(`${mc.label} > ${mc.subrows[0]?.label}`)
      }
      if (mc.link !== currentPath && mc.subrows) {
        mc.subrows.forEach((sub) => {
          if (sub.link === currentPath) {
            setActive(sub.label)
            setDisplay(`${mc.label} > ${sub.label}`)
          }
        })
      }
    })
  }, [mobileConfig, active, currentPath])

  return (
    <>
      <Button
        onClick={() => setIsDrawerOpen(true)}
        className={styles.selectContainer}
        as='unstyled'
        qa-test-id={`${qaTestId}-button`}
      >
        <div className={styles.mobileTabsSelect}>
          <span>{display}</span>
          <Icon icon='carat' iconSize='8px' />
        </div>
      </Button>
      <SideDrawer
        isOpen={isDrawerOpen}
        closeCallout={() => setIsDrawerOpen(false)}
        headerContent={c('selectATab')}
        qaTestId={`${qaTestId}-drawer`}
      >
        <MobileTabsOptions
          mobileConfig={mobileConfig}
          active={active}
          setActive={setActive}
          navigate={navigate}
          currentPath={currentPath}
          drawerCloseCallout={setIsDrawerOpen}
        />
      </SideDrawer>
    </>
  )
}

export default MobileRouterTabs
