<template>
    <Teleport v-if="isOpen" to="body">
        <Transition name="task-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 flex w-full max-w-2xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl ring-1 ring-black/5"
                    style="max-height: min(90vh, 900px)"
                >
                    <!-- Header -->
                    <div class="border-b border-neutral-100 bg-neutral-50/80 px-4 py-4 sm:px-8 sm:py-5">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-3">
                                <span
                                    v-if="isEditing && task?.project?.code && task?.number"
                                    class="rounded-md bg-primary-500 px-2.5 py-1 text-xs font-bold tracking-wide text-white"
                                >
                                    {{ task.project.code }}-{{ task.number }}
                                </span>
                                <h2 class="text-lg font-bold tracking-tight text-neutral-900">
                                    {{ isEditing ? 'Modifier un ticket' : 'Ajouter un ticket' }}
                                </h2>
                            </div>
                            <button
                                type="button"
                                class="flex h-8 w-8 items-center justify-center rounded-lg text-neutral-400 transition-colors hover:bg-neutral-200/60 hover:text-neutral-600"
                                @click="close"
                            >
                                <Icon name="mdi:close" size="20" />
                            </button>
                        </div>

                        <!-- Client ticket link -->
                        <div
                            v-if="isEditing && task?.clientTicket"
                            class="mt-2 flex items-center gap-2 rounded-lg bg-blue-50 px-3 py-2"
                        >
                            <Icon name="heroicons:user-circle" class="h-5 w-5 text-blue-500" />
                            <span class="text-sm font-medium text-blue-700">
                                {{ $t('clientTicket.linkedTooltip', { number: 'CT-' + String(task.clientTicket.number).padStart(3, '0') }) }}
                            </span>
                            <span
                                class="ml-auto rounded-full px-2 py-0.5 text-xs font-semibold"
                                :class="ticketStatusClass(task.clientTicket.status)"
                            >
                                {{ $t(`clientTicket.status.${task.clientTicket.status}`) }}
                            </span>
                        </div>
                    </div>

                    <!-- Body -->
                    <form @submit.prevent="handleSubmit" class="overflow-y-auto px-4 py-4 sm:px-8 sm:py-6">
                        <!-- Title -->
                        <MalioInputText
                            v-model="form.title"
                            label="Titre"
                            input-class="w-full"
                            :error="touched.title && !form.title.trim() ? 'Le titre est requis' : ''"
                            @blur="touched.title = true"
                        />

                        <!-- Two-column selects -->
                        <div class="mt-4 grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2">
                            <MalioSelect
                                v-model="form.statusId"
                                :options="statusOptions"
                                label="Statut"
                                empty-option-label="Aucun statut"
                                min-width="w-full"
                            />
                            <MalioSelect
                                v-model="form.assigneeId"
                                :options="userOptions"
                                label="User"
                                empty-option-label="Aucun utilisateur"
                                min-width="w-full"
                            />
                            <MalioSelect
                                v-model="form.effortId"
                                :options="effortOptions"
                                label="Effort"
                                empty-option-label="Aucun effort"
                                min-width="w-full"
                            />
                            <MalioSelect
                                v-model="form.priorityId"
                                :options="priorityOptions"
                                label="Priorité"
                                empty-option-label="Aucune priorité"
                                min-width="w-full"
                            />
                            <MalioSelect
                                v-model="form.groupId"
                                :options="groupOptions"
                                label="Groupe"
                                empty-option-label="Aucun groupe"
                                min-width="w-full"
                            />
                            <MalioSelect
                                v-if="clientTicketOptions.length"
                                v-model="form.clientTicketId"
                                :options="clientTicketOptions"
                                label="Ticket client"
                                empty-option-label="Aucun ticket client"
                                min-width="w-full"
                            />
                        </div>

                        <!-- Tags -->
                        <div v-if="tags.length" class="mt-5">
                            <p class="mb-2 text-sm font-medium text-neutral-700">Tags</p>
                            <div class="flex flex-wrap gap-2">
                                <label
                                    v-for="tag in tags"
                                    :key="tag.id"
                                    class="cursor-pointer rounded-full px-3 py-1 text-xs font-semibold transition-all"
                                    :class="form.tagIds.includes(tag.id)
                                        ? 'text-white shadow-sm'
                                        : 'bg-neutral-100 text-neutral-600 hover:bg-neutral-200'"
                                    :style="form.tagIds.includes(tag.id) ? { backgroundColor: tag.color } : {}"
                                >
                                    <input
                                        type="checkbox"
                                        class="hidden"
                                        :value="tag.id"
                                        :checked="form.tagIds.includes(tag.id)"
                                        @change="toggleTag(tag.id)"
                                    />
                                    {{ tag.label }}
                                </label>
                            </div>
                        </div>

                        <!-- Description -->
                        <div class="mt-5">
                            <MalioInputTextArea
                                v-model="form.description"
                                label="Description"
                                :size="3"
                            />
                        </div>

                        <!-- Documents -->
                        <TaskDocumentUpload
                            v-if="isEditing && task && isAdmin"
                            :task-id="task.id"
                            @uploaded="handleDocumentUploaded"
                        />
                        <TaskDocumentList
                            v-if="isEditing && task"
                            :documents="documents"
                            :is-admin="isAdmin"
                            @preview="openPreview"
                            @delete="handleDeleteDocument"
                        />

                        <!-- Document preview modal -->
                        <TaskDocumentPreview
                            :document="previewDoc"
                            :has-prev="previewIndex > 0"
                            :has-next="previewIndex < documents.length - 1"
                            @close="previewDoc = null"
                            @prev="prevPreview"
                            @next="nextPreview"
                        />

                        <!-- Git section -->
                        <TaskGitSection
                            v-if="hasGitea && isEditing && task"
                            :task="task"
                            :gitea-url="giteaUrl"
                        />

                        <!-- BookStack links -->
                        <TaskBookStackLinks
                            v-if="hasBookStack && isEditing && task"
                            :task-id="task.id"
                        />

                        <!-- Footer -->
                        <div
                            class="mt-6 flex items-center border-t border-neutral-100 pt-5"
                            :class="isEditing ? 'justify-between' : 'justify-end'"
                        >
                            <button
                                v-if="isEditing"
                                type="button"
                                class="rounded-lg bg-red-50 px-4 py-2 text-sm font-semibold text-red-600 transition-colors hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-50"
                                :disabled="isSubmitting"
                                @click="confirmDeleteOpen = true"
                            >
                                Supprimer
                            </button>
                            <div class="flex gap-3">
                                <button
                                    v-if="canArchive"
                                    type="button"
                                    class="rounded-lg border border-neutral-300 px-4 py-2 text-sm font-semibold text-neutral-700 transition-colors hover:bg-neutral-50 disabled:cursor-not-allowed disabled:opacity-50"
                                    :disabled="isSubmitting"
                                    @click="handleArchive"
                                >
                                    {{ $t('archive.archiveButton') }}
                                </button>
                                <button
                                    v-if="canUnarchive"
                                    type="button"
                                    class="rounded-lg border border-neutral-300 px-4 py-2 text-sm font-semibold text-neutral-700 transition-colors hover:bg-neutral-50 disabled:cursor-not-allowed disabled:opacity-50"
                                    :disabled="isSubmitting"
                                    @click="handleUnarchive"
                                >
                                    {{ $t('archive.unarchiveButton') }}
                                </button>
                                <button
                                    type="button"
                                    class="rounded-lg border border-neutral-300 px-4 py-2 text-sm font-semibold text-neutral-700 transition-colors hover:bg-neutral-50"
                                    @click="close"
                                >
                                    Annuler
                                </button>
                                <button
                                    type="submit"
                                    class="rounded-lg bg-primary-500 px-6 py-2 text-sm font-semibold text-white transition-colors hover:bg-secondary-500 disabled:cursor-not-allowed disabled:opacity-50"
                                    :disabled="isSubmitting"
                                >
                                    Enregistrer
                                </button>
                            </div>
                        </div>
                    </form>

                    <ConfirmDeleteTaskModal
                        v-model="confirmDeleteOpen"
                        @confirm="handleDelete"
                    />

                    <!-- Confirm delete document modal -->
                    <ConfirmDeleteDocumentModal
                        v-model="confirmDeleteDocOpen"
                        @confirm="confirmDeleteDocument"
                    />
                </div>
            </div>
        </Transition>
    </Teleport>
