<script setup lang="ts">
import { computed, ref } from 'vue'
import Button from 'primevue/button'
import Chip from 'primevue/chip'
import InputGroup from 'primevue/inputgroup'
import InputText from 'primevue/inputtext'

const model = defineModel<string[]>()
const entry = ref('')
const preventSubmit = computed(() => entry.value === '' || model.value?.includes(entry.value))
const emits = defineEmits<{
  (e: 'dirty'): void
}>()

const onRemove = (chip: string) => {
  if (!model.value) {
    return
  }

  const index = model.value.findIndex(other => other === chip)
  if (index > -1) {
    model.value?.splice(index, 1)
    emits('dirty')
  }
}

const onSubmit = (event: Event) => {
  event.preventDefault()
  if (preventSubmit.value) {
    return
  }
  if (!Array.isArray(model.value)) {
    model.value = []
  }
  model.value.push(entry.value)
  entry.value = ''
  emits('dirty')
}
</script>

<template lang="pug">
.input-chips
  .chips
    Chip(
      v-for='chip in model'
      :label='chip'
      :onRemove='(e) => onRemove(chip)'
      removable
    )
  InputGroup
    InputText(
      v-model='entry'
      v-on:keyup.enter='onSubmit'
      fluid
    )
    Button(
      icon='pi pi-plus'
      label='Add Option'
      type='submit'
      :disabled='preventSubmit'
      @click='onSubmit'
    )
</template>

<style scoped lang="sass">

</style>
