<script setup>
import { NSelect, NModal, NForm, NFormItem, NButton, NAlert } from 'naive-ui'
import {useReportStore} from "../../../Stores/report.js";
import {computed, ref, watch} from "vue";
import {router, Link} from "@inertiajs/vue3";
import {useDebounceFn} from "@vueuse/core";
import {useOnboardingStore} from "../../../Stores/onboarding.js";
const show = defineModel('show')

const props = defineProps({
    targetPath: {
        type: String,
        default: '/report'
    },
    submitLabel: {
        type: String,
        default: 'Перейти к заполнению сводной'
    },
    withExistsCheck: {
        type: Boolean,
        default: true
    },
    onlyUserDepartment: {
        type: Boolean,
        default: true
    }
})

const reportStore = useReportStore()
const formRef = ref()

const rawUsers = ref([])
const rawDepartments = ref([])
const usersLoaded = ref(false)
const departmentsLoaded = ref(false)
const reportExists = ref(false)
const existingReportId = ref(null)
const loadingDepartmentFetch = ref(false)
const loadingUserFetch = ref(false)

const users = computed(() => rawUsers.value.map(itm => ({
    label: `${itm.FAM_V} ${itm.IM_V} ${itm.OT_V}`,
    value: itm.LPUDoctorID
})))

const departments = computed(() => rawDepartments.value.map(itm => ({
    label: itm.name_short,
    value: itm.department_id
})))

const fetchUsers = (departmentId) => {
    usersLoaded.value = []
    loadingUserFetch.value = true
    const type = props.onlyUserDepartment ? 'nurse' : 'duty'
    axios.get(`/api/app/departments/${departmentId}/users?onlyUserDepartment=${props.onlyUserDepartment}&type=${type}`)
        .then((res) => {
            rawUsers.value = res.data
            usersLoaded.value = true
        }).finally((e) => {
        loadingUserFetch.value = false
    })
}

const fetchDepartments = () => {
    if (departmentsLoaded.value) return
    loadingDepartmentFetch.value = true
    axios.get('/api/app/departments')
        .then((res) => {
            rawDepartments.value = res.data
            departmentsLoaded.value = true
        }).finally((e) => {
        loadingDepartmentFetch.value = false
    })
}

const checkReportExists = async (userId, departmentId) => {
    if (!props.withExistsCheck || !userId || !departmentId) {
        reportExists.value = false;
        existingReportId.value = null;
        return;
    }

    try {
        await axios.get(`/api/report/check`, {
            params: {
                department_id: departmentId,
            }
        }).then(res => {
            reportExists.value = res.data.exists;
            existingReportId.value = res.data.report_id || null;
        });

    } catch (error) {
        console.error('Ошибка при проверке отчета:', error);
        reportExists.value = false;
        existingReportId.value = null;
    }
}

// Дебаунс функция
const debouncedCheck = useDebounceFn((userId, departmentId) => {
    checkReportExists(userId, departmentId);
}, 300);

// Автоматическая проверка при изменении любого из полей
watch(
    () => [reportStore.reportInfo.userId, reportStore.reportInfo.departmentId],
    ([newUserId, newDepartmentId], [oldUserId, oldDepartmentId]) => {
        // Проверяем, что оба поля заполнены и корректны
        const userIdValid = newUserId && Number.isInteger(Number(newUserId));
        const departmentIdValid = newDepartmentId && Number.isInteger(Number(newDepartmentId));

        if (userIdValid && departmentIdValid) {
            debouncedCheck(newUserId, newDepartmentId);
        } else {
            reportExists.value = false;
            existingReportId.value = null;
        }
    },
    { deep: true }
);

const rules = {
    userId: {
        required: true,
        validator: (rule, value) => {
            return Number.isInteger(value) ?? false
        },
        trigger: ['change', 'blur'],
        message: 'Выберите ответственного'
    },
    departmentId: {
        required: true,
        validator: (rule, value) => {
            return Number.isInteger(value) ?? false
        },
        trigger: ['change', 'blur'],
        message: 'Выберите отделение'
    },
}

watch(() => show.value, (opened) => {
    if (!opened) return

    reportStore.reportInfo.userId = null
    reportStore.reportInfo.departmentId = null
    // fetchUsers()
    fetchDepartments()
}, {immediate: false})

const onSubmit = (e) => {
    e.preventDefault()
    formRef.value?.validate((errors) => {
        if (!errors) {
            if (reportExists.value) return
            router.visit(props.targetPath, {
                data: {
                    userId: reportStore.reportInfo.userId,
                    departmentId: reportStore.reportInfo.departmentId
                }
            })
        }
        else {
            window.$message.warning('Заполните выделенные поля')
        }
    })
}

const onAfterLeave = () => {
    reportStore.reportInfo.userId = null
    reportStore.reportInfo.departmentId = null
    reportExists.value = false
    existingReportId.value = null
}

const onChangeDepartment = (departmentId) => {
    usersLoaded.value = false
    fetchUsers(departmentId)
}

const onboarding = useOnboardingStore()
const onAfterEnter = () => {
    // Если онбординг активен и текущий шаг имеет opensModal, переходим к следующему
    if (onboarding.isActive) {
        const currentSteps = onboarding.currentTourSteps
        const currentStep = currentSteps[onboarding.activeStepIndex]
        if (currentStep?.opensModal) {
            console.log(currentStep)
            onboarding.setStep(onboarding.activeStepIndex + 1) // переходим на шаг внутри модалки
        }
    }
}
</script>

<template>
    <NModal v-model:show="show"
            preset="card"
            class="max-w-[420px]"
            :mask-closable="false"
            @before-leave="onAfterLeave"
            @after-enter="onAfterEnter"
    >
        <NForm id="select-user-form" ref="formRef" :model="reportStore.reportInfo" :rules="rules">
            <NFormItem id="modal-select-user-department" label="Выберите отделение" path="departmentId">
                <NSelect :options="departments"
                         :loading="loadingDepartmentFetch"
                         @change="onChangeDepartment"
                         v-model:value="reportStore.reportInfo.departmentId"
                         filterable
                />
            </NFormItem>
            <NFormItem id="modal-select-user-doctor" label="Выберите ответственного" path="userId">
                <NSelect :options="users"
                         :loading="loadingUserFetch"
                         :disabled="!usersLoaded"
                         v-model:value="reportStore.reportInfo.userId"
                         filterable
                />
            </NFormItem>
        </NForm>
        <NAlert v-if="reportExists && withExistsCheck" type="warning">
            Сводная уже создана.
            <NButton :tag="Link" text :href="`${targetPath}?userId=${reportStore.reportInfo.userId}&departmentId=${reportStore.reportInfo.departmentId}`">
                Перейти
            </NButton>
        </NAlert>
        <template #action>
            <NButton form-id="select-user-form"
                     id="modal-select-user-submit"
                     type="primary"
                     block
                     @click="onSubmit"
                     :disabled="withExistsCheck && reportExists">
                {{ submitLabel }}
            </NButton>
        </template>
    </NModal>
</template>

<style scoped>

</style>
