<template>
    <AppDrawer v-model="isOpen" :title="isEditing ? 'Modifier un temps' : 'Ajouter une Activité'">
        <form class="space-y-4" @submit.prevent="onSubmit">
            <div>
                <label class="mb-1 block text-sm font-semibold text-neutral-700">Titre</label>
                <input
                    v-model="form.title"
                    type="text"
                    class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none"
                    placeholder="Que fais-tu ?"
                />
            </div>

            <div>
                <label class="mb-1 block text-sm font-semibold text-neutral-700">Description</label>
                <textarea
                    v-model="form.description"
                    rows="3"
                    class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none"
                />
            </div>

            <div class="grid grid-cols-2 gap-3">
                <div>
                    <label class="mb-1 block text-sm font-semibold text-neutral-700">Heure début</label>
                    <input
                        v-model="form.startedAt"
                        type="datetime-local"
                        class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none"
                    />
                </div>
                <div>
                    <label class="mb-1 block text-sm font-semibold text-neutral-700">Heure fin</label>
                    <input
                        v-model="form.stoppedAt"
                        type="datetime-local"
                        class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none"
                    />
                </div>
            </div>

            <div>
                <label class="mb-1 block text-sm font-semibold text-neutral-700">Utilisateur</label>
                <select
                    v-model="form.userId"
                    class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none"
                >
                    <option v-for="u in users" :key="u.id" :value="u.id">{{ u.username }}</option>
                </select>
            </div>

            <div>
                <label class="mb-1 block text-sm font-semibold text-neutral-700">Projet</label>
                <select
                    v-model="form.projectId"
                    class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none"
                >
                    <option :value="null">— Aucun —</option>
                    <option v-for="p in projects" :key="p.id" :value="p.id">{{ p.name }}</option>
                </select>
            </div>

            <div>
                <label class="mb-1 block text-sm font-semibold text-neutral-700">Type</label>
                <select
                    v-model="form.typeId"
                    class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none"
                >
                    <option :value="null">— Aucun —</option>
                    <option v-for="t in types" :key="t.id" :value="t.id">{{ t.label }}</option>
                </select>
            </div>

            <button
                type="submit"
                class="w-full rounded-md bg-primary-500 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-600 transition"
            >
                Enregistrer
            </button>
        </form>
    </AppDrawer>
</template>

<script setup lang="ts">
import type { TimeEntry } from '~/services/dto/time-entry'
import type { UserData } from '~/services/dto/user-data'
import type { Project } from '~/services/dto/project'
import type { TaskType } from '~/services/dto/task-type'
import { useTimeEntryService } from '~/services/time-entries'

const props = defineProps<{
    modelValue: boolean
    entry?: TimeEntry | null
    prefillStartedAt?: string | null
    users: UserData[]
    projects: Project[]
    types: TaskType[]
}>()

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.entry)

const authStore = useAuthStore()

const form = reactive({
    title: '',
    description: '',
    startedAt: '',
    stoppedAt: '',
    userId: authStore.user?.id ?? null as number | null,
    projectId: null as number | null,
    typeId: null as number | null,
})

watch(() => props.entry, (entry) => {
    if (entry) {
        form.title = entry.title ?? ''
        form.description = entry.description ?? ''
        form.startedAt = toLocalDatetimeInput(entry.startedAt)
        form.stoppedAt = entry.stoppedAt ? toLocalDatetimeInput(entry.stoppedAt) : ''
        form.userId = entry.user?.id ?? authStore.user?.id ?? null
        form.projectId = entry.project?.id ?? null
        form.typeId = entry.types?.[0]?.id ?? null
    } else {
        form.title = ''
        form.description = ''
        form.startedAt = props.prefillStartedAt ? toLocalDatetimeInput(props.prefillStartedAt) : ''
        form.stoppedAt = ''
        form.userId = authStore.user?.id ?? null
        form.projectId = null
        form.typeId = null
    }
}, { immediate: true })

function toLocalDatetimeInput(iso: string): string {
    const d = new Date(iso)
    const offset = d.getTimezoneOffset()
    const local = new Date(d.getTime() - offset * 60000)
    return local.toISOString().slice(0, 16)
}

function toISOFromLocal(localStr: string): string {
    return new Date(localStr).toISOString()
}

async function onSubmit() {
    const { create, update } = useTimeEntryService()

    const payload: Record<string, unknown> = {
        title: form.title || null,
        description: form.description || null,
        startedAt: toISOFromLocal(form.startedAt),
        stoppedAt: form.stoppedAt ? toISOFromLocal(form.stoppedAt) : null,
        user: `/api/users/${form.userId}`,
        project: form.projectId ? `/api/projects/${form.projectId}` : null,
        types: form.typeId ? [`/api/task_types/${form.typeId}`] : [],
    }

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

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