<script lang="ts">
  import { IntlString, translate } from '@hcengineering/platform'
  import { createQuery } from '@hcengineering/presentation'
  import { DropdownLabels } from '@hcengineering/ui'
  import { Ref, SortingOrder, Space } from '@hcengineering/core'
  import { DropdownTextItem } from '@hcengineering/ui/src/types'
  import task, { State } from '@hcengineering/task'
  import { Card } from '@hcengineering/board'
  import board from '../../plugin'

  export let object: Card
  export let label: IntlString
  export let selected: Ref<State>
  export let space: Ref<Space>

  let states: DropdownTextItem[] = []
  const statesQuery = createQuery()
  statesQuery.query(
    task.class.State,
    { space, isArchived: { $nin: [true] } },
    async (result) => {
      if (!result) return
      states = result.map(({ _id, title }) => ({ id: _id, label: title }))
      ;[{ _id: selected }] = result
      if (object.space === space) {
        const index = states.findIndex(({ id }) => id === object.state)
        states[index].label = await translate(board.string.Current, { label: states[index].label })
        selected = object.state
      }
    },
    { sort: { rank: SortingOrder.Ascending } }
  )
</script>

<DropdownLabels items={states} {label} bind:selected />
