'use client'

import React from 'react'
import { SvgTaillessLineArrowDown1 } from '@chainlink/blocks-icons'
import { cn } from '../../../../../utils'
import type {
  NavItemAction,
  NavItemAnchor,
  NavParent,
  NavEntry as NavEntryType,
} from '../../config'
import { LevelStateContext, LevelStateContextProvider } from '../../context'
import { useNavConfig } from '../../context/NavConfig'
import styles from '../../styles.module.css'
import { NavListAction, NavListAnchor } from '../List'
import { NavEntry } from '../Primitives'
import { NavLevel2 } from './NavLevel2'

export function NavLevel1Action({
  entry,
  after,
}: {
  entry: NavItemAction
  after?: React.ReactNode
}) {
  return <NavListAction entry={entry} after={after} showIcon />
}

export function NavLevel1Anchor({ entry }: { entry: NavItemAnchor }) {
  const { linkComponent } = useNavConfig()

  return <NavListAnchor entry={entry} showIcon linkComponent={linkComponent} />
}

function NavLevel1Parent({ entry }: { entry: NavParent }) {
  const { expandedParent, toggleParent, navHighlight } =
    React.useContext(LevelStateContext)
  const isExpandedParent = expandedParent === entry.label
  const onClick = () => toggleParent(entry.label)

  return (
    <div className="flex flex-col" data-menu-parent={entry.label}>
      <NavLevel1Action
        entry={{ ...entry, onClick }}
        after={
          <SvgTaillessLineArrowDown1
            color="platform-navigation-muted-more"
            className={cn(
              'transition-transform duration-200',
              isExpandedParent ? '-rotate-180' : 'rotate-0',
            )}
          />
        }
      />
      <LevelStateContextProvider navHighlight={navHighlight?.slice(1)}>
        <NavLevel2 entries={entry.items} isExpandedParent={isExpandedParent} />
      </LevelStateContextProvider>
    </div>
  )
}

export function NavLevel1Entry({ entry }: { entry: NavEntryType }) {
  return (
    <NavEntry
      {...{
        entry,
        Anchor: NavLevel1Anchor,
        Action: NavLevel1Action,
        Parent: NavLevel1Parent,
      }}
    />
  )
}

export function NavLevel1({ entries }: { entries: NavEntryType[] }) {
  return (
    <ul
      className={cn(
        styles.navList,
        styles.navLevel1,
        'flex flex-col gap-4 md:ml-[unset]',
      )}
    >
      {entries.map((entry) => (
        <NavLevel1Entry entry={entry} key={entry.label} />
      ))}
    </ul>
  )
}
