<template>
    <div class="min-w-0">
        <PageHeader>
            {{ project?.name ?? '' }}
            <template #actions>
                <div class="flex items-center gap-2">
                    <MalioButton
                        icon-name="mdi:plus"
                        icon-position="left"
                        button-class="w-auto px-3 shrink-0"
                        @click="openTaskCreate"
                    >
                        <span class="hidden sm:inline">Ajouter un ticket</span>
                        <span class="sm:hidden">Ticket</span>
                    </MalioButton>
                    <button
                        class="flex h-[40px] w-[40px] items-center justify-center rounded-md border transition-colors"
                        :class="viewMode === 'list'
                            ? 'border-primary-500 bg-primary-500 text-white'
                            : 'border-primary-500 text-primary-500 hover:bg-primary-50'"
                        title="Vue liste"
                        @click="viewMode = viewMode === 'kanban' ? 'list' : 'kanban'"
                    >
                        <Icon name="mdi:format-list-bulleted" size="20" />
                    </button>
                    <MalioButtonIcon
                        icon="heroicons:cog-6-tooth"
                        aria-label="Paramètres du projet"
                        variant="ghost"
                        @click="projectDrawerOpen = true"
                    />
                </div>
            </template>
            <template #subheader>
                <div class="mt-4 flex flex-wrap gap-3">
                    <MalioSelect
                        v-model="selectedGroupId"
                        :options="groupFilterOptions"
                        label="Groupe"
                        empty-option-label="Tous les groupes"
                        group-class="!w-40"
                        text-field="text-sm"
                        text-value="text-sm"
                    />
                    <MalioSelect
                        v-model="selectedTagId"
                        :options="tagFilterOptions"
                        label="Tags"
                        empty-option-label="Tous les tags"
                        group-class="!w-40"
                        text-field="text-sm"
                        text-value="text-sm"
                    />
                    <MalioSelect
                        v-model="selectedAssigneeId"
                        :options="userFilterOptions"
                        label="User"
                        empty-option-label="Tous les users"
                        group-class="!w-40"
                        text-field="text-sm"
                        text-value="text-sm"
                    />
                    <MalioSelect
                        v-if="viewMode === 'list'"
                        v-model="selectedStatusId"
                        :options="statusFilterOptions"
                        label="Status"
                        empty-option-label="Tous les status"
                        group-class="!w-40"
                        text-field="text-sm"
                        text-value="text-sm"
                    />
                    <MalioSelect
                        v-model="selectedPriorityId"
                        :options="priorityFilterOptions"
                        label="Priorité"
                        empty-option-label="Toutes"
                        group-class="!w-40"
                        text-field="text-sm"
                        text-value="text-sm"
                    />
                    <MalioSelect
                        v-model="selectedEffortId"
                        :options="effortFilterOptions"
                        label="Effort"
                        empty-option-label="Tous"
                        group-class="!w-40"
                        text-field="text-sm"
                        text-value="text-sm"
                    />
                </div>
            </template>
        </PageHeader>

        <!-- Kanban -->
        <div v-if="viewMode === 'kanban'" class="mt-6 flex h-[calc(100vh-200px)] gap-3 overflow-x-auto pb-4">
            <div
                v-for="status in statuses"
                :key="status.id"
                class="flex w-72 shrink-0 flex-col rounded-lg transition-colors"
                :class="dragOverStatusId === status.id ? 'bg-neutral-200' : 'bg-neutral-50'"
                @dragover.prevent
                @dragenter.prevent="onDragEnter(status.id)"
                @dragleave="onDragLeave"
                @drop.prevent="onDropStatus($event, status)"
            >
                <div
                    class="shrink-0 rounded-t-lg px-4 py-3 text-sm font-bold text-white"
                    :style="{ backgroundColor: status.color }"
                >
                    {{ status.label }} ({{ tasksByStatus(status.id).length }})
                </div>
                <div class="min-h-0 flex-1 overflow-y-auto p-3">
                    <div class="flex flex-col gap-3">
                        <TaskCard
                            v-for="task in tasksByStatus(status.id)"
                            :key="task.id"
                            :task="task"
                            @click="openTaskEdit(task)"
                        />
                        <p
                            v-if="tasksByStatus(status.id).length === 0"
                            class="py-4 text-center text-xs text-neutral-400"
                        >
                            Aucun ticket
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Backlog -->
        <div
            v-if="viewMode === 'kanban'"
            class="mt-8 rounded-lg p-4 transition-colors"
            :class="dragOverStatusId === 0 ? 'bg-tertiary-600' : 'bg-tertiary-500'"
            @dragover.prevent
            @dragenter.prevent="onDragEnter(0)"
            @dragleave="onDragLeave"
            @drop.prevent="onDropBacklog($event)"
        >
            <h2 class="text-lg font-bold text-neutral-900">Backlog ({{ backlogTasks.length }})</h2>
            <div class="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                <TaskCard
                    v-for="task in backlogTasks"
                    :key="task.id"
                    :task="task"
                    @click="openTaskEdit(task)"
                />
            </div>
        </div>

        <!-- List View -->
        <div v-if="viewMode === 'list'" class="mt-6 flex flex-col gap-2.5 rounded-[10px] bg-tertiary-500 p-2.5">
            <TaskBulkActions
                :selected-count="selectedTaskIds.size"
                :total-count="filteredTasks.length"
                :all-selected="filteredTasks.length > 0 && selectedTaskIds.size === filteredTasks.length"
                :some-selected="selectedTaskIds.size > 0 && selectedTaskIds.size < filteredTasks.length"
                :statuses="statuses"
                :users="users"
                :priorities="priorities"
                :efforts="efforts"
                :groups="groups"
                :can-archive="canArchiveSelection"
                @toggle-all="toggleSelectAll(filteredTasks)"
                @bulk-update="onBulkUpdate"
                @bulk-archive="onBulkArchive"
                @bulk-delete="onBulkDelete"
            />
            <TaskListItem
                v-for="task in filteredTasks"
                :key="task.id"
                :task="task"
                :selected="selectedTaskIds.has(task.id)"
                @click="openTaskEdit(task)"
                @toggle-select="toggleTaskSelect"
            />
            <p
                v-if="filteredTasks.length === 0"
                class="py-8 text-center text-sm text-neutral-400"
            >
                Aucun ticket
            </p>
        </div>

        <TaskModal
            v-model="taskDrawerOpen"
            :task="selectedTask"
            :project-id="projectId"
            :statuses="statuses"
            :efforts="efforts"
            :priorities="priorities"
            :tags="tags"
            :groups="groups"
            :users="users"
            @saved="onSaved"
        />

        <ProjectDrawer
            v-model="projectDrawerOpen"
            :project="project"
            :clients="clients"
            @saved="onProjectSaved"
        />

    </div>
