<script setup>
import {NButton, NForm, NFormItem, NInput, NModal, NSpace, NText, NSpin} from "naive-ui";
import {computed, ref, useTemplateRef, watch} from "vue";

const show = defineModel('show')
const props = defineProps({
    patient: Object
})
const emits = defineEmits([
    'onSubmit'
])

const formRef = useTemplateRef('form')
const loading = ref(true)
const model = ref({
    observable_reason: null
})
const rules = {
    observable_reason: {
        required: true,
    }
}

const resetForm = () => {
    model.value = {
        observable_reason: null
    }
}

const actionText = computed(() => props.patient.in_observable ? 'Просмотр контроля' : 'Постановка на контроль')

const submit = () => {
    formRef.value?.validate((errors) => {
        if (!errors) {
            emits('onSubmit', {
                ...props.patient,
                ...model.value
            })
            cancel()
        }
        else {
            alert(errors)
        }
    })
}
const cancel = () => {
    resetForm()
    show.value = false
    loading.value = true
}

const onAfterEnter = () => {
    model.value.observable_reason = props.patient.observable?.observable_reason
    loading.value = false
}
</script>

<template>
    <NModal v-model:show="show"
            :mask-closable="false"
            @afterLeave="cancel"
            @afterEnter="onAfterEnter"
            segmented
            draggable
            class="max-w-lg relative overflow-hidden"
            preset="card"
    >
        <template #header>
            <NSpace vertical :size="1" class="text-base font-normal">
                <NText strong>
                    {{ patient.full_name ?? '' }}
                </NText>
                <NText depth="3" class="text-sm">
                    {{ actionText }}
                </NText>
            </NSpace>
        </template>
        <NForm ref="form" :model="model" :rules="rules">
            <NFormItem label="Опишите причину" path="observable_reason" :show-feedback="false">
                <NInput type="textarea" :rows="6" :resizable="false" v-model:value="model.observable_reason" />
            </NFormItem>
        </NForm>
        <template #action>
            <NSpace align="center" justify="end">
                <NButton type="primary" secondary @click="submit">
                    Сохранить
                </NButton>
            </NSpace>
        </template>
        <div v-if="loading" class="absolute inset-0 z-10 flex items-center justify-center" style="background-color: var(--n-color);">
            <NSpin size="small" description="Загрузка..." />
        </div>
    </NModal>
</template>

<style scoped>

</style>
