<template>
	<CreateEdit
		v-model:loading="loadingModel"
		:title="$t('label.create.title')"
		:primary-disabled="label.title === ''"
		@create="newLabel()"
	>
		<FormField
			id="labelTitle"
			v-model="label.title"
			v-focus
			:label="$t('label.attributes.title')"
			:disabled="loading"
			:loading="loading"
			:placeholder="$t('label.attributes.titlePlaceholder')"
			type="text"
			:error="showError && label.title === '' ? $t('label.create.titleRequired') : null"
			@keyup.enter="newLabel()"
		/>
		<FormField :label="$t('label.attributes.color')">
			<ColorPicker v-model="label.hexColor" />
		</FormField>
	</CreateEdit>
</template>

<script setup lang="ts">
import {computed, onBeforeMount, ref} from 'vue'
import {useI18n} from 'vue-i18n'
import {useRouter} from 'vue-router'

import CreateEdit from '@/components/misc/CreateEdit.vue'
import ColorPicker from '@/components/input/ColorPicker.vue'
import FormField from '@/components/input/FormField.vue'

import LabelModel from '@/models/label'
import {useLabelStore} from '@/stores/labels'
import {useTitle} from '@/composables/useTitle'
import {success} from '@/message'
import {getRandomColorHex} from '@/helpers/color/randomColor'

const router = useRouter()

const {t} = useI18n({useScope: 'global'})
useTitle(() => t('label.create.title'))

const labelStore = useLabelStore()
const label = ref(new LabelModel())

onBeforeMount(() => label.value.hexColor = getRandomColorHex())

const showError = ref(false)
const loading = computed(() => labelStore.isLoading)
const isSubmitting = ref(false)

const loadingModel = computed({
	get: () => isSubmitting.value || loading.value,
	set(value: boolean) {
		isSubmitting.value = value
	},
})

async function newLabel() {
	if (label.value.title === '') {
		showError.value = true
		return
	}
	showError.value = false

	if (isSubmitting.value) {
		return
	}

	isSubmitting.value = true

	try {
		const newLabel = await labelStore.createLabel(label.value)
		router.push({
			name: 'labels.index',
			params: {id: newLabel.id},
		})
		success({message: t('label.create.success')})
	} finally {
		isSubmitting.value = false
	}
}
</script>
