import {pluralize} from '@crumbs/core/text'

import {ActionableRow} from '@/components/actionable-row'
import {List} from '@/components/ui/list'
import {useBusyAction} from '@/hooks/use-busy-action'
import {
  useAcceptTrailInvite,
  useDeclineTrailInvite,
  type TrailInvite,
} from '@/stores/trail-invites'

type TrailInviteListProps = {
  invites: TrailInvite[]
  emptyMessage?: string
}

export const TrailInviteList = ({
  invites,
  emptyMessage = 'No trail invites',
}: TrailInviteListProps) => {
  const accept = useAcceptTrailInvite()
  const decline = useDeclineTrailInvite()
  const {busy, run} = useBusyAction()

  return (
    <List
      items={invites}
      emptyMessage={emptyMessage}
      renderItem={(invite) => (
        <ActionableRow
          href={`/profile/${invite.inviter.id}`}
          // the trail is the subject: name it (+ who invited) so voiceover
          // announces the invite, not just a bare "@inviter's profile"
          accessibilityLabel={`Trail invite: ${invite.trail.name} from @${invite.inviter.handle}`}
          // cover when set, else the trail-initial disc
          avatar={{
            handle: invite.trail.name,
            uri: invite.trail.coverImageUrl,
          }}
          title={invite.trail.name}
          subtitle={[
            invite.trail.description,
            `Invited by @${invite.inviter.handle} · ${pluralize(
              invite.trail.crumbCount,
              'crumb',
            )} · ${pluralize(invite.trail.memberCount, 'member')}`,
          ]
            .filter(Boolean)
            .join('\n')}
          busy={busy === invite.id}
          onAccept={() => void run(invite.id, accept)}
          onDecline={() => void run(invite.id, decline)}
        />
      )}
    />
  )
}
