import {pluralize} from '@crumbs/core/text'
import {Stack, useLocalSearchParams, useRouter} from 'expo-router'

import {ModalListScreen} from '@/components/modal-list-screen'
import {CardRow, CardRowTitle} from '@/components/ui/card'
import {List} from '@/components/ui/list'
import {PressableRow} from '@/components/ui/pressable-row'
import {Text} from '@/components/ui/typography'
import {useBusyAction} from '@/hooks/use-busy-action'
import {usePagedListScreen} from '@/hooks/use-paged-list-screen'
import {goBack} from '@/lib/navigation'
import {useTheme} from '@/sprinkles'
import {addCrumbToTrail} from '@/stores/trail-crumbs'
import {addToTrailList} from '@/stores/trails'

export default function AddToTrailScreen() {
  const {crumbId} = useLocalSearchParams<{crumbId: string}>()
  const t = useTheme()
  const router = useRouter()
  const {
    items: trails,
    loading,
    loadingMore,
    screenProps,
  } = usePagedListScreen(addToTrailList, crumbId)
  const {
    busy: pendingId,
    error,
    run,
  } = useBusyAction({inlineError: true})

  const handlePick = (trailId: string) =>
    run(trailId, async (id) => {
      await addCrumbToTrail(id, crumbId)
      goBack()
    })

  const handleNewTrail = () =>
    router.replace({pathname: '/trail/new', params: {crumbId}})

  return (
    <ModalListScreen
      title="Add to trail"
      {...screenProps}
      error={error}
      toolbar={
        <Stack.Toolbar placement="right">
          <Stack.Toolbar.Button
            accessibilityLabel="New trail"
            icon="plus.circle.fill"
            onPress={handleNewTrail}
          />
        </Stack.Toolbar>
      }
    >
      <List
        items={trails}
        loading={loading}
        loadingMore={loadingMore}
        emptyMessage="No trails yet — create one"
        renderItem={(item) => (
          <PressableRow
            accessibilityLabel={item.name}
            disabled={pendingId !== null || item.containsCrumb}
            pending={pendingId === item.id || item.containsCrumb}
            onPress={() => void handlePick(item.id)}
          >
            <CardRow trailing={null}>
              <CardRowTitle>{item.name}</CardRowTitle>
              <Text style={[t.atoms.text_contrast_medium]}>
                {item.containsCrumb
                  ? 'Added'
                  : pluralize(item.crumbCount, 'crumb')}
              </Text>
            </CardRow>
          </PressableRow>
        )}
      />
    </ModalListScreen>
  )
}
