<template>
  <v-dialog :model-value="modelValue" max-width="420"
            @update:model-value="$emit('update:modelValue', $event)">
    <v-card>
      <v-card-title>New artist</v-card-title>
      <v-card-text>
        <v-text-field
          v-model="name" label="Artist name" autofocus
          :error-messages="error"
          @keyup.enter="submit"
        />
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn variant="text" @click="$emit('update:modelValue', false)">Cancel</v-btn>
        <v-btn color="accent" variant="flat" :loading="busy" @click="submit">Create</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { toast } from '../../utils/toast.js'
import { ref, watch } from 'vue'
import { useSourcesStore } from '../../stores/sources.js'

const props = defineProps({ modelValue: { type: Boolean, default: false } })
const emit = defineEmits(['update:modelValue', 'created'])
const store = useSourcesStore()

const name = ref('')
const error = ref('')
const busy = ref(false)

watch(() => props.modelValue, (open) => {
  if (open) { name.value = ''; error.value = '' }
})

async function submit() {
  error.value = ''
  if (!name.value.trim()) {
    error.value = 'Name is required'
    return
  }
  busy.value = true
  try {
    const { artist, created } = await store.findOrCreateArtist(name.value.trim())
    toast({
      text: created ? 'Artist created' : 'Artist already exists',
      type: 'success',
    })
    emit('created', artist)
  } catch (e) {
    error.value = String(e?.detail || e?.message || e)
  } finally {
    busy.value = false
  }
}
</script>
