<script setup lang="ts">
import type { MailMessageHeaderDto } from '~/services/dto/mail'
import { useMailService } from '~/services/mail'
import { useMailStore } from '~/stores/mail'

const props = defineProps<{
    modelValue: boolean
    /** ID de la tâche cible (destinataire du lien) */
    taskId: number
}>()

const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    /** Émis après liaison réussie — payload = id du message lié */
    linked: [messageId: number]
}>()

const { t } = useI18n()
const mailService = useMailService()
const mailStore = useMailStore()

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

const searchQuery = ref('')
const allMessages = ref<MailMessageHeaderDto[]>([])
const selectedMessage = ref<MailMessageHeaderDto | null>(null)
const isLoading = ref(false)
const isSubmitting = ref(false)

// ─── Filtrage local (pas d'appel API par frappe — les messages sont déjà chargés) ──

const filteredMessages = computed(() => {
    const q = searchQuery.value.toLowerCase().trim()
    if (!q) return allMessages.value
    return allMessages.value.filter(
        (m) =>
            (m.subject ?? '').toLowerCase().includes(q)
            || (m.fromName ?? '').toLowerCase().includes(q)
            || (m.fromEmail ?? '').toLowerCase().includes(q),
    )
})

// ─── Chargement à l'ouverture ─────────────────────────────────────────────

watch(() => props.modelValue, async (open) => {
    if (!open) return
    searchQuery.value = ''
    selectedMessage.value = null
    isLoading.value = true
    try {
        // Utiliser le dossier actuellement sélectionné dans le store si disponible,
        // sinon fallback sur INBOX.
        const folderPath = mailStore.selectedFolderPath ?? 'INBOX'
        const page = await mailService.listMessages(folderPath, undefined, 50)
        allMessages.value = page.items
    } finally {
        isLoading.value = false
    }
})

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

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

function selectMessage(msg: MailMessageHeaderDto): void {
    selectedMessage.value = msg
}

async function handleSubmit(): Promise<void> {
    if (!selectedMessage.value) return
    isSubmitting.value = true
    try {
        await mailService.linkTask(selectedMessage.value.id, props.taskId)
        emit('linked', selectedMessage.value.id)
        close()
    } finally {
        isSubmitting.value = false
    }
}

// ─── Formatage ────────────────────────────────────────────────────────────

function formatDate(iso: string | null): string {
    if (!iso) return ''
    return new Date(iso).toLocaleDateString('fr', {
        day: '2-digit',
        month: 'short',
        year: 'numeric',
    })
}
</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">
                <div
                    class="absolute inset-0 bg-slate-900/40 backdrop-blur-sm"
                    @click="close"
                />

                <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.pickerModal.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-4">
                        <!-- Recherche locale -->
                        <input
                            v-model="searchQuery"
                            type="text"
                            :placeholder="t('mail.pickerModal.searchPlaceholder')"
                            class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
                        />

                        <!-- Résultats -->
                        <div class="max-h-80 overflow-y-auto rounded-md border border-neutral-200 divide-y divide-neutral-100">
                            <!-- Chargement -->
                            <div
                                v-if="isLoading"
                                class="flex items-center justify-center py-8 text-sm text-neutral-400"
                            >
                                <Icon name="material-symbols:progress-activity" size="18" class="mr-2 animate-spin" />
                                {{ t('mail.pickerModal.loading') }}
                            </div>

                            <!-- Vide -->
                            <div
                                v-else-if="filteredMessages.length === 0"
                                class="py-8 text-center text-sm text-neutral-400 italic"
                            >
                                {{ t('mail.pickerModal.empty') }}
                            </div>

                            <!-- Liste -->
                            <button
                                v-for="msg in filteredMessages"
                                :key="msg.id"
                                type="button"
                                class="flex w-full items-start gap-3 px-4 py-3 text-left text-sm transition-colors hover:bg-neutral-50"
                                :class="selectedMessage?.id === msg.id
                                    ? 'bg-primary-50 border-l-2 border-primary-500'
                                    : 'border-l-2 border-transparent'"
                                @click="selectMessage(msg)"
                            >
                                <Icon
                                    name="material-symbols:mail-outline"
                                    size="16"
                                    class="mt-0.5 flex-shrink-0 text-neutral-400"
                                />
                                <div class="min-w-0 flex-1">
                                    <p class="truncate font-medium text-neutral-800">
                                        {{ msg.subject ?? t('mail.noSubject') }}
                                    </p>
                                    <p class="flex items-center gap-2 text-xs text-neutral-500">
                                        <span class="truncate">{{ msg.fromName ?? msg.fromEmail }}</span>
                                        <span class="flex-shrink-0">·</span>
                                        <span class="flex-shrink-0">{{ formatDate(msg.sentAt ?? msg.receivedAt) }}</span>
                                    </p>
                                </div>
                                <Icon
                                    v-if="selectedMessage?.id === msg.id"
                                    name="material-symbols:check-circle"
                                    size="16"
                                    class="flex-shrink-0 text-primary-500"
                                />
                            </button>
                        </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.pickerModal.submit')"
                            button-class="w-auto px-6"
                            :disabled="!selectedMessage || 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>
