<template>
    <MalioDrawer v-model="isOpen" :title="isEditing ? $t('projects.editProject') : $t('projects.addProject')">
        <form @submit.prevent="handleSubmit" class="flex flex-col gap-2">
            <MalioInputText
                v-model="codeProxy"
                label="Code"
                input-class="w-full"
                :max-length="10"
                :disabled="isEditing"
                :error="touched.code && !form.code ? 'Le code est requis' : touched.code && !/^[A-Z]{2,10}$/.test(form.code) ? '2 à 10 lettres majuscules' : ''"
                @blur="touched.code = true"
            />
            <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">
                <MalioButton
                    label="Enregistrer"
                    button-class="w-auto px-6"
                    :disabled="isSubmitting"
                    @click="handleSubmit"
                />
            </div>
        </form>

        <div v-if="isEditing && project" class="mt-6 border-t border-neutral-200 pt-4 flex items-center justify-between">
            <MalioButton
                variant="tertiary"
                :icon-name="project.archived ? 'mdi:archive-arrow-up-outline' : 'mdi:archive-arrow-down-outline'"
                icon-position="left"
                button-class="w-auto px-4"
                :disabled="isSubmitting"
                @click="handleArchiveToggle"
            >
                {{ project.archived ? 'Désarchiver' : 'Archiver' }}
            </MalioButton>
            <MalioButton
                v-if="project.taskCount === 0"
                variant="danger"
                icon-name="mdi:delete-outline"
                icon-position="left"
                button-class="w-auto px-4"
                :disabled="isSubmitting"
                @click="confirmDeleteOpen = true"
            >
                {{ $t('common.delete') }}
            </MalioButton>
        </div>

        <div v-if="props.project" class="mt-4 rounded border border-neutral-200 p-3">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs uppercase text-neutral-500">{{ $t('workflows.title') }}</p>
                    <p class="text-sm font-semibold text-neutral-900">{{ props.project.workflow?.name }}</p>
                </div>
                <MalioButton
                    v-if="canManageWorkflows"
                    type="button"
                    icon-name="mdi:swap-horizontal"
                    icon-position="left"
                    button-class="w-auto px-3 py-1 text-xs"
                    :label="$t('workflows.switchTitle')"
                    @click="switchModalOpen = true"
                />
            </div>
        </div>

        <ConfirmDeleteProjectModal
            v-model="confirmDeleteOpen"
            @confirm="handleDelete"
        />

        <ProjectWorkflowSwitchModal
            v-if="props.project"
            v-model="switchModalOpen"
            :project="props.project"
            @switched="onWorkflowSwitched"
        />
    </MalioDrawer>
</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 confirmDeleteOpen = ref(false)
const switchModalOpen = ref(false)

const auth = useAuthStore()
const canManageWorkflows = computed(() => auth.user?.roles?.includes('ROLE_ADMIN') ?? false)

function onWorkflowSwitched() {
    emit('saved')
    isOpen.value = 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,
})

// Source unique de vérité : on sanitise dans le setter (majuscules, lettres
// uniquement, max 10) plutôt que via @input — sinon course entre la mutation
// manuelle et l'émission update:modelValue de MalioInputText, qui laissait
// form.code en minuscules et bloquait la création.
const codeProxy = computed({
    get: () => form.code,
    set: (value: string) => {
        form.code = (value ?? '').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 10)
    },
})

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, remove } = useProjectService()

async function handleSubmit() {
    touched.name = true
    touched.code = true
    if (!form.name.trim()) return
    if (!isEditing.value && !/^[A-Z]{2,10}$/.test(form.code)) 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
            await create(payload)
        }

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

async function handleDelete() {
    if (!props.project) return
    isSubmitting.value = true
    try {
        await remove(props.project.id)
        emit('saved')
        isOpen.value = false
    } finally {
        confirmDeleteOpen.value = false
        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>
