import { useQuery } from '@tanstack/react-query'
import { type ErrorBoundaryProps, useLocalSearchParams, useRouter } from 'expo-router'
import { ErrorState } from 'src/components/common/ErrorState'
import { PostComposer } from 'src/components/composer/PostComposer'
import { PlaybackScope } from 'src/hooks/playback/PlaybackScope'
import { useAcceptableUseToastOnce } from 'src/hooks/useAcceptableUseToastOnce'
import { accountQueries } from 'src/lib/queries/accounts'
import { postQueries } from 'src/lib/queries/posts'
import { useActiveProfile } from 'src/state/AuthProvider'

export function ErrorBoundary({ error, retry }: ErrorBoundaryProps) {
  return <ErrorState message={error.message} onRetry={retry} />
}

export default function Camera() {
  const router = useRouter()
  useAcceptableUseToastOnce()
  const { quotedStatusId: quotedStatusIdParam, inReplyToId: inReplyToIdParam } =
    useLocalSearchParams<{
      quotedStatusId?: string
      inReplyToId?: string
    }>()
  const quotedStatusId = quotedStatusIdParam ?? null
  const inReplyToId = inReplyToIdParam ?? null
  const { profile: userCache } = useActiveProfile()
  const { data: userSelf } = useQuery(accountQueries.self())
  // Cached-only read of the reply target — `postQueries.detail` falls back
  // to a network fetch on cache miss, which is fine: the modal renders
  // immediately with `target={null}` (the `<ReplyIndicator>` returns null
  // until the data lands) so the user-perceived latency is just the banner
  // appearing when the cache resolves.
  const { data: replyTarget } = useQuery({
    ...postQueries.detail(inReplyToId ?? ''),
    enabled: !!inReplyToId,
  })

  return (
    <PlaybackScope name="camera">
      <PostComposer
        quotedStatusId={quotedStatusId}
        inReplyToId={inReplyToId}
        inReplyTo={replyTarget ?? null}
        userId={userSelf?.id ?? null}
        username={userCache?.username ?? null}
        displayName={userCache?.display_name ?? userSelf?.display_name ?? null}
        avatarUrl={userCache?.avatar ?? null}
        lockedAccount={!!userSelf?.locked}
        onCancelQuote={() => router.replace('/camera')}
      />
    </PlaybackScope>
  )
}
