import {Stack, useRouter} from 'expo-router'
import {useCallback} from 'react'

import {ConversationList} from '@/components/dm/conversation-list'
import {ModalListScreen} from '@/components/modal-list-screen'
import {useFocusedPoll} from '@/hooks/use-focused-poll'
import {
  useConversations,
  useConversationsError,
  useConversationsLoading,
  useRefreshConversations,
} from '@/stores/dms'

const INBOX_POLL_INTERVAL_MS = 30_000

export default function MessagesScreen() {
  const router = useRouter()
  const conversations = useConversations()
  const loading = useConversationsLoading()
  const error = useConversationsError()
  const refresh = useRefreshConversations()

  useFocusedPoll(
    useCallback(() => void refresh(), [refresh]),
    INBOX_POLL_INTERVAL_MS,
  )

  return (
    <ModalListScreen
      title="Messages"
      onRefresh={() => void refresh()}
      loading={loading}
      itemCount={conversations.length}
      error={error}
      toolbar={
        <Stack.Toolbar placement="right">
          <Stack.Toolbar.Button
            accessibilityLabel="New message"
            icon="plus.circle.fill"
            onPress={() => router.push('/dms/new')}
          />
        </Stack.Toolbar>
      }
    >
      <ConversationList
        conversations={conversations}
        loading={loading}
      />
    </ModalListScreen>
  )
}