</template>

<script setup lang="ts">
import type { Project } from '~/modules/project-management/services/dto/project'
import type { Task } from '~/modules/project-management/services/dto/task'
import type { TaskStatus } from '~/modules/project-management/services/dto/task-status'
import type { TaskEffort } from '~/modules/project-management/services/dto/task-effort'
import type { TaskPriority } from '~/modules/project-management/services/dto/task-priority'
import type { TaskTag } from '~/modules/project-management/services/dto/task-tag'
import type { TaskGroup } from '~/modules/project-management/services/dto/task-group'
import type { UserData } from '~/services/dto/user-data'
import type { Client } from '~/modules/directory/services/dto/client'
import { useProjectService } from '~/modules/project-management/services/projects'
import { useClientService } from '~/modules/directory/services/clients'
import { useTaskService } from '~/modules/project-management/services/tasks'
import { useTaskEffortService } from '~/modules/project-management/services/task-efforts'
import { useTaskPriorityService } from '~/modules/project-management/services/task-priorities'
import { useTaskTagService } from '~/modules/project-management/services/task-tags'
import { useTaskGroupService } from '~/modules/project-management/services/task-groups'
import { useUserService } from '~/services/users'

const route = useRoute()
const router = useRouter()
const projectId = computed(() => Number(route.params.id))

useHead({ title: 'Projet' })