</template>

<script setup lang="ts">
import type { Task, TaskWrite } from '~/services/dto/task'
import type { TaskDocument } from '~/services/dto/task-document'
import type { ClientTicket } from '~/services/dto/client-ticket'
import { useGiteaService } from '~/services/gitea'
import { useTaskDocumentService } from '~/services/task-documents'
import { useClientTicketService } from '~/services/client-tickets'
import ConfirmDeleteDocumentModal from '~/components/ui/ConfirmDeleteDocumentModal.vue'
import type { TaskStatus } from '~/services/dto/task-status'
import type { TaskEffort } from '~/services/dto/task-effort'
import type { TaskPriority } from '~/services/dto/task-priority'
import type { TaskTag } from '~/services/dto/task-tag'
import type { TaskGroup } from '~/services/dto/task-group'
import type { UserData } from '~/services/dto/user-data'
import { useTaskService } from '~/services/tasks'

const props = defineProps<{
    modelValue: boolean
    task: Task | null
    projectId: number
    statuses: TaskStatus[]
    efforts: TaskEffort[]
    priorities: TaskPriority[]
    tags: TaskTag[]
    groups: TaskGroup[]
    users: UserData[]
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'saved'): void
}>()

const isOpen = computed({
    get: () => props.modelValue,
    set: (v) => emit('update:modelValue', v),
})

