import { Feather } from '@expo/vector-icons'
import { Link } from 'expo-router'
import React, { useCallback, useState } from 'react'
import { ActivityIndicator, Pressable } from 'react-native'
import type { SharedValue } from 'react-native-reanimated'
import LikeButton from 'src/components/common/LikeButton'
import { PressableOpacity } from 'src/components/common/PressableOpacity'
import { useBookmarkMutation } from 'src/hooks/mutations/useBookmarkMutation'
import { useConfirmDialog } from 'src/hooks/useConfirmDialog'
import type { Status, StatusLikedBy } from 'src/lib/api-types'
import { ICON } from 'src/lib/icons'
import { prettyCount } from 'src/utils'
import { Text, useTheme, useToastController, View, XStack, YStack } from 'tamagui'

// Variant signals the surface the action row sits on so future
// variant-specific affordances can branch from a single prop. Today the
// layout is identical across variants: every caller gets ICON.lg icons,
// accent-tinted active states, and the same ordering.
export type PostActionsVariant = 'media' | 'text' | 'event'

export interface PostActionsProps {
  hasLiked: boolean
  hasShared: boolean
  likesCount: number
  isLikePending: boolean
  likedBy: StatusLikedBy | null
  sharesCount: number
  onOpenComments: () => void
  post: Status
  progress: SharedValue<number>
  handleLike: () => void
  showAltText: boolean
  commentsCount: number
  hasBookmarked: boolean
  isLikeFeed: boolean
  onShare: () => void
  // When true, skip the outer padded background wrapper. Use inside a parent
  // that already controls padding/background (e.g. EventCard).
  inline?: boolean
  variant?: PostActionsVariant
}

const PostActions = React.memo(
  ({
    post,
    hasLiked,
    likesCount,
    isLikePending,
    hasShared,
    sharesCount,
    commentsCount,
    progress,
    showAltText,
    hasBookmarked,
    handleLike,
    onShare,
    onOpenComments,
    isLikeFeed,
    inline,
    variant: _variant = 'media',
  }: PostActionsProps) => {
    const hasAltText =
      post?.media_attachments?.length > 0 &&
      (post?.media_attachments[0]?.description?.trim().length || 0) > 0

    const toast = useToastController()
    const { confirm, dialog: confirmDialog } = useConfirmDialog()

    const onShowAlt = useCallback(() => {
      const currentIndex = Math.floor(progress?.value ?? 0)
      const altText =
        post?.media_attachments[currentIndex]?.description ??
        'Media was not tagged with any alt text.'
      toast.show('Alt text', { message: altText, duration: 6000 })
    }, [progress, post?.media_attachments, toast])

    const theme = useTheme()
    const [shareCountCache, setShareCount] = useState(sharesCount)
    const [hasSharedCache, setShared] = useState(hasShared)

    const { handleBookmark, isBookmarkPending } = useBookmarkMutation()
    const handleBookmarkAction = useCallback(() => {
      handleBookmark(post.id, !hasBookmarked)
    }, [post.id, hasBookmarked, handleBookmark])

    const handleOnShare = useCallback(async () => {
      const labelText = hasSharedCache ? 'Unshare' : 'Share'
      const ok = await confirm({
        title: `Confirm ${labelText}`,
        message: `Are you sure you want to ${labelText.toLowerCase()} this post to your followers?`,
        confirmLabel: labelText,
      })
      if (!ok) return
      if (hasSharedCache) {
        setShareCount(shareCountCache ? shareCountCache - 1 : 0)
        setShared(false)
      } else {
        setShareCount(shareCountCache ? shareCountCache + 1 : 1)
        setShared(true)
      }
      onShare()
    }, [hasSharedCache, shareCountCache, onShare, confirm])

    const row = (
      <YStack pt="$3" pb="$2" px="$2" gap={10}>
        <XStack gap="$4" justifyContent="space-between" alignItems="center">
          <XStack gap="$5" alignItems="center">
            <XStack justifyContent="center" alignItems="center" gap="$2">
              <LikeButton hasLiked={hasLiked} handleLike={handleLike} size={ICON.lg} />
              {isLikePending ? <ActivityIndicator color={theme.color.val} /> : null}
              {!isLikePending && likesCount ? (
                <Link href={`/post/likes/${post.id}`} asChild>
                  <Pressable hitSlop={{ left: 5, right: 20, top: 12, bottom: 12 }}>
                    <Text
                      fontWeight={'bold'}
                      allowFontScaling={false}
                      color={theme.colorSecondary.val}
                    >
                      {prettyCount(likesCount)}
                    </Text>
                  </Pressable>
                </Link>
              ) : null}
            </XStack>
            <Pressable
              onPress={() => onOpenComments()}
              hitSlop={{ top: 4, bottom: 4, left: 4, right: 4 }}
            >
              <XStack justifyContent="center" alignItems="center" gap="$2">
                <Feather name="message-circle" size={ICON.lg} color={theme.color.val} />
                {commentsCount ? (
                  <Text
                    fontWeight={'bold'}
                    allowFontScaling={false}
                    fontSize="$2"
                    color={theme.colorSecondary.val}
                  >
                    {prettyCount(commentsCount)}
                  </Text>
                ) : null}
              </XStack>
            </Pressable>
          </XStack>
          <XStack gap="$4" alignItems="center">
            {post.visibility === 'public' ? (
              <XStack justifyContent="center" alignItems="center" gap="$2">
                <Pressable
                  onPress={handleOnShare}
                  hitSlop={6}
                  style={({ pressed }) => ({
                    marginRight: 5,
                    transform: [{ scale: pressed ? 0.96 : 1 }],
                    opacity: pressed ? 0.9 : 1,
                  })}
                >
                  <Feather
                    name="refresh-cw"
                    size={ICON.lg}
                    color={
                      hasSharedCache ? (theme.accent.val as string) : theme.color.val
                    }
                  />
                </Pressable>
                {sharesCount ? (
                  <Link href={`/post/shares/${post.id}`} asChild>
                    <Pressable hitSlop={{ left: 5, right: 20, top: 12, bottom: 12 }}>
                      <Text
                        fontWeight={'bold'}
                        allowFontScaling={false}
                        color={theme.colorSecondary.val}
                      >
                        {prettyCount(shareCountCache)}
                      </Text>
                    </Pressable>
                  </Link>
                ) : null}
              </XStack>
            ) : null}
            {!isLikeFeed && isBookmarkPending ? (
              <ActivityIndicator color={theme.color.val} />
            ) : null}
            {!isBookmarkPending && !isLikeFeed ? (
              <PressableOpacity onPress={handleBookmarkAction} hitSlop={4}>
                <XStack gap="$4">
                  <Feather
                    name="bookmark"
                    size={ICON.lg}
                    color={hasBookmarked ? (theme.accent.val as string) : theme.color.val}
                  />
                </XStack>
              </PressableOpacity>
            ) : null}
            {showAltText && hasAltText ? (
              <PressableOpacity onPress={onShowAlt}>
                <XStack bg={theme.color.val} px="$3" py={4} borderRadius={5}>
                  <Text color={theme.colorInverse.val} fontSize="$5" fontWeight="bold">
                    ALT
                  </Text>
                </XStack>
              </PressableOpacity>
            ) : null}
          </XStack>
        </XStack>
      </YStack>
    )

    if (inline) {
      return (
        <>
          {row}
          {confirmDialog}
        </>
      )
    }

    return (
      <View px="$3" backgroundColor={theme.background.val}>
        {row}
        {confirmDialog}
      </View>
    )
  }
)

export default PostActions