const projectService = useProjectService()
const clientService = useClientService()
const taskService = useTaskService()
const effortService = useTaskEffortService()
const priorityService = useTaskPriorityService()
const tagService = useTaskTagService()
const groupService = useTaskGroupService()
const userService = useUserService()

const project = ref<Project | null>(null)
const tasks = ref<Task[]>([])
const efforts = ref<TaskEffort[]>([])
const priorities = ref<TaskPriority[]>([])
const tags = ref<TaskTag[]>([])
const groups = ref<TaskGroup[]>([])
const users = ref<UserData[]>([])
const clients = ref<Client[]>([])
const isLoading = ref(true)

const statuses = computed<TaskStatus[]>(() =>
    [...(project.value?.workflow?.statuses ?? [])].sort((a, b) => a.position - b.position),
)

const selectedGroupId = ref<number | null>(null)
const selectedTagId = ref<number | null>(null)
const selectedAssigneeId = ref<number | null>(null)
const selectedStatusId = ref<number | null>(null)
const selectedPriorityId = ref<number | null>(null)
const selectedEffortId = ref<number | null>(null)
const viewMode = ref<'kanban' | 'list'>('kanban')

watch(viewMode, (mode) => {
    if (mode === 'kanban') {
        selectedStatusId.value = null
    }
})
const selectedTaskIds = reactive(new Set<number>())
const dragOverStatusId = ref<number | null>(null)
const dragCounter = ref(0)
const taskDrawerOpen = ref(false)
const projectDrawerOpen = ref(false)
const selectedTask = ref<Task | null>(null)

const groupFilterOptions = computed(() =>
    groups.value.filter(g => !g.archived).map(g => ({ label: g.title, value: g.id }))
)

const tagFilterOptions = computed(() =>
    tags.value.map(t => ({ label: t.label, value: t.id }))
)

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

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

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

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

const canArchiveSelection = computed(() => {
    if (selectedStatusId.value === null) return false
    const status = statuses.value.find(s => s.id === selectedStatusId.value)
    return status?.isFinal === true
})

const filteredTasks = computed(() => {
    let result = tasks.value.filter(t => !t.archived)
    if (selectedGroupId.value) {
        result = result.filter(t => t.group?.id === selectedGroupId.value)
    }
    if (selectedTagId.value) {
        result = result.filter(t => t.tags?.some(tag => tag.id === selectedTagId.value))
    }
    if (selectedAssigneeId.value) {
        result = result.filter(t =>
            t.assignee?.id === selectedAssigneeId.value
            || t.collaborators?.some(c => c.id === selectedAssigneeId.value)
        )
    }
    if (selectedStatusId.value) {
        result = result.filter(t => t.status?.id === selectedStatusId.value)
    }
    if (selectedPriorityId.value) {
        result = result.filter(t => t.priority?.id === selectedPriorityId.value)
    }
    if (selectedEffortId.value) {
        result = result.filter(t => t.effort?.id === selectedEffortId.value)
    }
    return result
})

watch(filteredTasks, (list) => {
    if (selectedTaskIds.size === 0) return
    const visibleIds = new Set(list.map(t => t.id))
    for (const id of selectedTaskIds) {
        if (!visibleIds.has(id)) selectedTaskIds.delete(id)
    }
})

function tasksByStatus(statusId: number): Task[] {
    return filteredTasks.value.filter(t => t.status?.id === statusId)
}

const backlogTasks = computed(() =>
    filteredTasks.value.filter(t => !t.status)
)

async function loadData() {
    isLoading.value = true
    try {
        const [p, t, e, pr, ty, g, u, c] = await Promise.all([
            projectService.getById(projectId.value),
            taskService.getByProject(projectId.value),
            effortService.getAll(),
            priorityService.getAll(),
            tagService.getAll(),
            groupService.getByProject(projectId.value),
            userService.getAll(),
            clientService.getAll(),
        ])
        project.value = p
        tasks.value = t
        efforts.value = e
        priorities.value = pr
        tags.value = ty
        groups.value = g
        users.value = u
        clients.value = c
    } finally {
        isLoading.value = false
    }
}

function openTaskCreate() {
    selectedTask.value = null
    taskDrawerOpen.value = true
    router.replace({ query: {} })
}

