import { Feather } from '@expo/vector-icons'
import { useToastController } from '@tamagui/toast'
import * as Clipboard from 'expo-clipboard'
import { router } from 'expo-router'
import { useCallback, useMemo } from 'react'
import { Platform, Share } from 'react-native'
import type { Status } from 'src/lib/api-types'
import { ICON } from 'src/lib/icons'
import { safeOpenStatusOriginal } from 'src/utils'
import { Menu, useTheme, View } from 'tamagui'

type Props = {
  item: Status
  viewerId: string | null | undefined
  onReport: (id: string) => void
  onDelete: (id: string) => void
  onShowLikes: (id: string) => void
}

// Per-comment 3-dot kebab. Mirrors FeedPost's anchor kebab
// (`FeedPost.tsx:835-913`) — same Menu shape, comment-relevant items only.
// Skipped vs FeedPost: View Post (the row body still tap-pivots into a
// permalink) and Quote (rare on comments). Mute / Block deliberately
// omitted — heavier UX commitments, reach via View Profile.
export function CommentItemKebab({
  item,
  viewerId,
  onReport,
  onDelete,
  onShowLikes,
}: Props) {
  const theme = useTheme()
  const toast = useToastController()

  const isSelf = !!viewerId && item.account?.id === viewerId
  const permalink = item.url || item.uri || ''

  const onShare = useCallback(async () => {
    if (!permalink) return
    try {
      await Share.share({ message: permalink })
    } catch (_e) {}
  }, [permalink])

  const onCopyLink = useCallback(() => {
    if (!permalink) return
    Clipboard.setStringAsync(permalink)
    toast.show('Link copied to clipboard', {
      preset: 'success',
      duration: 2000,
    })
  }, [permalink, toast])

  const onViewProfile = useCallback(() => {
    router.push(`/profile/${item.account.id}`)
  }, [item.account?.id])

  const onAboutAccount = useCallback(() => {
    router.push(`/profile/about/${item.account.id}`)
  }, [item.account?.id])

  const onOpenBrowser = useCallback(async () => {
    if (!permalink) return
    await safeOpenStatusOriginal(item)
  }, [permalink, item])

  const onShowLikesForThis = useCallback(() => {
    onShowLikes(item.id)
  }, [onShowLikes, item.id])

  const onReportThis = useCallback(() => {
    onReport(item.id)
  }, [onReport, item.id])

  const onEditThis = useCallback(() => {
    router.push(`/post/edit/${item.id}`)
  }, [item.id])

  const onDeleteThis = useCallback(() => {
    onDelete(item.id)
  }, [onDelete, item.id])

  // Memoized like FeedPost's kebab — rebuilds only when item identity,
  // viewer identity, or `favourites_count > 0` flips across the threshold.
  // Without this every recycled CommentItem rebuilds the Menu tree and
  // zeego processes ~7 Menu.Items eagerly.
  const hasLikes = (item.favourites_count ?? 0) > 0
  return useMemo(
    () => (
      <Menu>
        <Menu.Trigger>
          <View px="$3" hitSlop={8}>
            <Feather
              name={Platform.OS === 'ios' ? 'more-horizontal' : 'more-vertical'}
              size={ICON.md}
              color={theme.color.val}
            />
          </View>
        </Menu.Trigger>
        <Menu.Content>
          <Menu.Item key="share" onSelect={onShare}>
            <Menu.ItemTitle>Share</Menu.ItemTitle>
            <Menu.ItemIcon ios={{ name: 'square.and.arrow.up' }} />
          </Menu.Item>
          <Menu.Item key="copy-link" onSelect={onCopyLink}>
            <Menu.ItemTitle>Copy link</Menu.ItemTitle>
            <Menu.ItemIcon ios={{ name: 'link' }} />
          </Menu.Item>
          <Menu.Item key="view-profile" onSelect={onViewProfile}>
            <Menu.ItemTitle>View Profile</Menu.ItemTitle>
            <Menu.ItemIcon ios={{ name: 'person' }} />
          </Menu.Item>
          <Menu.Item key="about" onSelect={onAboutAccount}>
            <Menu.ItemTitle>About this account</Menu.ItemTitle>
            <Menu.ItemIcon ios={{ name: 'info.circle' }} />
          </Menu.Item>
          <Menu.Item key="browser" onSelect={onOpenBrowser}>
            <Menu.ItemTitle>Open in browser</Menu.ItemTitle>
            <Menu.ItemIcon ios={{ name: 'safari' }} />
          </Menu.Item>
          {hasLikes ? (
            <Menu.Item key="view-likes" onSelect={onShowLikesForThis}>
              <Menu.ItemTitle>View Likes</Menu.ItemTitle>
              <Menu.ItemIcon ios={{ name: 'heart' }} />
            </Menu.Item>
          ) : null}
          {!isSelf ? (
            <Menu.Item key="report" destructive onSelect={onReportThis}>
              <Menu.ItemTitle>Report</Menu.ItemTitle>
              <Menu.ItemIcon ios={{ name: 'exclamationmark.triangle' }} />
            </Menu.Item>
          ) : null}
          {isSelf ? (
            <Menu.Group>
              <Menu.Item key="edit" onSelect={onEditThis}>
                <Menu.ItemTitle>Edit</Menu.ItemTitle>
                <Menu.ItemIcon ios={{ name: 'pencil' }} />
              </Menu.Item>
              <Menu.Item key="delete" destructive onSelect={onDeleteThis}>
                <Menu.ItemTitle>Delete</Menu.ItemTitle>
                <Menu.ItemIcon ios={{ name: 'trash' }} />
              </Menu.Item>
            </Menu.Group>
          ) : null}
        </Menu.Content>
      </Menu>
    ),
    [
      theme.color.val,
      isSelf,
      hasLikes,
      onShare,
      onCopyLink,
      onViewProfile,
      onAboutAccount,
      onOpenBrowser,
      onShowLikesForThis,
      onReportThis,
      onEditThis,
      onDeleteThis,
    ]
  )
}
