import type {CrumbReactionSummary} from '@crumbs/core/schemas'
import {View} from 'react-native'

import {Chip} from '@/components/chip'
import {ReactionChips} from '@/components/reaction-chips'
import {SyncBadge} from '@/components/sync-badge'
import {CardRow, CardRowTitle} from '@/components/ui/card'
import {Link} from '@/components/ui/link'
import {List} from '@/components/ui/list'
import {Thumbnail} from '@/components/ui/thumbnail'
import {Text} from '@/components/ui/typography'
import {formatDayDate} from '@/lib/dates'
import {crumbPlannedDate} from '@/lib/planned'
import {atoms as a, useTheme} from '@/sprinkles'
import {type Crumb} from '@/stores/crumbs'

export type CrumbWithAuthor = Crumb & {
  authorHandle?: string
  reactions?: CrumbReactionSummary[]
}

// one crumb row, reusable by any list container (List, VirtualList).
// generic so a caller with richer rows (e.g. a trail's crumbs) gets its
// own type back in the long-press handler
export const CrumbRow = <T extends CrumbWithAuthor>({
  crumb,
  showAuthor,
  onLongPress,
}: {
  crumb: T
  showAuthor?: boolean
  onLongPress?: (crumb: T) => void
}) => {
  const t = useTheme()
  const date = crumbPlannedDate(crumb)
  const meta = [crumb.place?.name, date && formatDayDate(date)]
    .filter(Boolean)
    .join(' · ')

  return (
    <Link
      href={`/crumb/${crumb.id}`}
      accessibilityLabel={crumb.name}
      accessibilityHint={
        onLongPress ? 'Long press for options' : undefined
      }
      onLongPress={onLongPress && (() => onLongPress(crumb))}
    >
      {(isPressed) => (
        <CardRow
          pressed={isPressed}
          leading={
            crumb.imageUrl ? (
              <Thumbnail
                uri={crumb.imageUrl}
                width={52}
                height={52}
                accessibilityLabel={crumb.name}
              />
            ) : undefined
          }
        >
          <View
            style={[
              a.flex_row,
              a.align_center,
              a.justify_between,
              a.gap_sm,
            ]}
          >
            <View
              style={[a.flex_row, a.align_center, a.gap_xs, a.flex_1]}
            >
              {crumb.status === 'done' && (
                <Text emoji style={a.text_sm}>
                  ✅
                </Text>
              )}
              <CardRowTitle>{crumb.name}</CardRowTitle>
            </View>
            <ReactionChips reactions={crumb.reactions ?? []} />
          </View>
          {meta ? (
            <Text
              emoji
              style={[a.text_sm, t.atoms.text_contrast_medium]}
            >
              {meta}
            </Text>
          ) : null}
          <SyncBadge scope={crumb.id} />
          {(showAuthor && crumb.authorHandle) ||
          crumb.tags.length > 0 ? (
            <View
              style={[
                a.flex_row,
                a.flex_wrap,
                a.align_center,
                a.gap_xs,
              ]}
            >
              {showAuthor && crumb.authorHandle && (
                <Text style={[t.atoms.text_contrast_medium]}>
                  @{crumb.authorHandle}
                </Text>
              )}
              {crumb.tags.map((tag) => (
                <Chip key={tag.name} label={tag.name} />
              ))}
            </View>
          ) : null}
        </CardRow>
      )}
    </Link>
  )
}

export const CRUMB_REORDER_ROW_HEIGHT = 52

// compact fixed-height row for drag-to-reorder mode
export const CrumbReorderRow = ({
  crumb,
}: {
  crumb: CrumbWithAuthor
}) => (
  <View
    style={[
      a.flex_row,
      a.align_center,
      a.gap_md,
      {height: CRUMB_REORDER_ROW_HEIGHT},
    ]}
  >
    {crumb.imageUrl && (
      <Thumbnail
        uri={crumb.imageUrl}
        width={36}
        height={36}
        accessibilityLabel={crumb.name}
      />
    )}
    <CardRowTitle numberOfLines={1} style={a.flex_1}>
      {crumb.name}
    </CardRowTitle>
  </View>
)

export const CrumbList = <T extends CrumbWithAuthor>({
  crumbs,
  loading,
  loadingMore,
  emptyMessage = 'No crumbs yet',
  showAuthor,
  currentUserId,
  onCrumbLongPress,
}: {
  crumbs: T[]
  loading?: boolean
  loadingMore?: boolean
  emptyMessage?: string
  showAuthor?: boolean
  // hides the handle on the viewer's own rows, like FeedList does
  currentUserId?: string
  onCrumbLongPress?: (crumb: T) => void
}) => (
  <List
    items={crumbs}
    loading={loading}
    loadingMore={loadingMore}
    emptyMessage={emptyMessage}
    renderItem={(crumb) => (
      <CrumbRow
        crumb={crumb}
        showAuthor={showAuthor && crumb.authorId !== currentUserId}
        onLongPress={onCrumbLongPress}
      />
    )}
  />
)
