import { useQuery } from '@tanstack/react-query'
import { useRouter } from 'expo-router'
import { useMemo, useState } from 'react'
import { ScrollView } from 'react-native'
import { SelfAvatarModal } from 'src/components/common/SelfStoriesModal'
import StoryRing from 'src/components/stories/StoryRing'
import { storyQueries } from 'src/lib/queries/stories'
import { normalizeCarousel, type StoryCarousel } from 'src/lib/story-types'
import { useActiveProfile, useAuth } from 'src/state/AuthProvider'
import { appStorage, uiKeys } from 'src/state/storage'
import { useTheme, View, XStack } from 'tamagui'

type Props = {
  // When mounted on a user profile, scope the rail to show only that user's
  // stories (useful for other-profile headers). Home leaves this undefined
  // and shows the full carousel.
  scopedToPid?: string
}

export default function StoriesRail({ scopedToPid }: Props) {
  const theme = useTheme()
  const router = useRouter()
  const { profile: user } = useActiveProfile()
  const hidden = appStorage.getBoolean(uiKeys.hideStories) === true
  // Mastodon Pass Phase 4 §5.3 — Stories are a Pixelfed-only feature
  // (`/api/v1.2/stories/*`); the rail must not render or fetch its carousel
  // when the active account is Mastodon. The Home call site also gates this
  // for cleanliness, but the component-level guard is the seatbelt for
  // any other mount point (other-profile headers, future surfaces).
  const { user: account } = useAuth()
  const isPixelfed = account?.type === 'pixelfed'
  const [selfModalOpen, setSelfModalOpen] = useState(false)

  const { data } = useQuery({
    ...storyQueries.carousel(),
    enabled: !hidden && isPixelfed,
  })

  const carousel: StoryCarousel = useMemo(() => normalizeCarousel(data), [data])
  const selfForModal = useMemo(
    () =>
      carousel.self.map((s) => {
        const x = s as unknown as Record<string, unknown>
        return {
          id: String(s.id),
          url: String(x.url ?? s.src ?? ''),
          created_at: String(s.created_at ?? x.created_at ?? ''),
          viewed: Boolean(x.viewed ?? s.seen ?? false),
          view_count: Number(x.view_count ?? 0),
        }
      }),
    [carousel.self]
  )

  if (hidden || !isPixelfed) return null

  const selfStories = carousel.self
  const selfGroup = scopedToPid ? carousel.nodes.find((g) => g.pid === scopedToPid) : null

  // Scoped mode: render a single ring for that profile. Keeps the API and
  // component signature symmetric between home and profile mounts.
  if (scopedToPid) {
    const isSelf = user?.id && String(user.id) === String(scopedToPid)
    const group = selfGroup
    const hasStories =
      (isSelf ? selfStories.length > 0 : (group?.nodes?.length ?? 0) > 0) || false

    if (!hasStories && !isSelf) return null

    return (
      <View py="$3" px="$4" backgroundColor={theme.background.val}>
        <XStack>
          {isSelf ? (
            <SelfRing
              avatar={user?.avatar}
              hasStories={selfStories.length > 0}
              onOpenModal={() => setSelfModalOpen(true)}
              onOpenViewer={() => router.push(`/story/view/${user?.id}`)}
              onOpenComposer={() => router.push('/story/compose')}
            />
          ) : group ? (
            <StoryRing
              avatar={group.avatar}
              label={group.username}
              variant={group.seen ? 'seen' : 'unseen'}
              onPress={() => router.push(`/story/view/${group.pid}`)}
            />
          ) : null}
        </XStack>
        {isSelf ? (
          <SelfAvatarModal
            isOpen={selfModalOpen}
            stories={selfForModal}
            onClose={() => setSelfModalOpen(false)}
            userAvatar={user?.avatar ?? ''}
            username={user?.username ?? ''}
            onAddStory={() => router.push('/story/compose')}
            onViewStories={() => router.push(`/story/view/${user?.id}`)}
          />
        ) : null}
      </View>
    )
  }

  // Default (home) mode: full rail with self first.
  const othersToShow = carousel.nodes.filter((g) => String(g.pid) !== String(user?.id))

  return (
    <View py="$3" backgroundColor={theme.background.val}>
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={{ paddingHorizontal: 12, gap: 12 }}
      >
        <SelfRing
          avatar={user?.avatar}
          hasStories={selfStories.length > 0}
          onOpenModal={() => setSelfModalOpen(true)}
          onOpenViewer={() => router.push(`/story/view/${user?.id}`)}
          onOpenComposer={() => router.push('/story/compose')}
        />
        {othersToShow.map((group) => (
          <StoryRing
            key={group.pid}
            avatar={group.avatar}
            label={group.username}
            variant={group.seen ? 'seen' : 'unseen'}
            onPress={() => router.push(`/story/view/${group.pid}`)}
          />
        ))}
      </ScrollView>

      <SelfAvatarModal
        isOpen={selfModalOpen}
        stories={selfStories as any}
        onClose={() => setSelfModalOpen(false)}
        userAvatar={user?.avatar ?? ''}
        username={user?.username ?? ''}
        onAddStory={() => router.push('/story/compose')}
        onViewStories={() => router.push(`/story/view/${user?.id}`)}
      />
    </View>
  )
}

function SelfRing({
  avatar,
  hasStories,
  onOpenModal,
  onOpenViewer,
  onOpenComposer,
}: {
  avatar?: string
  hasStories: boolean
  onOpenModal: () => void
  onOpenViewer: () => void
  onOpenComposer: () => void
}) {
  // Tap: viewer if you have stories, composer if you don't. Long-press:
  // the management modal either way (add / delete / view viewers).
  if (hasStories) {
    return (
      <StoryRing
        avatar={avatar}
        label="Your story"
        variant="self-unseen"
        onPress={onOpenViewer}
        onLongPress={onOpenModal}
      />
    )
  }
  return (
    <StoryRing
      avatar={avatar}
      label="Your story"
      variant="add"
      onPress={onOpenComposer}
      onLongPress={onOpenModal}
    />
  )
}
