import type {TrailDetail} from '@crumbs/core/schemas'
import {pluralize} from '@crumbs/core/text'
import {View} from 'react-native'

import {AvatarStack} from '@/components/avatar-stack'
import {RichPostText} from '@/components/trail-post-list'
import {Avatar} from '@/components/ui/avatar'
import {CardRowTitle} from '@/components/ui/card'
import {Link} from '@/components/ui/link'
import {MapPreview} from '@/components/ui/map-preview'
import {Thumbnail} from '@/components/ui/thumbnail'
import {Tile, TILE_HEIGHT} from '@/components/ui/tile'
import {Text} from '@/components/ui/typography'
import {ZoomMapLink} from '@/components/zoom-map-link'
import {
  crumbCoords,
  isLocated,
  toMarker,
  type LocatedCrumb,
} from '@/lib/geo'
import {atoms as a, useTheme} from '@/sprinkles'

const POST_PREVIEW_LINES = 3

// glanceable header grid: cover + description on top, latest post
// full width below, then trail map + collaborators peers
export const TrailBento = ({
  trail,
  isMember,
}: {
  trail: TrailDetail
  isMember: boolean
}) => {
  const t = useTheme()
  const located = trail.crumbs.filter(isLocated)
  const showPosts = isMember || trail.posts.length > 0

  return (
    <View style={a.gap_md}>
      <Thumbnail
        uri={trail.coverImageUrl}
        width="100%"
        aspectRatio={16 / 9}
        radius={12}
        accessibilityLabel={`${trail.name} cover`}
      />
      {trail.description && (
        <Text style={t.atoms.text_contrast_medium}>
          {trail.description}
        </Text>
      )}
      {showPosts && <PostsTile trail={trail} isMember={isMember} />}
      <View style={[a.flex_row, a.gap_md]}>
        <CollaboratorsTile
          trailId={trail.id}
          collaborators={trail.collaborators}
        />
        {located.length > 0 && (
          <TrailMapTile trailId={trail.id} crumbs={located} />
        )}
      </View>
    </View>
  )
}

// edge-to-edge thumbnail of the trail's located crumbs; keeps the
// apple-zoom transition into the full map filtered to this trail
const TrailMapTile = ({
  trailId,
  crumbs,
}: {
  trailId: string
  crumbs: LocatedCrumb[]
}) => {
  const t = useTheme()
  const markers = crumbs.map((c) => toMarker(c, t.palette.bg))

  return (
    <ZoomMapLink
      href={{pathname: '/map', params: {trailId}}}
      label="View trail on map"
    >
      <MapPreview
        center={crumbCoords(crumbs[0]!)}
        markers={markers}
        zoom={13}
        height={TILE_HEIGHT}
        style={t.atoms.bg_contrast_25}
      />
    </ZoomMapLink>
  )
}

const COLLABORATOR_DISC_SIZE = 36

const CollaboratorsTile = ({
  trailId,
  collaborators,
}: {
  trailId: string
  collaborators: TrailDetail['collaborators']
}) => {
  const t = useTheme()
  const count = collaborators.length

  if (count === 0)
    return (
      <Tile
        label="Collaborators"
        style={[a.flex_1, {height: TILE_HEIGHT}]}
      >
        <View style={[a.flex_1, a.justify_end]}>
          <Text style={t.atoms.text_contrast_medium}>
            No collaborators yet
          </Text>
        </View>
      </Tile>
    )

  return (
    <Link
      href={`/trail/collaborators/${trailId}`}
      accessibilityLabel="View collaborators"
      style={[a.flex_1, {height: TILE_HEIGHT}]}
    >
      {(pressed) => (
        <Tile
          label="Collaborators"
          pressed={pressed}
          style={a.flex_1}
        >
          <View style={[a.flex_1, a.justify_between, a.gap_sm]}>
            <AvatarStack
              members={collaborators}
              size={COLLABORATOR_DISC_SIZE}
            />
            <Text style={t.atoms.text_contrast_medium}>
              {pluralize(count, 'collaborator')}
            </Text>
          </View>
        </Tile>
      )}
    </Link>
  )
}

const PREVIEW_AVATAR_SIZE = 24

// the whole tile opens the message board; the latest post is a plain preview
// (post actions live on the board, not this glanceable card)
const PostsTile = ({
  trail,
  isMember,
}: {
  trail: TrailDetail
  isMember: boolean
}) => {
  const t = useTheme()
  const latest = trail.posts[0]

  return (
    <Link
      href={`/trail/posts/${trail.id}`}
      accessibilityLabel="Message board"
    >
      {(pressed) => (
        <Tile label="Message board" pressed={pressed}>
          {latest ? (
            <View style={a.gap_xs}>
              <View style={[a.flex_row, a.align_center, a.gap_sm]}>
                <Avatar
                  handle={latest.author.handle}
                  uri={latest.author.avatarUrl}
                  size={PREVIEW_AVATAR_SIZE}
                />
                <CardRowTitle>@{latest.author.handle}</CardRowTitle>
              </View>
              <RichPostText
                text={latest.text}
                facets={latest.facets}
                numberOfLines={POST_PREVIEW_LINES}
              />
            </View>
          ) : (
            <Text style={t.atoms.text_contrast_medium}>
              {isMember
                ? 'No posts yet — start the conversation'
                : 'No posts yet'}
            </Text>
          )}
        </Tile>
      )}
    </Link>
  )
}
