import {SymbolView} from 'expo-symbols'
import {PropsWithChildren, useState} from 'react'
import {Pressable, View} from 'react-native'
import Animated, {FadeIn} from 'react-native-reanimated'

import {Text} from '@/components/ui/typography'
import {atoms as a, pressed, tokens, useTheme} from '@/sprinkles'

export function Collapsible({
  children,
  title,
}: PropsWithChildren & {title: string}) {
  const [isOpen, setIsOpen] = useState(false)
  const t = useTheme()

  return (
    <View style={t.atoms.bg}>
      <Pressable
        accessibilityRole="button"
        accessibilityState={{expanded: isOpen}}
        style={({pressed: p}) => [
          a.flex_row,
          a.align_center,
          a.gap_sm,
          p && pressed,
        ]}
        onPress={() => setIsOpen((value) => !value)}
      >
        <View
          style={[
            a.rounded_full,
            a.justify_center,
            a.align_center,
            {
              width: tokens.space._2xl,
              height: tokens.space._2xl,
              backgroundColor: t.atoms.bg_contrast_25.backgroundColor,
            },
          ]}
        >
          <SymbolView
            name="chevron.right"
            size={14}
            weight="bold"
            tintColor={t.atoms.text.color}
            style={{
              transform: [{rotate: isOpen ? '-90deg' : '90deg'}],
            }}
          />
        </View>

        <Text>{title}</Text>
      </Pressable>
      {isOpen && (
        <Animated.View entering={FadeIn.duration(200)}>
          <View
            style={[
              a.mt_lg,
              a.rounded_lg,
              a.p_2xl,
              {
                marginLeft: tokens.space._2xl,
                backgroundColor:
                  t.atoms.bg_contrast_25.backgroundColor,
              },
            ]}
          >
            {children}
          </View>
        </Animated.View>
      )}
    </View>
  )
}
