import { YStack, XStack, Button, H2, Paragraph, useThemeName } from '@junwon/aesthetics'
import { useRouterContext } from '../providers/RouterProvider'
import { JunwonIcon } from '@junwon/assets'
import { ArrowLeft } from '@tamagui/lucide-icons'
import { useEffect, useState } from 'react'

interface BackButtonProps {
  onPress: () => void
}

function BackButton({ onPress }: BackButtonProps) {
  return (
    <Button
      onPress={onPress}
      icon={<ArrowLeft size="$1" />}
      br="$10"
      p={0}
      w="$4"
      h="$4"
      bc="$gray2"
      pos="absolute"
      l={0}
    />
  )
}

interface ActionBarProps {
  showBackButtonAtRoot?: boolean
}

export function ActionBar({ showBackButtonAtRoot = false }: ActionBarProps) {
  const { route, pop, pageTitle, pageSubtitle } = useRouterContext()
  const shouldShowBack = showBackButtonAtRoot || route !== '/'
  const themeName = useThemeName()
  const [isDarkMode, setIsDarkMode] = useState(false)

  useEffect(() => {
    setIsDarkMode(themeName?.includes('dark'))
  }, [themeName])

  return (
    <YStack gap="$5">
      <XStack
        my="$2"
        ai="center"
        jc="center"
      >
        {shouldShowBack && <BackButton onPress={pop} />}
        <JunwonIcon
          height={36}
          width={36}
          color={isDarkMode ? '#FFF' : '#000'}
        />
      </XStack>
      <YStack
        gap="$3"
        ai="center"
      >
        <XStack>
          <H2>{pageTitle}</H2>
        </XStack>
        {pageSubtitle && <Paragraph col="$gray9">{pageSubtitle}</Paragraph>}
      </YStack>
    </YStack>
  )
}
