<script setup>
import { ref, watch, computed } from 'vue'
import { router } from '@inertiajs/vue3'
import { NModal, NForm, NFormItem, NInput, NSelect, NInputNumber, NButton, NFlex, NText } from 'naive-ui'

const props = defineProps({
    show: { type: Boolean, default: false },
    dataset: { type: String, default: null },
    baseMeasures: { type: Array, default: () => [] }, // [{ label, value }]
})

const emit = defineEmits(['update:show'])

const name = ref('')
const baseMeasure = ref(null)
const factor = ref(1)
const unit = ref(null)

const unitOptions = [
    { label: 'Число', value: 'count' },
    { label: 'Процент', value: 'percent' },
    { label: 'Деньги (₽)', value: 'money' },
    { label: 'Без единицы', value: null },
]

watch(() => props.show, (value) => {
    if (value) {
        name.value = ''
        baseMeasure.value = props.baseMeasures[0]?.value ?? null
        factor.value = 1
        unit.value = 'count'
    }
})

const canSave = computed(() => name.value.trim() && baseMeasure.value)

const save = () => {
    if (!canSave.value) return
    router.post('/reports/measures', {
        name: name.value.trim(),
        dataset: props.dataset,
        base_measure: baseMeasure.value,
        factor: factor.value,
        unit: unit.value,
    }, {
        preserveScroll: true,
        preserveState: false,
        onSuccess: () => emit('update:show', false),
    })
}
</script>

<template>
    <NModal
        :show="show"
        preset="card"
        title="Новый показатель"
        style="width: 460px; max-width: 94vw;"
        @update:show="emit('update:show', $event)"
    >
        <NText depth="3" style="font-size: 12px; display: block; margin-bottom: 12px;">
            Производный показатель — базовый показатель, умноженный на коэффициент
        </NText>
        <NForm>
            <NFormItem label="Название">
                <NInput v-model:value="name" maxlength="50" placeholder="Например: Выписано (×100)" />
            </NFormItem>
            <NFormItem label="Базовый показатель">
                <NSelect v-model:value="baseMeasure" :options="baseMeasures" placeholder="Выберите показатель" />
            </NFormItem>
            <NFormItem label="Коэффициент">
                <NInputNumber v-model:value="factor" :step="0.1" style="width: 100%;" />
            </NFormItem>
            <NFormItem label="Единица">
                <NSelect v-model:value="unit" :options="unitOptions" />
            </NFormItem>
        </NForm>
        <template #footer>
            <NFlex justify="end" :size="8">
                <NButton @click="emit('update:show', false)">Отменить</NButton>
                <NButton type="primary" :disabled="!canSave" @click="save">Создать</NButton>
            </NFlex>
        </template>
    </NModal>
</template>
