import { Feather } from '@expo/vector-icons'
import { router } from 'expo-router'
import { Dimensions, Pressable } from 'react-native'
import type { SharedValue } from 'react-native-reanimated'
import EmojiText from 'src/components/common/EmojiText'
import UserAvatar from 'src/components/common/UserAvatar'
import RsvpPill from 'src/components/event/RsvpPill'
import ImageComponent from 'src/components/ImageComponent'
import { useRsvpMutation } from 'src/hooks/mutations/useRsvpMutation'
import { useEventRsvpAvailable } from 'src/hooks/useEventRsvpAvailable'
import type { RsvpAction } from 'src/lib/api'
import type { PfEvent, Status } from 'src/lib/api-types'
import { isEventPast } from 'src/lib/events'
import { ICON } from 'src/lib/icons'
import { getMediaAspectRatio } from 'src/lib/media-source'
import { enforceLen, prettyCount } from 'src/utils'
import { Separator, Text, useTheme, View, XStack, YStack } from 'tamagui'
import PostActions from './PostActions'

const SCREEN_WIDTH = Dimensions.get('screen').width
const EVENT_CARD_WIDTH = SCREEN_WIDTH - 20
const EVENT_COVER_MAX_HEIGHT = 320

type EventCardActionProps = {
  hasLiked: boolean
  hasShared: boolean
  hasBookmarked: boolean
  isLikeFeed: boolean
  likesCount: number
  sharesCount: number
  commentsCount: number
  progress: SharedValue<number>
  handleLike: () => void
  onOpenComments: () => void
  onShare: () => void
}

type EventCardProps = {
  post: Status
  // When provided, EventCard renders an inline action bar (like/comment/
  // share/bookmark). Without these props the card renders read-only chrome
  // (e.g. nested inside other surfaces). The RSVP pill lives inside the
  // metadata row regardless of `actions`, gated by `useEventRsvpAvailable`.
  actions?: EventCardActionProps
}

const ONE_DAY_MS = 24 * 60 * 60 * 1000

function formatEventDate(
  startTime: string | null | undefined,
  timeZone: string | null
): string | null {
  if (!startTime) return null
  const d = new Date(startTime)
  if (Number.isNaN(d.getTime())) return null
  try {
    return new Intl.DateTimeFormat(undefined, {
      weekday: 'short',
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
      ...(timeZone ? { timeZone } : null),
    }).format(d)
  } catch {
    return d.toDateString()
  }
}

function formatMultiDayLabel(event: PfEvent): string | null {
  if (!event.end_time) return null
  const s = Date.parse(event.start_time)
  const e = Date.parse(event.end_time)
  if (Number.isNaN(s) || Number.isNaN(e)) return null
  const longFlag = event.long_event === true
  if (!longFlag && e - s < ONE_DAY_MS) return null
  try {
    const fmtDay = new Intl.DateTimeFormat(undefined, {
      month: 'short',
      day: 'numeric',
      ...(event.timezone ? { timeZone: event.timezone } : null),
    })
    return `Through ${fmtDay.format(new Date(e))}`
  } catch {
    return 'Multi-day event'
  }
}

function locationLabel(event: PfEvent): string | null {
  const loc = event.location
  if (!loc) return null
  if (loc.name?.trim()) return loc.name
  if (loc.address?.trim()) return loc.address
  if (loc.online_url) return 'Online'
  return null
}

