<template>
    <AppDrawer v-model="isOpen" :title="isEditing ? 'Modifier un projet' : 'Ajouter un projet'">
        <form @submit.prevent="handleSubmit" class="flex flex-col gap-2">
            <MalioInputText
                v-model="form.code"
                label="Code"
                input-class="w-full uppercase"
                :disabled="isEditing"
                :error="touched.code && !form.code.trim() ? 'Le code est requis' : touched.code && !/^[A-Z]{2,10}$/.test(form.code.trim()) ? '2 à 10 lettres majuscules' : ''"
                @blur="touched.code = true"
                @input="form.code = form.code.toUpperCase().replace(/[^A-Z]/g, '')"
            />
            <MalioInputText
                v-model="form.name"
                label="Titre"
                input-class="w-full"
                :error="touched.name && !form.name.trim() ? 'Le titre est requis' : ''"
                @blur="touched.name = true"
            />
            <MalioInputTextArea
                v-model="form.description"
                label="Description"
                :size="3"
            />
            <MalioSelect
                v-model="form.clientId"
                :options="clientOptions"
                label="Client"
                empty-option-label="Aucun client"
                min-width="w-full"
            />
            <div class="mt-4">
                <ColorPicker v-model="form.color" />
            </div>

            <div v-if="giteaRepos.length" class="mt-4">
                <MalioSelect
                    v-model="form.giteaRepoFullName"
                    :options="giteaRepoOptions"
                    label="Dépôt Gitea"
                    empty-option-label="Aucun dépôt"
                    min-width="w-full"
                />
            </div>

            <div v-if="bookstackShelves.length" class="mt-4">
                <MalioSelect
                    v-model="form.bookstackShelfId"
                    :options="bookstackShelfOptions"
                    label="Étagère BookStack"
                    empty-option-label="Aucune étagère"
                    min-width="w-full"
                />
            </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>

        <div v-if="isEditing && project" class="mt-6 border-t border-neutral-200 pt-4">
            <button
                class="flex items-center gap-2 text-sm text-neutral-500 hover:text-amber-600"
                :disabled="isSubmitting"
                @click="handleArchiveToggle"
            >
                <Icon :name="project.archived ? 'mdi:archive-arrow-up-outline' : 'mdi:archive-arrow-down-outline'" size="18" />
                {{ project.archived ? 'Désarchiver' : 'Archiver' }}
            </button>
        </div>
    </AppDrawer>
</template>

<script setup lang="ts">
import type { Project, ProjectWrite } from '~/services/dto/project'
import type { Client } from '~/services/dto/client'
import type { GiteaRepository } from '~/services/dto/gitea'
import type { BookStackShelf } from '~/services/dto/bookstack'
import { useProjectService } from '~/services/projects'
import { useGiteaService } from '~/services/gitea'
import { useBookStackService } from '~/services/bookstack'

const props = defineProps<{
    modelValue: boolean
    project: Project | null
    clients: Client[]
}>()

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

const { listRepositories } = useGiteaService()
const giteaRepos = ref<GiteaRepository[]>([])

const giteaRepoOptions = computed(() =>
    giteaRepos.value.map(r => ({ label: r.fullName, value: r.fullName }))
)

const { listShelves } = useBookStackService()
const bookstackShelves = ref<BookStackShelf[]>([])

const bookstackShelfOptions = computed(() =>
    bookstackShelves.value.map(s => ({ label: s.name, value: s.id }))
)

const form = reactive({
    code: '',
    name: '',
    description: '',
    color: '#222783',
    clientId: null as number | null,
    giteaRepoFullName: null as string | null,
    bookstackShelfId: null as number | null,
})

const touched = reactive({
    code: false,
    name: false,
})

const clientOptions = computed(() =>
    props.clients.map(c => ({ label: c.name, value: c.id }))
)

watch(() => props.modelValue, (open) => {
    if (open) {
        if (props.project) {
            form.code = props.project.code ?? ''
            form.name = props.project.name ?? ''
            form.description = props.project.description ?? ''
            form.color = props.project.color ?? '#222783'
            form.clientId = props.project.client?.id ?? null
            form.giteaRepoFullName = props.project?.giteaOwner && props.project?.giteaRepo
                ? `${props.project.giteaOwner}/${props.project.giteaRepo}`
                : null
            form.bookstackShelfId = props.project.bookstackShelfId ?? null
        } else {
            form.code = ''
            form.name = ''
            form.description = ''
            form.color = '#222783'
            form.clientId = null
            form.giteaRepoFullName = null
            form.bookstackShelfId = null
        }
        touched.code = false
        touched.name = false
    }
})

const { create, update } = useProjectService()

async function handleSubmit() {
    touched.name = true
    touched.code = true
    if (!form.name.trim()) return
    if (!isEditing.value && (!form.code.trim() || !/^[A-Z]{2,10}$/.test(form.code.trim()))) return

    isSubmitting.value = true
    try {
        const payload: ProjectWrite = {
            name: form.name.trim(),
            description: form.description.trim() || null,
            color: form.color,
            client: form.clientId ? `/api/clients/${form.clientId}` : null,
        }

        if (form.giteaRepoFullName) {
            const [owner, repo] = form.giteaRepoFullName.split('/')
            payload.giteaOwner = owner
            payload.giteaRepo = repo
        } else {
            payload.giteaOwner = null
            payload.giteaRepo = null
        }

        if (form.bookstackShelfId) {
            const shelf = bookstackShelves.value.find(s => s.id === form.bookstackShelfId)
            payload.bookstackShelfId = form.bookstackShelfId
            payload.bookstackShelfName = shelf?.name ?? null
        } else {
            payload.bookstackShelfId = null
            payload.bookstackShelfName = null
        }

        if (isEditing.value && props.project) {
            await update(props.project.id, payload)
        } else {
            payload.code = form.code.trim()
            await create(payload)
        }

        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}

async function handleArchiveToggle() {
    if (!props.project) return
    isSubmitting.value = true
    try {
        const newArchived = !props.project.archived
        await update(props.project.id, { archived: newArchived }, {
            toastSuccessKey: newArchived ? 'projects.archived' : 'projects.unarchived',
        })
        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}

onMounted(async () => {
    try {
        giteaRepos.value = await listRepositories()
    } catch {
        // Gitea not configured, ignore
    }
    try {
        bookstackShelves.value = await listShelves()
    } catch {
        // BookStack not configured, ignore
    }
})
</script>
