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

import {FeedList} from '@/components/feed-list'
import {Bento} from '@/components/home/bento'
import {SectionHeader} from '@/components/section-header'
import {Card} from '@/components/ui/card'
import {Layout} from '@/components/ui/layout'
import {toolbarBadgeButton} from '@/components/ui/toolbar-badge-button'
import {useCrumbComposer} from '@/hooks/use-crumb-composer'
import {useCurrentLocation} from '@/hooks/use-current-location'
import {useRefreshOnActive} from '@/hooks/use-refresh-on-active'
import {showActionSheet} from '@/lib/dialogs'
import {SF_DEFAULT_COORDS} from '@/lib/geo'
import {setPendingShare} from '@/lib/pending-share'
import {pickShareImage} from '@/lib/pick-image'
import {atoms as a} from '@/sprinkles'
import {useAuth} from '@/stores/auth'
import {useLoadRecentCrumbs, useRefreshPlanned} from '@/stores/crumbs'
import {useRefreshConversations, useTotalUnread} from '@/stores/dms'
import {useFeed, useFeedLoading, useLoadFeed} from '@/stores/feed'
import {
  usePendingRequestCount,
  useRefreshRequests,
} from '@/stores/friends'
import {
  usePendingInviteCount,
  useRefreshTrailInvites,
} from '@/stores/trail-invites'
import {useRefreshQuickTrails} from '@/stores/trails'

export default function HomeScreen() {
  const router = useRouter()
  const {open} = useCrumbComposer()
  const refreshPlanned = useRefreshPlanned()
  const refreshQuickTrails = useRefreshQuickTrails()
  const refreshRequests = useRefreshRequests()
  const refreshInvites = useRefreshTrailInvites()
  const refreshConversations = useRefreshConversations()
  const pendingNotifications =
    usePendingRequestCount() + usePendingInviteCount()
  const unreadMessages = useTotalUnread()
  const location = useCurrentLocation()
  const center = location ?? SF_DEFAULT_COORDS

  const user = useAuth((s) => s.user)
  const feed = useFeed()
  const feedLoading = useFeedLoading()
  const loadFeed = useLoadFeed()
  // the map bento tile previews the viewer's own recent crumbs
  const loadRecentCrumbs = useLoadRecentCrumbs()

  const onFromScreenshot = async () => {
    const uri = await pickShareImage()
    if (!uri) return
    setPendingShare({kind: 'image', uri})
    router.push('/screengrab')
  }

  const showCreateMenu = () =>
    showActionSheet([
      {label: 'New crumb', onPress: open},
      {
        label: 'From screenshot',
        onPress: () => void onFromScreenshot(),
      },
      {label: 'New trail', onPress: () => router.push('/trail/new')},
    ])

  useEffect(() => {
    void refreshPlanned()
    void refreshQuickTrails()
    void loadFeed()
    void loadRecentCrumbs()
  }, [refreshPlanned, refreshQuickTrails, loadFeed, loadRecentCrumbs])

  useRefreshOnActive(
    useCallback(() => {
      void refreshRequests()
      void refreshInvites()
      void refreshConversations()
    }, [refreshRequests, refreshInvites, refreshConversations]),
  )

  return (
    <>
      <Layout.LargeTitle>Crumbs</Layout.LargeTitle>
      <Stack.Toolbar placement="left">
        {toolbarBadgeButton({
          accessibilityLabel: 'Notifications',
          icon: 'bell',
          count: pendingNotifications,
          onPress: () => router.push('/notifications'),
        })}
        {toolbarBadgeButton({
          accessibilityLabel: 'Messages',
          icon: 'tray',
          count: unreadMessages,
          onPress: () => router.push('/dms'),
        })}
      </Stack.Toolbar>
      <Stack.Toolbar placement="right">
        <Stack.Toolbar.Button
          accessibilityLabel="Create"
          icon="plus.circle.fill"
          onPress={showCreateMenu}
        />
      </Stack.Toolbar>

      <Layout.Content>
        <Layout.Column>
          <Bento center={center} />

          <View style={a.gap_xs}>
            <SectionHeader
              label="Recent"
              seeAllHref="/feed"
              seeAllLabel="See all activity"
            />
            <Card>
              <FeedList
                items={feed}
                loading={feedLoading}
                currentUserId={user?.id}
              />
            </Card>
          </View>
        </Layout.Column>
      </Layout.Content>
    </>
  )
}
