<script setup lang="ts">
import { getSelectedProfile } from '@/api/profile'
import { TransactionApiClient } from '@/api/transaction'
import { computed, onMounted, ref, type Ref } from 'vue'
import { useRoute } from 'vue-router'
import TagLabel from './TagLabel.vue'
import AppButton from './common/AppButton.vue'

const route = useRoute()
const model = defineModel<string[]>({ required: true })
const existingTags: Ref<string[]> = ref([])
const availableTags = computed(() => {
  return existingTags.value.filter((t) => !model.value.includes(t))
})

const tagSelect: Ref<string | null> = ref(null)
const enteringCustomTag = computed(() => tagSelect.value == '--CUSTOM_TAG--')
const customTagInput: Ref<string> = ref('')
const customTagInputValid = computed(() => {
  const result = customTagInput.value.match('^[a-z0-9-_]{3,32}$')
  return result !== null && result.length > 0
})
const canAddTag = computed(() => {
  if (tagSelect.value !== null && !enteringCustomTag.value) return true
  return enteringCustomTag.value && customTagInputValid.value
})

onMounted(async () => {
  const api = new TransactionApiClient(getSelectedProfile(route))
  existingTags.value = await api.getAllTags()
})

function addTag() {
  if (customTagInputValid.value) {
    model.value.push(customTagInput.value)
    tagSelect.value = null
    customTagInput.value = ''
  } else if (tagSelect.value !== null) {
    model.value.push(tagSelect.value)
    tagSelect.value = null
    customTagInput.value = ''
  }
  model.value.sort()
}
</script>
<template>
  <div style="margin-top: 0.5rem; margin-bottom: 0.5rem; font-weight: normal">
    <TagLabel
      v-for="t in model"
      :key="t"
      :tag="t"
      deletable
      @deleted="model = model.filter((tg) => tg !== t)"
    />
  </div>
  <div>
    <select v-model="tagSelect">
      <option
        v-for="tag in availableTags"
        :key="tag"
        :value="tag"
      >
        {{ tag }}
      </option>
      <option value="--CUSTOM_TAG--">Add a new tag</option>
    </select>
    <input
      style="margin-left: 0.25rem"
      v-model="customTagInput"
      v-if="enteringCustomTag"
      placeholder="Custom tag..."
    />
    <AppButton
      size="sm"
      style="margin-left: 0.25rem"
      @click="addTag()"
      :disabled="!canAddTag"
    >
      Add Tag
    </AppButton>
  </div>
</template>