function close() {
    isOpen.value = false
}

const isEditing = computed(() => !!props.task)
const isSubmitting = ref(false)
const confirmDeleteOpen = ref(false)

const giteaUrl = ref('')
const { getSettings: getGiteaSettings } = useGiteaService()

const hasGitea = computed(() => {
    return !!props.task?.project?.giteaOwner && !!props.task?.project?.giteaRepo && !!giteaUrl.value
})

const hasBookStack = computed(() => {
    return !!props.task?.project?.bookstackShelfId
})

const form = reactive({
    title: '',
    description: '',
    statusId: null as number | null,
    effortId: null as number | null,
    priorityId: null as number | null,
    assigneeId: null as number | null,
    groupId: null as number | null,
    tagIds: [] as number[],
    clientTicketId: null as number | null,
})

const touched = reactive({
    title: false,
})

const statusOptions = computed(() =>
    props.statuses.map(s => ({ label: s.label, value: s.id }))
)

const effortOptions = computed(() =>
    props.efforts.map(e => ({ label: e.label, value: e.id }))
)

const priorityOptions = computed(() =>
    props.priorities.map(p => ({ label: p.label, value: p.id }))
)

const userOptions = computed(() =>
    props.users.map(u => ({ label: u.username, value: u.id }))
)

const groupOptions = computed(() =>
    props.groups.map(g => ({ label: g.title, value: g.id }))
)

const canArchive = computed(() => {
    if (!isEditing.value || !props.task) return false
    if (props.task.archived) return false
    const status = props.statuses.find(s => s.id === props.task?.status?.id)
    return !!status?.isFinal
})

const canUnarchive = computed(() => {
    return isEditing.value && !!props.task?.archived
})

function toggleTag(id: number) {
    const idx = form.tagIds.indexOf(id)
    if (idx >= 0) {
        form.tagIds.splice(idx, 1)
    } else {
        form.tagIds.push(id)
    }
}

function populateForm(task: Task | null) {
    if (task) {
        form.title = task.title ?? ''
        form.description = task.description ?? ''
        form.statusId = task.status?.id ?? null
        form.effortId = task.effort?.id ?? null
        form.priorityId = task.priority?.id ?? null
        form.assigneeId = task.assignee?.id ?? null
        form.groupId = task.group?.id ?? null
        form.tagIds = task.tags.map(t => t.id)
        form.clientTicketId = task.clientTicket?.id ?? null
    } else {
        form.title = ''
        form.description = ''
        form.statusId = null
        form.effortId = null
        form.priorityId = null
        form.assigneeId = null
        form.groupId = null
        form.tagIds = []
        form.clientTicketId = null
    }
    touched.title = false
}

watch(() => props.modelValue, async (open) => {
    if (open) {
        populateForm(props.task)
        try {
            clientTickets.value = await clientTicketService.getAll({ project: props.projectId })
        } catch {
            clientTickets.value = []
        }
    }
})

watch(() => props.task, (task) => {
    if (props.modelValue) {
        populateForm(task)
    }
})

watch(() => props.modelValue, async (open) => {
    if (open && props.task?.project?.giteaOwner && props.task?.project?.giteaRepo && !giteaUrl.value) {
        try {
            const settings = await getGiteaSettings()
            giteaUrl.value = settings.url ?? ''
        } catch {
            // Gitea not available
        }
    }
})

const { create, update, remove } = useTaskService()
const { remove: removeDocument, getByTask: getDocumentsByTask } = useTaskDocumentService()
const clientTicketService = useClientTicketService()
const { t } = useI18n()

