<script setup lang="ts">
import type { MailMessageDetailDto } from '~/modules/mail/services/dto/mail'
import type { Task } from '~/modules/project-management/services/dto/task'
import type { Project } from '~/modules/project-management/services/dto/project'
import type { TaskGroup } from '~/modules/project-management/services/dto/task-group'
import type { UserData } from '~/services/dto/user-data'
import { useMailService } from '~/modules/mail/services/mail'
import { useProjectService } from '~/modules/project-management/services/projects'
import { useTaskGroupService } from '~/modules/project-management/services/task-groups'
import { useUserService } from '~/services/users'
import { useAuthStore } from '~/shared/stores/auth'

const props = defineProps<{
    modelValue: boolean
    messageId: number
    messageDetail: MailMessageDetailDto | null
}>()
const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    created: [task: Task]
}>()

const { t } = useI18n()
const auth = useAuthStore()
const mailService = useMailService()
const projectService = useProjectService()
const taskGroupService = useTaskGroupService()
const userService = useUserService()

const projectId = ref<number | null>(null)
const taskGroupId = ref<number | null>(null)
const assigneeId = ref<number | null>(null)
const statusId = ref<number | null>(null)
const isSubmitting = ref(false)
const touchedProject = ref(false)

const projects = ref<Project[]>([])
const groups = ref<TaskGroup[]>([])
const users = ref<UserData[]>([])
const loadingGroups = ref(false)

const projectOptions = computed(() => projects.value.map(p => ({ label: p.name, value: p.id })))
const groupOptions = computed(() => groups.value.filter(g => !g.archived).map(g => ({ label: g.title, value: g.id })))
const userOptions = computed(() => users.value.map(u => ({ label: u.username, value: u.id })))

const selectedProject = computed(() => projects.value.find(p => p.id === projectId.value) ?? null)
const statusOptions = computed(() =>
    (selectedProject.value?.workflow?.statuses ?? []).map(s => ({ label: s.label, value: s.id })),
)

onMounted(async () => {
    const [projs, us] = await Promise.all([
        projectService.getAll({ archived: false }),
        userService.getAll(),
    ])
    projects.value = projs
    users.value = us
})

watch(projectId, async (pid) => {
    taskGroupId.value = null
    statusId.value = selectedProject.value?.workflow?.statuses?.[0]?.id ?? null
    groups.value = []
    if (!pid) return
    loadingGroups.value = true
    try {
        groups.value = await taskGroupService.getByProject(pid)
    } finally {
        loadingGroups.value = false
    }
})

watch(() => props.modelValue, (open) => {
    if (open) {
        projectId.value = null
        taskGroupId.value = null
        statusId.value = null
        assigneeId.value = auth.user?.id ?? null
        touchedProject.value = false
    }
})

function close(): void {
    emit('update:modelValue', false)
}

async function handleSubmit(): Promise<void> {
    touchedProject.value = true
    if (!projectId.value) return
    isSubmitting.value = true
    try {
        const task = await mailService.createTaskFromMail(props.messageId, {
            projectId: projectId.value,
            taskGroupId: taskGroupId.value ?? undefined,
            assigneeId: assigneeId.value ?? undefined,
            statusId: statusId.value ?? undefined,
        })
        emit('created', task)
        close()
    } finally {
        isSubmitting.value = false
    }
}
</script>

<template>
    <AppModal
        :model-value="modelValue"
        width="lg"
        :title="t('mail.createTaskModal.title')"
        @update:model-value="emit('update:modelValue', $event)"
    >
        <div class="space-y-5">
            <div v-if="messageDetail" class="rounded-lg border border-neutral-200 bg-neutral-50 px-4 py-3 text-sm">
                <p class="truncate font-medium text-neutral-800">{{ messageDetail.header.subject ?? t('mail.noSubject') }}</p>
                <p class="mt-0.5 truncate text-xs text-neutral-500">{{ messageDetail.header.fromName ?? messageDetail.header.fromEmail }}</p>
                <p class="mt-2 text-xs italic text-neutral-400">{{ t('mail.createTaskModal.titleHint') }}</p>
                <p class="text-xs italic text-neutral-400">{{ t('mail.createTaskModal.descriptionHint') }}</p>
            </div>

            <div>
                <MalioSelect v-model="projectId" :options="projectOptions" :label="t('mail.createTaskModal.projectLabel')" :empty-option-label="t('mail.createTaskModal.projectPlaceholder')" group-class="w-full" />
                <p v-if="touchedProject && !projectId" class="mt-1 text-xs text-red-500">{{ t('mail.createTaskModal.projectLabel').replace(' *', '') }} requis</p>
            </div>

            <div v-if="projectId">
                <MalioSelect v-model="taskGroupId" :options="groupOptions" :label="t('mail.createTaskModal.groupLabel')" :empty-option-label="t('mail.createTaskModal.groupPlaceholder')" group-class="w-full" :disabled="loadingGroups" />
            </div>

            <div v-if="projectId">
                <MalioSelect v-model="statusId" :options="statusOptions" :label="t('mail.createTaskModal.statusLabel')" group-class="w-full" />
            </div>

            <div>
                <MalioSelect v-model="assigneeId" :options="userOptions" :label="t('mail.createTaskModal.assigneeLabel')" :empty-option-label="t('mail.createTaskModal.assigneePlaceholder')" group-class="w-full" />
            </div>
        </div>

        <template #footer>
            <MalioButton variant="tertiary" label="Annuler" button-class="w-auto px-4" @click="close" />
            <MalioButton :label="t('mail.createTaskModal.submit')" button-class="w-auto px-6" :disabled="isSubmitting" @click="handleSubmit" />
        </template>
    </AppModal>
</template>
