<template>
    <div class="min-w-0">
        <div class="sticky top-8 z-20 bg-white pb-4 sm:top-12">
            <div class="flex items-center justify-between gap-3">
                <h1 class="text-xl font-bold text-primary-500 sm:text-2xl">{{ project?.name ?? '' }}</h1>
                <div class="flex items-center gap-2">
                    <button
                        class="shrink-0 rounded-md bg-primary-500 px-3 py-2 text-xs font-semibold text-white hover:bg-secondary-500 sm:px-4 sm:text-sm"
                        @click="openTaskCreate"
                    >
                        <span class="hidden sm:inline">+ Ajouter un ticket</span>
                        <span class="sm:hidden">+ Ticket</span>
                    </button>
                    <button
                        class="flex shrink-0 items-center rounded-md bg-neutral-200 px-3 py-2 text-neutral-600 hover:bg-neutral-300 sm:px-4"
                        title="Paramètres du projet"
                        @click="projectDrawerOpen = true"
                    >
                        <Icon name="heroicons:cog-6-tooth" class="size-4 sm:size-5" />
                    </button>
                </div>
            </div>

            <div class="mt-4 flex flex-wrap gap-3">
                <MalioSelect
                    v-model="selectedGroupId"
                    :options="groupFilterOptions"
                    label="Groupe"
                    empty-option-label="Tous les groupes"
                    min-width="!w-40"
                    text-field="text-sm"
                    text-value="text-sm"
                />
                <MalioSelect
                    v-model="selectedTagId"
                    :options="tagFilterOptions"
                    label="Tags"
                    empty-option-label="Tous les tags"
                    min-width="!w-40"
                    text-field="text-sm"
                    text-value="text-sm"
                />
                <MalioSelect
                    v-model="selectedAssigneeId"
                    :options="userFilterOptions"
                    label="User"
                    empty-option-label="Tous les users"
                    min-width="!w-40"
                    text-field="text-sm"
                    text-value="text-sm"
                />
                <MalioSelect
                    v-model="selectedStatusId"
                    :options="statusFilterOptions"
                    label="Status"
                    empty-option-label="Tous les status"
                    min-width="!w-40"
                    text-field="text-sm"
                    text-value="text-sm"
                />
            </div>
        </div>

        <!-- Kanban -->
        <div class="mt-6 flex gap-3 overflow-x-auto pb-4">
            <div
                v-for="status in statuses"
                :key="status.id"
                class="flex min-w-36 flex-1 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="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="flex flex-col gap-3 p-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>

        <!-- Backlog -->
        <div
            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>

        <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 '~/services/dto/project'
import type { Task } from '~/services/dto/task'
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 type { Client } from '~/services/dto/client'
import { useProjectService } from '~/services/projects'
import { useClientService } from '~/services/clients'
import { useTaskService } from '~/services/tasks'
import { useTaskStatusService } from '~/services/task-statuses'
import { useTaskEffortService } from '~/services/task-efforts'
import { useTaskPriorityService } from '~/services/task-priorities'
import { useTaskTagService } from '~/services/task-tags'
import { useTaskGroupService } from '~/services/task-groups'
import { useUserService } from '~/services/users'

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

useHead({ title: 'Projet' })

const projectService = useProjectService()
const clientService = useClientService()
const taskService = useTaskService()
const statusService = useTaskStatusService()
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 statuses = ref<TaskStatus[]>([])
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 selectedGroupId = ref<number | null>(null)
const selectedTagId = ref<number | null>(null)
const selectedAssigneeId = ref<number | null>(null)
const selectedStatusId = ref<number | null>(null)
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 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)
    }
    if (selectedStatusId.value) {
        result = result.filter(t => t.status?.id === selectedStatusId.value)
    }
    return result
})

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, s, e, pr, ty, g, u, c] = await Promise.all([
            projectService.getById(projectId.value),
            taskService.getByProject(projectId.value),
            statusService.getAll(),
            effortService.getAll(),
            priorityService.getAll(),
            tagService.getAll(),
            groupService.getByProject(projectId.value),
            userService.getAll(),
            clientService.getAll(),
        ])
        project.value = p
        tasks.value = t
        statuses.value = s
        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
}

function openTaskEdit(task: Task) {
    selectedTask.value = task
    taskDrawerOpen.value = true
}

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 })
}

async function onSaved() {
    await loadData()
}

async function onProjectSaved() {
    await loadData()
}

onMounted(() => {
    loadData()
})
</script>
