<script setup>
import {computed, ref, watch} from "vue";
import {NButton, NEmpty, NInput, NList, NListItem, NModal, NSpin} from "naive-ui";
import {useReportStore} from "../../../Stores/report.js";

const props = defineProps({
    patient: {
        type: Object,
        default: null,
    }
})

const show = defineModel('show', {type: Boolean, default: false})
const reportStore = useReportStore()
const search = ref('')
const results = ref([])
const loading = ref(false)

const canSearch = computed(() => search.value.trim().length >= 2)

const runSearch = async () => {
    if (!canSearch.value) {
        results.value = []
        return
    }

    loading.value = true
    try {
        results.value = await reportStore.searchMisPatients(
            reportStore.reportInfo.department.department_id,
            search.value.trim()
        )
    } finally {
        loading.value = false
    }
}

const linkPatient = async (patient) => {
    if (!props.patient?.department_patient_id || !patient.medical_history_id) {
        return
    }

    await reportStore.linkManualPatient(props.patient.department_patient_id, patient.medical_history_id)
    show.value = false
    window.$message.success('Пациент связан с МИС')
}

watch(show, (value) => {
    if (!value) {
        search.value = ''
        results.value = []
    }
})
</script>

<template>
    <NModal v-model:show="show" preset="card" title="Связать с пациентом МИС" class="max-w-2xl">
        <div class="space-y-4">
            <NInput v-model:value="search" placeholder="Введите фамилию, имя или отчество" @input="runSearch" />

            <div v-if="loading" class="flex justify-center py-6">
                <NSpin />
            </div>

            <NList v-else-if="results.length">
                <NListItem v-for="item in results" :key="item.id">
                    <div class="flex items-center justify-between gap-4">
                        <div>
                            <div class="font-medium">{{ item.fullname }}</div>
                            <div class="text-sm text-slate-500">
                                {{ item.birth_date || 'Без даты рождения' }}
                                <span v-if="item.mkb?.ds"> · {{ item.mkb.ds }}</span>
                            </div>
                        </div>
                        <NButton size="small" @click="linkPatient(item)">Связать</NButton>
                    </div>
                </NListItem>
            </NList>

            <NEmpty v-else description="Совпадений не найдено" />
        </div>
    </NModal>
</template>
