<script setup lang="ts">
import type { MailMessageDetailDto } from '~/services/dto/mail'
import type { Task } from '~/services/dto/task'
import type { Project } from '~/services/dto/project'
import type { TaskGroup } from '~/services/dto/task-group'
import type { TaskPriority } from '~/services/dto/task-priority'
import { useMailService } from '~/services/mail'
import { useProjectService } from '~/services/projects'
import { useTaskGroupService } from '~/services/task-groups'
import { useTaskPriorityService } from '~/services/task-priorities'

const props = defineProps<{
    /** v-model: true = modal ouvert */
    modelValue: boolean
    /** ID BDD du message source */
    messageId: number
    /** Détail du message (pour afficher sujet/expéditeur en lecture seule) */
    messageDetail: MailMessageDetailDto | null
}>()

const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    /** Émis après création réussie — payload = tâche créée */
    created: [task: Task]
}>()

const { t } = useI18n()
const mailService = useMailService()
const projectService = useProjectService()
const taskGroupService = useTaskGroupService()
const priorityService = useTaskPriorityService()

// ─── État formulaire ──────────────────────────────────────────────────────

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

// ─── Données de référence ─────────────────────────────────────────────────

const projects = ref<Project[]>([])
const groups = ref<TaskGroup[]>([])
const priorities = ref<TaskPriority[]>([])
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 priorityOptions = computed(() =>
    priorities.value.map(p => ({ label: p.label, value: p.id })),
)

// ─── Chargement initial ───────────────────────────────────────────────────

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

// Recharger les groupes quand le projet change
watch(projectId, async (pid) => {
    taskGroupId.value = null
    groups.value = []
    if (!pid) return
    loadingGroups.value = true
    try {
        groups.value = await taskGroupService.getByProject(pid)
    } finally {
        loadingGroups.value = false
    }
})

// Reset formulaire à l'ouverture
watch(() => props.modelValue, (open) => {
    if (open) {
        projectId.value = null
        taskGroupId.value = null
        priorityId.value = null
        touchedProject.value = false
    }
})

// ─── Actions ──────────────────────────────────────────────────────────────

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,
            priority: priorityId.value ? `/api/task_priorities/${priorityId.value}` : undefined,
        })
        emit('created', task)
        close()
    } finally {
        isSubmitting.value = false
    }
}
</script>

<template>
    <Teleport v-if="modelValue" to="body">
        <Transition name="mail-modal" appear>
            <div class="fixed inset-0 z-50 flex items-center justify-center p-4">
                <!-- Backdrop -->
                <div
                    class="absolute inset-0 bg-slate-900/40 backdrop-blur-sm"
                    @click="close"
                />

                <!-- Modal -->
                <div
                    class="relative z-10 w-full max-w-lg rounded-2xl bg-white shadow-2xl ring-1 ring-black/5 overflow-hidden"
                    style="max-height: min(90vh, 640px)"
                >
                    <!-- Header -->
                    <div class="flex items-center justify-between border-b border-neutral-100 bg-neutral-50/80 px-6 py-4">
                        <h2 class="text-base font-bold text-neutral-900">
                            {{ t('mail.createTaskModal.title') }}
                        </h2>
                        <MalioButtonIcon
                            icon="mdi:close"
                            aria-label="Fermer"
                            variant="ghost"
                            icon-size="20"
                            @click="close"
                        />
                    </div>

                    <!-- Corps -->
                    <div class="overflow-y-auto px-6 py-5 space-y-5">
                        <!-- Info mail source (lecture seule) -->
                        <div
                            v-if="messageDetail"
                            class="rounded-lg border border-neutral-200 bg-neutral-50 px-4 py-3 text-sm"
                        >
                            <p class="font-medium text-neutral-800 truncate">
                                {{ messageDetail.header.subject ?? t('mail.noSubject') }}
                            </p>
                            <p class="mt-0.5 text-xs text-neutral-500 truncate">
                                {{ messageDetail.header.fromName ?? messageDetail.header.fromEmail }}
                            </p>
                            <p class="mt-2 text-xs text-neutral-400 italic">
                                {{ t('mail.createTaskModal.titleHint') }}
                            </p>
                            <p class="text-xs text-neutral-400 italic">
                                {{ t('mail.createTaskModal.descriptionHint') }}
                            </p>
                        </div>

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

                        <!-- Sélection groupe (optionnel, chargé après projet) -->
                        <div v-if="projectId">
                            <MalioSelect
                                v-model="taskGroupId"
                                :options="groupOptions"
                                :label="t('mail.createTaskModal.groupLabel')"
                                :empty-option-label="t('mail.createTaskModal.groupPlaceholder')"
                                min-width="w-full"
                                :disabled="loadingGroups"
                            />
                        </div>

                        <!-- Sélection priorité (optionnelle) — MalioSelect car les values sont number | null -->
                        <div>
                            <MalioSelect
                                v-model="priorityId"
                                :options="priorityOptions"
                                :label="t('mail.createTaskModal.priorityLabel')"
                                :empty-option-label="t('mail.createTaskModal.priorityPlaceholder')"
                                min-width="w-full"
                            />
                        </div>
                    </div>

                    <!-- Footer -->
                    <div class="flex justify-end gap-3 border-t border-neutral-100 px-6 py-4">
                        <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"
                        />
                    </div>
                </div>
            </div>
        </Transition>
    </Teleport>
</template>

<style scoped>
.mail-modal-enter-active,
.mail-modal-leave-active {
    transition: opacity 0.2s ease;
}

.mail-modal-enter-active > div:last-child,
.mail-modal-leave-active > div:last-child {
    transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.2s ease;
}

.mail-modal-enter-from,
.mail-modal-leave-to {
    opacity: 0;
}

.mail-modal-enter-from > div:last-child {
    transform: scale(0.95) translateY(8px);
    opacity: 0;
}
</style>
