<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>
                <label class="mb-1 block text-sm font-semibold text-neutral-700">Date</label>
                <input
                    v-model="form.date"
                    type="date"
                    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">Début</label>
                    <input
                        v-model="form.startTime"
                        type="time"
                        step="60"
                        class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm tabular-nums focus:border-primary-500 focus:outline-none"
                    />
                </div>
                <div>
                    <label class="mb-1 block text-sm font-semibold text-neutral-700">Fin</label>
                    <input
                        v-model="form.endTime"
                        type="time"
                        step="60"
                        class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm tabular-nums focus:border-primary-500 focus:outline-none"
                    />
                </div>
            </div>

            <div
                v-if="durationLabel"
                class="rounded-md bg-neutral-100 px-3 py-2 text-center text-sm font-semibold text-neutral-600 tabular-nums"
            >
                {{ durationLabel }}
            </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>

            <div class="flex items-center" :class="isEditing ? 'justify-between' : 'justify-end'">
                <button
                    v-if="isEditing"
                    type="button"
                    class="rounded-md bg-red-500 px-4 py-2 text-sm font-semibold text-white hover:bg-red-600 transition"
                    @click="onDelete"
                >
                    Supprimer
                </button>
                <button
                    type="submit"
                    class="rounded-md bg-primary-500 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-600 transition"
                >
                    Enregistrer
                </button>
            </div>
        </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: '',
    date: '',
    startTime: '',
    endTime: '',
    userId: authStore.user?.id ?? null as number | null,
    projectId: null as number | null,
    typeId: null as number | null,
})

const durationLabel = computed(() => {
    if (!form.startTime || !form.endTime) return ''
    const [sh, sm] = form.startTime.split(':').map(Number) as [number, number]
    const [eh, em] = form.endTime.split(':').map(Number) as [number, number]
    const diff = (eh * 60 + em) - (sh * 60 + sm)
    if (diff <= 0) return ''
    const h = Math.floor(diff / 60)
    const m = diff % 60
    return m > 0 ? `${h}h${String(m).padStart(2, '0')}` : `${h}h`
})

function toLocalDate(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, 10)
}

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

function toISO(date: string, time: string): string {
    return new Date(`${date}T${time}`).toISOString()
}

function populateForm(entry: TimeEntry | null | undefined) {
    if (entry) {
        form.title = entry.title ?? ''
        form.description = entry.description ?? ''
        form.date = toLocalDate(entry.startedAt)
        form.startTime = toLocalTime(entry.startedAt)
        form.endTime = entry.stoppedAt ? toLocalTime(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.date = props.prefillStartedAt ? toLocalDate(props.prefillStartedAt) : new Date().toISOString().slice(0, 10)
        form.startTime = props.prefillStartedAt ? toLocalTime(props.prefillStartedAt) : ''
        form.endTime = ''
        form.userId = authStore.user?.id ?? null
        form.projectId = null
        form.typeId = null
    }
}

watch([() => props.modelValue, () => props.entry] as const, ([open, entry]) => {
    if (open) {
        populateForm(entry)
    }
})

async function onDelete() {
    if (!props.entry) return
    const { remove } = useTimeEntryService()
    await remove(props.entry.id)
    emit('saved')
    isOpen.value = false
}

async function onSubmit() {
    if (!form.date || !form.startTime || !form.endTime) return

    const { create, update } = useTimeEntryService()

    const payload: Record<string, unknown> = {
        title: form.title || null,
        description: form.description || null,
        startedAt: toISO(form.date, form.startTime),
        stoppedAt: form.endTime ? toISO(form.date, form.endTime) : 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>
