<script setup lang="ts">
import type { ComposerSenderIdentity } from '@/types/composer';
import { computed, watch } from 'vue'

interface Props {
  modelValue: ComposerSenderIdentity | null
  options: ComposerSenderIdentity[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:modelValue': [value: ComposerSenderIdentity | null]
}>()

type SenderListItem = {
  title: string
  value: string
}

const items = computed<SenderListItem[]>(() => {
  return props.options.map(option => ({
    title: formatSenderLabel(option.label, option.address),
    value: option.address,
  }))
})

const selectedValue = computed(() => props.modelValue?.address ?? null)

const errorMessages = computed(() => {
  if (props.options.length === 0) {
    return ['No send-capable account is available.']
  }

  return []
})

// Auto-select (and keep selected) the only send-capable account, since
// there's no "from" UI shown for the user to pick it themselves.
watch(
  () => props.options,
  options => {
    if (options.length === 1 && props.modelValue?.address !== options[0].address) {
      emit('update:modelValue', options[0])
    }
  },
  { immediate: true },
)

function handleUpdate(value: string | null) {
  const match = value ? props.options.find(o => o.address === value) ?? null : null
  emit('update:modelValue', match)
}

function formatSenderLabel(label: string | null | undefined, address: string): string {
  return label ? `${label} <${address}>` : address
}
</script>

<template>
  <div v-if="options.length !== 1" class="composer-sender px-4 pt-4 pb-0">
    <v-select
      :model-value="selectedValue"
      :items="items"
      item-title="title"
      item-value="value"
      label="From"
      variant="outlined"
      density="compact"
      :error="errorMessages.length > 0"
      :error-messages="errorMessages"
      :disabled="options.length === 0"
      class="mb-2"
      @update:model-value="handleUpdate"
    />
  </div>
</template>

<style scoped lang="scss">
.composer-sender {
  flex-shrink: 0;
}
</style>