import {type ReactNode} from 'react'
import {ScrollView, View} from 'react-native'
import {KeyboardAvoidingView} from 'react-native-keyboard-controller'
import {useSafeAreaInsets} from 'react-native-safe-area-context'

import {CancelButton} from '@/components/ui/cancel-button'
import {Layout} from '@/components/ui/layout'
import {Text} from '@/components/ui/typography'
import {useKeyboardVerticalOffset} from '@/hooks/use-keyboard-offset'
import {atoms as a, FONT_FAMILY_DISPLAY, useTheme} from '@/sprinkles'

// fullscreen composer scaffold mirroring bluesky's composer layout: a js
// top bar (cancel | title | submit), a scroll view for the body, and a
// slim bordered toolbar in normal flow below it, all inside one avoiding
// view. everything is frame-based — the avoiding view shrinks the
// container to the keyboard top, so the scroll view always ends exactly
// at the toolbar and no keyboard insets are needed anywhere.
//
// deliberately no native header: setting header options from inside a
// modal screen flips header visibility after mount, which remounts the
// screen (losing input state) and made the keyboard bounce
export const ComposerSheet = ({
  title,
  onCancel,
  submit,
  children,
  toolbar,
}: {
  title: string
  onCancel: () => void
  submit: ReactNode
  children: ReactNode
  toolbar: ReactNode
}) => {
  const t = useTheme()
  const insets = useSafeAreaInsets()
  const keyboardVerticalOffset = useKeyboardVerticalOffset()
  return (
    <KeyboardAvoidingView
      behavior="padding"
      keyboardVerticalOffset={keyboardVerticalOffset}
      style={[a.flex_1, t.atoms.bg]}
    >
      <View style={[a.flex_1, {paddingBottom: insets.bottom}]}>
        <Layout.Padded
          style={[a.flex_row, a.align_center, a.gap_sm, a.py_sm]}
        >
          <View style={[a.flex_1, a.align_start]}>
            <CancelButton onPress={onCancel} />
          </View>
          <Text
            style={[
              a.text_md,
              a.font_semi_bold,
              {fontFamily: FONT_FAMILY_DISPLAY},
            ]}
          >
            {title}
          </Text>
          <View style={[a.flex_1, a.align_end]}>{submit}</View>
        </Layout.Padded>
        <ScrollView
          style={a.flex_1}
          contentContainerStyle={[a.py_2xl, a.px_2xl, a.gap_lg]}
          keyboardShouldPersistTaps="handled"
          keyboardDismissMode="interactive"
        >
          {children}
        </ScrollView>
        <Layout.Padded
          style={[
            a.flex_row,
            a.align_center,
            a.justify_between,
            a.gap_sm,
            a.border_t,
            a.py_xs,
            t.atoms.bg,
            t.atoms.border_contrast_low,
          ]}
        >
          {toolbar}
        </Layout.Padded>
      </View>
    </KeyboardAvoidingView>
  )
}
