<template>
    <AppDrawer v-model="isOpen" :title="isEditing ? 'Modifier un ticket' : 'Ajouter un ticket'">
        <form @submit.prevent="handleSubmit" class="flex flex-col gap-2">
            <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"
            />
            <MalioInputTextArea
                v-model="form.description"
                label="Description"
                :size="3"
            />
            <MalioSelect
                v-model="form.statusId"
                :options="statusOptions"
                label="Statut"
                empty-option-label="Aucun statut"
                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.assigneeId"
                :options="userOptions"
                label="User"
                empty-option-label="Aucun utilisateur"
                min-width="w-full"
            />
            <MalioSelect
                v-model="form.groupId"
                :options="groupOptions"
                label="Groupe"
                empty-option-label="Aucun groupe"
                min-width="w-full"
            />

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

            <div class="mt-6 flex justify-end">
                <button
                    type="submit"
                    class="rounded-md bg-primary-500 px-6 py-2 text-sm font-semibold text-white hover:bg-secondary-500 disabled:cursor-not-allowed disabled:opacity-50"
                    :disabled="isSubmitting"
                >
                    Enregistrer
                </button>
            </div>
        </form>
    </AppDrawer>
</template>

<script setup lang="ts">
import type { Task, TaskWrite } 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 { TaskType } from '~/services/dto/task-type'
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[]
    types: TaskType[]
    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),
})

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

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,
    typeIds: [] as number[],
})

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

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

watch(() => props.modelValue, (open) => {
    if (open) {
        if (props.task) {
            form.title = props.task.title ?? ''
            form.description = props.task.description ?? ''
            form.statusId = props.task.status?.id ?? null
            form.effortId = props.task.effort?.id ?? null
            form.priorityId = props.task.priority?.id ?? null
            form.assigneeId = props.task.assignee?.id ?? null
            form.groupId = props.task.group?.id ?? null
            form.typeIds = props.task.types.map(t => t.id)
        } else {
            form.title = ''
            form.description = ''
            form.statusId = null
            form.effortId = null
            form.priorityId = null
            form.assigneeId = null
            form.groupId = null
            form.typeIds = []
        }
        touched.title = false
    }
})

const { create, update } = useTaskService()

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}`,
            types: form.typeIds.map(id => `/api/task_types/${id}`),
        }

        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>