function openTaskEdit(task: Task) {
    selectedTask.value = task
    taskDrawerOpen.value = true
    if (project.value?.code && task.number) {
        router.replace({ query: { task: `${project.value.code}-${task.number}` } })
    }
}

watch(taskDrawerOpen, (open) => {
    if (!open) {
        router.replace({ query: {} })
    }
})

function onDragEnter(id: number) {
    dragCounter.value++
    dragOverStatusId.value = id
}

function onDragLeave() {
    dragCounter.value--
    if (dragCounter.value === 0) {
        dragOverStatusId.value = null
    }
}

function onDrop(event: DragEvent) {
    dragCounter.value = 0
    dragOverStatusId.value = null
    return Number(event.dataTransfer!.getData('text/plain'))
}


async function onDropStatus(event: DragEvent, status: TaskStatus) {
    const taskId = onDrop(event)
    const task = tasks.value.find(t => t.id === taskId)
    if (!task || task.status?.id === status.id) return
    task.status = status
    await taskService.update(taskId, { status: `/api/task_statuses/${status.id}` })
}

async function onDropBacklog(event: DragEvent) {
    const taskId = onDrop(event)
    const task = tasks.value.find(t => t.id === taskId)
    if (!task || !task.status) return
    task.status = null
    await taskService.update(taskId, { status: null })
}

function toggleTaskSelect(taskId: number) {
    if (selectedTaskIds.has(taskId)) {
        selectedTaskIds.delete(taskId)
    } else {
        selectedTaskIds.add(taskId)
    }
}

function toggleSelectAll(taskList: Task[]) {
    if (selectedTaskIds.size === taskList.length) {
        selectedTaskIds.clear()
    } else {
        taskList.forEach(t => selectedTaskIds.add(t.id))
    }
}

async function onBulkUpdate(field: string, value: number) {
    const ids = [...selectedTaskIds]
    if (ids.length === 0) return
    const payload: Record<string, unknown> = {}
    if (field === 'status') payload.status = `/api/task_statuses/${value}`
    else if (field === 'assignee') payload.assignee = `/api/users/${value}`
    else if (field === 'priority') payload.priority = `/api/task_priorities/${value}`
    else if (field === 'effort') payload.effort = `/api/task_efforts/${value}`
    else if (field === 'group') payload.group = `/api/task_groups/${value}`
    await Promise.all(ids.map(id => taskService.update(id, payload)))
    selectedTaskIds.clear()
    await loadData()
}

async function onBulkArchive() {
    const ids = [...selectedTaskIds]
    if (ids.length === 0) return
    await Promise.all(ids.map(id => taskService.update(id, { archived: true })))
    selectedTaskIds.clear()
    await loadData()
}

async function onBulkDelete() {
    const ids = [...selectedTaskIds]
    if (ids.length === 0) return
    await Promise.all(ids.map(id => taskService.remove(id)))
    selectedTaskIds.clear()
    await loadData()
}

async function onSaved(savedTask?: Task) {
    // Mise à jour optimiste : la modale se ferme avant la fin du re-fetch, on
    // réinjecte immédiatement la tâche fraîche renvoyée par l'API pour éviter
    // que la liste (et un éventuel ré-ouverture de la modale) reste sur l'ancien snapshot.
    if (savedTask) {
        const idx = tasks.value.findIndex(t => t.id === savedTask.id)
        if (idx !== -1) tasks.value[idx] = savedTask
        else tasks.value.push(savedTask)
        if (selectedTask.value?.id === savedTask.id) selectedTask.value = savedTask
    }
    await loadData()
}

async function onProjectSaved() {
    await loadData()
}

onMounted(async () => {
    await loadData()
    const taskParam = route.query.task as string | undefined
    if (taskParam && project.value) {
        const prefix = `${project.value.code}-`
        if (taskParam.startsWith(prefix)) {
            const num = Number(taskParam.slice(prefix.length))
            if (num) {
                const task = tasks.value.find(t => t.number === num)
                if (task) {
                    openTaskEdit(task)
                }
            }
        }
    }
})
</script>
