<template>
    <MalioDrawer v-model="isOpen">
        <template #header>
            <h2 class="text-xl font-bold">{{ isEditing ? $t('timeEntries.editEntry') : $t('timeEntries.addEntry') }}</h2>
        </template>
        <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>

            <MalioInputRichText
                v-model="form.description"
                label="Description"
                min-height="120px"
            />

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

            <MalioSelect
                v-model="form.userId"
                :options="userOptions"
                label="Utilisateur"
                group-class="w-full"
            />

            <MalioSelect
                v-model="form.projectId"
                :options="projectOptions"
                label="Projet"
                empty-option-label="— Aucun —"
                group-class="w-full"
            />

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

            <div class="flex items-center" :class="isEditing ? 'justify-between' : 'justify-end'">
                <MalioButton
                    v-if="isEditing"
                    variant="danger"
                    label="Supprimer"
                    button-class="w-auto px-4"
                    @click="onDelete"
                />
                <div class="flex gap-2">
                    <MalioButton
                        v-if="isEditing"
                        variant="secondary"
                        label="Dupliquer"
                        button-class="w-auto px-4"
                        @click="onDuplicate"
                    />
                    <MalioButton
                        label="Enregistrer"
                        button-class="w-auto px-4"
                        @click="onSubmit"
                    />
                </div>
            </div>
        </form>
    </MalioDrawer>
</template>

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

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

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

const userOptions = computed(() =>
    props.users.map(u => ({ label: u.username, value: u.id }))
)

const projectOptions = computed(() =>
    props.projects.map(p => ({ label: p.name, value: p.id }))
)

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 toggleTag(id: number) {
    const idx = form.tagIds.indexOf(id)
    if (idx >= 0) {
        form.tagIds.splice(idx, 1)
    } else {
        form.tagIds.push(id)
    }
}

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.tagIds = entry.tags?.map(t => t.id) ?? []
    } 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.tagIds = []
    }
}

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

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

    const { create } = 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,
        tags: form.tagIds.map(id => `/api/task_tags/${id}`),
    }

    await create(payload as TimeEntryWrite)
    emit('saved')
    isOpen.value = false
}

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,
        tags: form.tagIds.map(id => `/api/task_tags/${id}`),
    }

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

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