import {Stack, useLocalSearchParams, useRouter} from 'expo-router'

import {ModalListScreen} from '@/components/modal-list-screen'
import {TrailPostList} from '@/components/trail-post-list'
import {usePagedListScreen} from '@/hooks/use-paged-list-screen'
import {useTrailPostActions} from '@/hooks/use-trail-post-actions'
import {useAuth} from '@/stores/auth'
import {trailPostsList} from '@/stores/trail-posts'
import {useTrail} from '@/stores/trails'

export default function TrailPostsScreen() {
  const {trailId} = useLocalSearchParams<{trailId: string}>()
  const router = useRouter()
  const user = useAuth((s) => s.user)
  const trail = useTrail(trailId)
  const {
    items: posts,
    loading,
    loadingMore,
    screenProps,
  } = usePagedListScreen(trailPostsList, trailId)
  const {onPostLongPress} = useTrailPostActions(
    trailId,
    trail?.viewerRole,
    user?.id,
  )

  const isMember =
    trail?.viewerRole === 'owner' ||
    trail?.viewerRole === 'collaborator'

  return (
    <ModalListScreen
      title="Message board"
      {...screenProps}
      toolbar={
        isMember ? (
          <Stack.Toolbar placement="right">
            <Stack.Toolbar.Button
              accessibilityLabel="New post"
              icon="square.and.pencil"
              onPress={() => router.push(`/trail/post/${trailId}`)}
            />
          </Stack.Toolbar>
        ) : undefined
      }
    >
      <TrailPostList
        posts={posts}
        loading={loading}
        loadingMore={loadingMore}
        emptyAction={
          isMember
            ? {
                label: 'Write the first post',
                onPress: () => router.push(`/trail/post/${trailId}`),
              }
            : undefined
        }
        onPostLongPress={onPostLongPress}
      />
    </ModalListScreen>
  )
}
