import {
  BottomSheetBackdrop,
  type BottomSheetModal,
  BottomSheetView,
} from '@gorhom/bottom-sheet'
import { type Ref, useCallback, useMemo } from 'react'
import { PixelfedBottomSheetModal } from 'src/components/common/BottomSheets'
import { Button, Separator, Text, useTheme, YStack } from 'tamagui'

// Reusable 2-to-4-button @gorhom action sheet. One destructive slot supported
// via the `destructive` flag on an item; the theme="red" button inherits the
// shared dialog's visual language. Consumers own the ref so they can dismiss
// imperatively after an action fires.

export type ActionSheetItem = {
  id: string
  label: string
  destructive?: boolean
  onPress: () => void
}

type Props = {
  ref?: Ref<BottomSheetModal | null>
  title: string
  description?: string
  items: ActionSheetItem[]
  onCancel: () => void
  cancelLabel?: string
  snapPoints?: string[]
}

export function ActionSheet({
  ref,
  title,
  description,
  items,
  onCancel,
  cancelLabel = 'Cancel',
  snapPoints,
}: Props) {
  const theme = useTheme()
  const points = useMemo(() => snapPoints ?? ['33%'], [snapPoints])
  const renderBackdrop = useCallback(
    (props: any) => (
      <BottomSheetBackdrop {...props} disappearsOnIndex={-1} appearsOnIndex={0} />
    ),
    []
  )

  return (
    <PixelfedBottomSheetModal
      ref={ref}
      index={0}
      snapPoints={points}
      backdropComponent={renderBackdrop}
      backgroundStyle={{ backgroundColor: theme.background.val }}
      handleIndicatorStyle={{ backgroundColor: theme.backgroundTertiary.val }}
    >
      <BottomSheetView
        style={{ flex: 1, padding: 16, backgroundColor: theme.background.val }}
      >
        <YStack gap="$1" pb="$3">
          <Text fontSize="$6" fontWeight="bold" color={theme.color.val}>
            {title}
          </Text>
          {description ? (
            <Text fontSize="$3" color={theme.colorSecondary.val}>
              {description}
            </Text>
          ) : null}
        </YStack>
        <Separator borderColor={theme.borderColor.val} />
        <YStack py="$3" gap="$2">
          {items.map((item) => (
            <Button
              key={item.id}
              size="$4"
              chromeless={!item.destructive}
              theme={item.destructive ? 'red' : undefined}
              transition="quick"
              pressStyle={{ opacity: 0.85, scale: 0.99 }}
              onPress={item.onPress}
            >
              <Button.Text color={item.destructive ? undefined : theme.color.val}>
                {item.label}
              </Button.Text>
            </Button>
          ))}
          <Button
            size="$4"
            chromeless
            transition="quick"
            pressStyle={{ opacity: 0.85 }}
            onPress={onCancel}
          >
            <Button.Text color={theme.colorSecondary.val}>{cancelLabel}</Button.Text>
          </Button>
        </YStack>
      </BottomSheetView>
    </PixelfedBottomSheetModal>
  )
}
