<template>
    <AppDrawer v-model="isOpen" :title="isEditing ? $t('taskGroups.editGroup') : $t('taskGroups.addGroup')">
        <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"
            />
            <div class="mt-4">
                <ColorPicker v-model="form.color" />
            </div>

            <div
                v-if="isEditing && !canArchive && !canUnarchive && nonFinalTasksCount > 0"
                class="mt-4 rounded-md bg-amber-50 px-4 py-3 text-sm text-amber-700"
            >
                {{ $t('archive.groupNonFinalTasks', { count: nonFinalTasksCount }) }}
            </div>

            <div class="mt-6 flex items-center" :class="isEditing ? 'justify-between' : 'justify-end'">
                <button
                    v-if="canArchive"
                    type="button"
                    class="rounded-md bg-neutral-500 px-4 py-2 text-sm font-semibold text-white hover:bg-neutral-600 disabled:cursor-not-allowed disabled:opacity-50"
                    :disabled="isSubmitting"
                    @click="handleArchive"
                >
                    {{ $t('archive.archiveButton') }}
                </button>
                <button
                    v-if="canUnarchive"
                    type="button"
                    class="rounded-md bg-neutral-500 px-4 py-2 text-sm font-semibold text-white hover:bg-neutral-600 disabled:cursor-not-allowed disabled:opacity-50"
                    :disabled="isSubmitting"
                    @click="handleUnarchive"
                >
                    {{ $t('archive.unarchiveButton') }}
                </button>
                <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 { TaskGroup, TaskGroupWrite } from '~/services/dto/task-group'
import type { Task } from '~/services/dto/task'
import { useTaskGroupService } from '~/services/task-groups'
import { useTaskService } from '~/services/tasks'

const props = defineProps<{
    modelValue: boolean
    group: TaskGroup | null
    projectId: number
    tasks?: Task[]
}>()

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.group)
const isSubmitting = ref(false)

const form = reactive({
    title: '',
    description: '',
    color: '#222783',
})

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

watch(() => props.modelValue, (open) => {
    if (open) {
        if (props.group) {
            form.title = props.group.title ?? ''
            form.description = props.group.description ?? ''
            form.color = props.group.color ?? '#222783'
        } else {
            form.title = ''
            form.description = ''
            form.color = '#222783'
        }
        touched.title = false
    }
})

const { create, update } = useTaskGroupService()
const taskService = useTaskService()

const groupTasks = computed(() =>
    (props.tasks ?? []).filter(t => t.group?.id === props.group?.id)
)

const nonFinalTasksCount = computed(() =>
    groupTasks.value.filter(t => t.status?.isFinal !== true).length
)

const canArchive = computed(() => {
    if (!isEditing.value || !props.group || props.group.archived) return false
    if (groupTasks.value.length === 0) return false
    return nonFinalTasksCount.value === 0
})

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

async function handleArchive() {
    if (!props.group) return
    isSubmitting.value = true
    try {
        await Promise.all(groupTasks.value.map(t => taskService.update(t.id, { archived: true })))
        await update(props.group.id, { archived: true })
        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}

async function handleUnarchive() {
    if (!props.group) return
    isSubmitting.value = true
    try {
        await Promise.all(groupTasks.value.map(t => taskService.update(t.id, { archived: false })))
        await update(props.group.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: TaskGroupWrite = {
            title: form.title.trim(),
            description: form.description.trim() || null,
            color: form.color,
            project: `/api/projects/${props.projectId}`,
        }

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

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