import { Feather } from '@expo/vector-icons'
import { useCallback, useState } from 'react'
import type { ListRenderItemInfo } from 'react-native'
import { FlatList } from 'react-native-gesture-handler'
import { PressableOpacity } from 'src/components/common/PressableOpacity'
import VideoThumb from 'src/components/common/VideoThumb'
import ImageComponent from 'src/components/ImageComponent'
import { MediaBadge } from 'src/components/ui'
import { ICON } from 'src/lib/icons'
import type { MediaAsset } from 'src/lib/media'
import {
  Button,
  Separator,
  Sheet,
  Text,
  useTheme,
  View,
  XStack,
  YStack,
  ZStack,
} from 'tamagui'

// Compose Redesign Phase 4 §3.5/§4 — per-tile menu migrated from the
// `@gorhom/bottom-sheet`-backed `<ActionSheet>` to a Tamagui `Sheet`. The
// existing `<ActionSheet>` primitive stays for non-composer call sites
// (settings/profile uses it) so this is a partial migration; the @gorhom
// dep is not yet droppable.
//
// Tile interaction is unchanged from the user's POV: tap the sliders
// affordance under the thumbnail to open the menu. The plan suggested
// long-press as an alternative trigger, but the carousel-scroll conflict
// risk (and a11y cost — long-press competes with VoiceOver swipe gestures)
// outweighs the saved chrome. The plan §9 risk row explicitly allows the
// fallback to a tap-to-open trailing menu icon, which is the path taken.

type Props = {
  media: MediaAsset[]
  onEditAltText: (index: number) => void
  onRemove: (uri: string) => void
}

export function MediaRail({ media, onEditAltText, onRemove }: Props) {
  const theme = useTheme()
  const [activeIndex, setActiveIndex] = useState<number | null>(null)
  const open = activeIndex !== null
  const activeItem = activeIndex !== null ? (media[activeIndex] ?? null) : null

  const openMenu = useCallback((index: number) => {
    setActiveIndex(index)
  }, [])
  const closeMenu = useCallback(() => setActiveIndex(null), [])

  const renderItem = ({ item, index }: ListRenderItemInfo<MediaAsset>) => (
    <View m="$1">
      <YStack alignItems="center">
        {item.kind === 'photo' ? (
          <ZStack w={120} h={200}>
            <ImageComponent
              source={{ uri: item.uri }}
              resizeMode={'cover' as any}
              style={{
                width: 120,
                height: 200,
                borderRadius: 10,
                borderWidth: 1,
                borderColor: theme.borderColor.val,
              }}
            />
            {item.altText && item.altText.length ? (
              <MediaBadge text="ALT" corner="bottomLeft" />
            ) : null}
            {item.originalUri ? <MediaBadge text="RESIZED" corner="topLeft" /> : null}
          </ZStack>
        ) : (
          <ZStack w={120} h={200}>
            <VideoThumb uri={item.uri} width={120} height={200} />
            {item.originalUri ? <MediaBadge text="COMPRESSED" corner="topLeft" /> : null}
          </ZStack>
        )}
        <PressableOpacity
          onPress={() => openMenu(index)}
          hitSlop={{ left: 15, right: 15 }}
          accessibilityLabel="Manage media"
        >
          <Text color={theme.color.val} my="$3">
            <Feather name="sliders" size={ICON.md} />
          </Text>
        </PressableOpacity>
      </YStack>
    </View>
  )

  return (
    <>
      <FlatList
        data={media}
        renderItem={renderItem}
        horizontal
        keyExtractor={(m) => m.uri}
      />
      <Sheet
        modal
        open={open}
        onOpenChange={(next: boolean) => {
          if (!next) closeMenu()
        }}
        snapPointsMode="fit"
        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="$4"
          paddingBottom="$5"
          gap="$3"
        >
          <Text fontSize="$6" fontWeight="bold" color={theme.color.val}>
            Manage media
          </Text>
          <Separator borderColor={theme.borderColor.val} />
          <YStack gap="$2">
            <Button
              size="$4"
              chromeless
              transition="quick"
              pressStyle={{ opacity: 0.85, scale: 0.99 }}
              onPress={() => {
                if (activeIndex !== null) onEditAltText(activeIndex)
                closeMenu()
              }}
            >
              <XStack gap="$3" alignItems="center" flex={1}>
                <Feather name="type" size={ICON.md} color={theme.color.val} />
                <Button.Text color={theme.color.val}>Edit alt text</Button.Text>
              </XStack>
            </Button>
            <Button
              size="$4"
              theme="red"
              transition="quick"
              pressStyle={{ opacity: 0.85, scale: 0.99 }}
              onPress={() => {
                if (activeItem) onRemove(activeItem.uri)
                closeMenu()
              }}
            >
              <XStack gap="$3" alignItems="center" flex={1}>
                <Feather name="trash-2" size={ICON.md} />
                <Button.Text>Remove</Button.Text>
              </XStack>
            </Button>
            <Button
              size="$4"
              chromeless
              transition="quick"
              pressStyle={{ opacity: 0.85 }}
              onPress={closeMenu}
            >
              <Button.Text color={theme.colorSecondary.val}>Cancel</Button.Text>
            </Button>
          </YStack>
        </Sheet.Frame>
      </Sheet>
    </>
  )
}