const clientTickets = ref<ClientTicket[]>([])
const clientTicketOptions = computed(() =>
    clientTickets.value.map(ct => ({ label: `CT-${String(ct.number).padStart(3, '0')} — ${ct.title}`, value: ct.id }))
)

const authStore = useAuthStore()
const isAdmin = computed(() => authStore.user?.roles?.includes('ROLE_ADMIN') ?? false)

function ticketStatusClass(status: string): string {
    switch (status) {
        case 'new': return 'bg-blue-100 text-blue-700'
        case 'in_progress': return 'bg-yellow-100 text-yellow-700'
        case 'done': return 'bg-green-100 text-green-700'
        case 'rejected': return 'bg-red-100 text-red-700'
        default: return 'bg-neutral-100 text-neutral-700'
    }
}

const localDocuments = ref<TaskDocument[]>([])
const documents = computed(() => localDocuments.value)
const previewDoc = ref<TaskDocument | null>(null)

// Sync documents from task prop when modal opens or task changes
watch(() => props.task?.documents, (docs) => {
    localDocuments.value = docs ? [...docs] : []
}, { immediate: true })

async function refreshDocuments() {
    if (!props.task) return
    localDocuments.value = await getDocumentsByTask(props.task.id)
}

const previewIndex = computed(() => {
    if (!previewDoc.value) return -1
    return documents.value.findIndex(d => d.id === previewDoc.value!.id)
})

function openPreview(doc: TaskDocument) {
    previewDoc.value = doc
}

function prevPreview() {
    if (previewIndex.value > 0) {
        previewDoc.value = documents.value[previewIndex.value - 1]
    }
}

function nextPreview() {
    if (previewIndex.value < documents.value.length - 1) {
        previewDoc.value = documents.value[previewIndex.value + 1]
    }
}

const confirmDeleteDocOpen = ref(false)
const documentToDelete = ref<TaskDocument | null>(null)

function handleDeleteDocument(doc: TaskDocument) {
    documentToDelete.value = doc
    confirmDeleteDocOpen.value = true
}

async function confirmDeleteDocument() {
    if (!documentToDelete.value) return
    await removeDocument(documentToDelete.value.id)
    confirmDeleteDocOpen.value = false
    documentToDelete.value = null
    await refreshDocuments()
}

async function handleDocumentUploaded() {
    await refreshDocuments()
}

async function handleDelete() {
    if (!props.task) return
    isSubmitting.value = true
    try {
        await remove(props.task.id)
        confirmDeleteOpen.value = false
        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}

async function handleArchive() {
    if (!props.task) return
    const timerStore = useTimerStore()
    if (timerStore.activeEntry?.task) {
        const taskIri = typeof timerStore.activeEntry.task === 'string'
            ? timerStore.activeEntry.task
            : (timerStore.activeEntry.task as any)?.['@id'] ?? `/api/tasks/${(timerStore.activeEntry.task as any)?.id}`
        if (taskIri === `/api/tasks/${props.task.id}`) {
            await timerStore.stop()
        }
    }
    isSubmitting.value = true
    try {
        await update(props.task.id, { archived: true })
        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}

async function handleUnarchive() {
    if (!props.task) return
    isSubmitting.value = true
    try {
        await update(props.task.id, { archived: false })
        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}

async function handleSubmit() {
    touched.title = true
    if (!form.title.trim()) return

    isSubmitting.value = true
    try {
        const payload: TaskWrite = {
            title: form.title.trim(),
            description: form.description.trim() || null,
            status: form.statusId ? `/api/task_statuses/${form.statusId}` : null,
            effort: form.effortId ? `/api/task_efforts/${form.effortId}` : null,
            priority: form.priorityId ? `/api/task_priorities/${form.priorityId}` : null,
            assignee: form.assigneeId ? `/api/users/${form.assigneeId}` : null,
            group: form.groupId ? `/api/task_groups/${form.groupId}` : null,
            project: `/api/projects/${props.projectId}`,
            tags: form.tagIds.map(id => `/api/task_tags/${id}`),
            clientTicket: form.clientTicketId ? `/api/client_tickets/${form.clientTicketId}` : null,
        }

        if (isEditing.value && props.task) {
            await update(props.task.id, payload)
        } else {
            await create(payload)
        }

        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}
</script>

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

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

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

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

.task-modal-leave-to > div:last-child {
    transform: scale(0.97);
    opacity: 0;
}
</style>
