import { useEffect, useState } from 'react'
import ImageComponent from 'src/components/ImageComponent'
import { CharCount } from 'src/components/ui'
import type { MediaAsset } from 'src/lib/media'
import { Button, Sheet, Text, TextArea, useTheme, View, XStack, YStack } from 'tamagui'

// Compose Redesign Phase 4 §3.5/§4 — migrated from `@gorhom/bottom-sheet`
// (PixelfedBottomSheetModal + BottomSheetTextInput + BottomSheetScrollView)
// to a Tamagui `Sheet`. The sheet is controlled by `open` / `onOpenChange`
// rather than the prior imperative ref API; the consumer (`PostComposer`)
// owns the open state alongside `activeAltIndex` so the two stay in sync
// without a forwarded ref.
//
// The character counter routes through the shared `<CharCount>` primitive
// instead of the previous inline 14pt bold text. Heading copy moves from
// "Alt Text" to "Describe this image" per §6.1 of the redesign — same
// intent on Pixelfed and Mastodon, action-oriented framing.

type Props = {
  open: boolean
  onOpenChange: (open: boolean) => void
  media: MediaAsset | null
  maxLength: number
  onSave: (altText: string) => void
}

export function AltTextSheet({ open, onOpenChange, media, maxLength, onSave }: Props) {
  const theme = useTheme()
  const [draft, setDraft] = useState(media?.altText ?? '')

  useEffect(() => {
    setDraft(media?.altText ?? '')
  }, [media?.uri, media?.altText])

  const overLimit = draft.length > maxLength

  return (
    <Sheet
      modal
      open={open}
      onOpenChange={onOpenChange}
      snapPoints={[70]}
      dismissOnSnapToBottom
      zIndex={100_000}
    >
      <Sheet.Overlay
        backgroundColor="rgba(0,0,0,0.5)"
        enterStyle={{ opacity: 0 }}
        exitStyle={{ opacity: 0 }}
      />
      <Sheet.Handle backgroundColor={theme.backgroundTertiary.val} />
      <Sheet.Frame backgroundColor={theme.background.val} padding="$3" gap="$3">
        <YStack gap="$1">
          <Text fontSize="$8" fontWeight="bold" color={theme.color.val}>
            Describe this image
          </Text>
          <Text color={theme.colorTertiary.val}>
            Add optional alt text to describe the media for visually impaired
          </Text>
        </YStack>
        {media ? (
          <View alignItems="center">
            <ImageComponent
              source={{ uri: media.uri }}
              style={{
                width: '100%',
                height: 220,
                borderRadius: 10,
              }}
              resizeMode={'contain' as any}
            />
          </View>
        ) : null}
        <TextArea
          size="$4"
          fontSize="$5"
          minHeight={120}
          borderWidth={1}
          bg={theme.backgroundTertiary.val}
          borderColor={
            overLimit ? ('$colorDanger' as any) : (theme.borderColor.val as any)
          }
          color={theme.color.val}
          placeholderTextColor={theme.colorTertiary.val as any}
          placeholder="Add optional alt text to describe the media for visually impaired"
          value={draft}
          onChangeText={setDraft}
          maxLength={maxLength}
          autoCapitalize="sentences"
          multiline
          numberOfLines={4}
        />
        <XStack justifyContent="flex-end">
          <CharCount
            current={draft.length}
            max={maxLength}
            tone={overLimit ? 'danger' : 'default'}
          />
        </XStack>
        <Button
          bg={theme.interactiveActive.val}
          size="$5"
          onPress={() => {
            onSave(draft)
            setDraft('')
          }}
        >
          <Button.Text color="white" fontWeight="bold">
            Save
          </Button.Text>
        </Button>
      </Sheet.Frame>
    </Sheet>
  )
}