export default function EventCard({ post, actions }: EventCardProps) {
  const theme = useTheme()
  const event = post.pf_event
  const rsvpAvailable = useEventRsvpAvailable()
  const { handleRsvp, isRsvpPending } = useRsvpMutation({ profileId: post.account?.id })
  if (!event) return null

  const when = formatEventDate(event.start_time, event.timezone ?? null)
  const multiDay = formatMultiDayLabel(event)
  const where = locationLabel(event)
  const coverAttachment = post.media_attachments?.[0] ?? null
  const cover = coverAttachment?.url ?? null
  const coverAspectRatio = getMediaAspectRatio(coverAttachment)
  const coverNaturalHeight = EVENT_CARD_WIDTH / coverAspectRatio
  const coverHeight =
    coverNaturalHeight > EVENT_COVER_MAX_HEIGHT
      ? EVENT_COVER_MAX_HEIGHT
      : coverNaturalHeight
  const attendees = event.hide_attendee_count ? null : event.attendees_count
  const cancelled = event.status === 'cancelled'
  const rsvp = event.my_participation?.status ?? null
  const past = isEventPast(event)
  const author = post.account
  const authorLabel =
    author?.display_name?.trim() || author?.acct || author?.username || ''

  const onSelectRsvp = (action: RsvpAction) => handleRsvp(post.id, action)

  return (
    <View
      borderWidth={1}
      borderColor={theme.borderColor.val}
      borderRadius={12}
      overflow="hidden"
      marginHorizontal={10}
      marginVertical={8}
      backgroundColor={theme.background.val}
    >
      <Pressable onPress={() => router.push(`/post/${post.id}`)} hitSlop={4}>
        {cover && (
          <View position="relative">
            <ImageComponent
              source={{ uri: cover }}
              style={{ width: '100%', height: coverHeight } as any}
              resizeMode={'cover' as any}
            />
            {author ? (
              <View position="absolute" top={8} left={8}>
                <Pressable
                  onPress={() => router.push(`/profile/${author.id}`)}
                  hitSlop={4}
                >
                  <XStack
                    alignItems="center"
                    gap="$2"
                    px="$2"
                    py="$1"
                    borderRadius={999}
                    backgroundColor="rgba(0,0,0,0.45)"
                  >
                    {author.avatar ? <UserAvatar url={author.avatar} size="xs" /> : null}
                    <EmojiText
                      text={enforceLen(authorLabel, 32, true)}
                      emojis={author?.emojis}
                      fontSize="$2"
                      color="white"
                    />
                  </XStack>
                </Pressable>
              </View>
            ) : null}
          </View>
        )}

        <YStack padding={12} gap="$2">
          {!cover && author ? (
            <Pressable onPress={() => router.push(`/profile/${author.id}`)} hitSlop={4}>
              <XStack alignItems="center" gap="$2">
                {author.avatar ? <UserAvatar url={author.avatar} size="xs" /> : null}
                <EmojiText
                  text={enforceLen(authorLabel, 32, true)}
                  emojis={author?.emojis}
                  fontSize="$2"
                  color={theme.colorSecondary.val}
                />
              </XStack>
            </Pressable>
          ) : null}

          {cancelled ? (
            <Text fontSize="$2" fontWeight="bold" color={theme.red10?.val ?? '#c00'}>
              CANCELLED
            </Text>
          ) : null}

          <Text fontSize="$5" fontWeight="bold" color={theme.color.val} numberOfLines={2}>
            {event.name}
          </Text>

          <XStack gap="$3" alignItems="center">
            <YStack flex={1} gap="$2">
              {when ? (
                <XStack alignItems="center" gap="$2">
                  <Feather
                    name="calendar"
                    size={ICON.xs}
                    color={theme.colorSecondary.val}
                  />
                  <Text fontSize="$3" color={theme.colorSecondary.val} flexShrink={1}>
                    {when}
                  </Text>
                  {multiDay ? (
                    <Text fontSize="$2" color={theme.colorTertiary.val}>
                      · {multiDay}
                    </Text>
                  ) : null}
                </XStack>
              ) : null}

              {where ? (
                <XStack alignItems="center" gap="$2">
                  <Feather
                    name="map-pin"
                    size={ICON.xs}
                    color={theme.colorSecondary.val}
                  />
                  <Text
                    fontSize="$3"
                    color={theme.colorSecondary.val}
                    numberOfLines={1}
                    flexShrink={1}
                  >
                    {where}
                  </Text>
                </XStack>
              ) : null}

              {attendees != null ? (
                <XStack alignItems="center" gap="$2">
                  <Feather name="users" size={ICON.xs} color={theme.colorTertiary.val} />
                  <Text fontSize="$2" color={theme.colorTertiary.val}>
                    {prettyCount(attendees)} going
                  </Text>
                </XStack>
              ) : null}
            </YStack>

            {rsvpAvailable ? (
              <View justifyContent="center" maxWidth="40%">
                <RsvpPill
                  rsvp={rsvp}
                  past={past}
                  pending={isRsvpPending}
                  onSelect={onSelectRsvp}
                  size="sm"
                />
              </View>
            ) : null}
          </XStack>
        </YStack>
      </Pressable>

      {actions ? (
        <>
          <Separator borderColor={theme.borderColor.val} />
          <View paddingHorizontal={4} paddingTop={4}>
            <PostActions
              inline
              variant="event"
              post={post}
              progress={actions.progress}
              hasLiked={actions.hasLiked}
              hasShared={actions.hasShared}
              hasBookmarked={actions.hasBookmarked}
              isLikeFeed={actions.isLikeFeed}
              likesCount={actions.likesCount}
              sharesCount={actions.sharesCount}
              commentsCount={actions.commentsCount}
              showAltText={false}
              handleLike={actions.handleLike}
              onOpenComments={actions.onOpenComments}
              onShare={actions.onShare}
            />
          </View>
        </>
      ) : null}
    </View>
  )
}
