<script setup lang="ts">
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const slug = route.params.slug as string

const application = ref<Application | null>(null)
const loading = ref(true)
const editingApp = ref(false)
const editForm = ref<ApplicationWrite>({ name: '', slug: '', registryImage: '', description: '', giteaUrl: '' })
const isSubmitting = ref(false)

// Environment form
const showEnvForm = ref(false)
const editingEnvId = ref<number | null>(null)
const envForm = ref<EnvironmentWrite>({
    name: '',
    containerName: '',
    deployScriptPath: '',
    maintenanceFilePath: '',
    appUrl: '',
    logFiles: [],
})
const isSubmittingEnv = ref(false)
const pendingMaintenanceByEnvId = ref<Record<number, boolean>>({})

async function loadApplication() {
    loading.value = true
    try {
        application.value = await getApplication(slug)
    } finally {
        loading.value = false
    }
}

// Application edit
function startEditApp() {
    if (!application.value) return
    editForm.value = {
        name: application.value.name,
        slug: application.value.slug,
        registryImage: application.value.registryImage,
        description: application.value.description ?? '',
        giteaUrl: application.value.giteaUrl ?? '',
    }
    editingApp.value = true
}

async function saveApp() {
    isSubmitting.value = true
    try {
        application.value = await updateApplication(slug, editForm.value)
        editingApp.value = false
        if (editForm.value.slug !== slug) {
            router.replace(`/applications/${editForm.value.slug}`)
        }
    } finally {
        isSubmitting.value = false
    }
}

async function handleDeleteApp() {
    if (!confirm(t('applications.detail.deleteConfirm'))) return
    await deleteApplication(slug)
    router.push('/applications')
}

// Environment CRUD
function startCreateEnv() {
    editingEnvId.value = null
    envForm.value = { name: '', containerName: '', deployScriptPath: '', maintenanceFilePath: '', appUrl: '', logFiles: [] }
    showEnvForm.value = true
}

function startEditEnv(env: Environment) {
    editingEnvId.value = env.id!
    envForm.value = {
        name: env.name,
        containerName: env.containerName,
        deployScriptPath: env.deployScriptPath,
        maintenanceFilePath: env.maintenanceFilePath,
        appUrl: env.appUrl ?? '',
        logFiles: env.logFiles.map(lf => ({ label: lf.label, path: lf.path })),
    }
    showEnvForm.value = true
}

async function saveEnv() {
    isSubmittingEnv.value = true
    try {
        if (editingEnvId.value) {
            await updateEnvironment(editingEnvId.value, envForm.value)
        } else {
            await createEnvironment(slug, envForm.value)
        }
        showEnvForm.value = false
        await loadApplication()
    } finally {
        isSubmittingEnv.value = false
    }
}

async function handleDeleteEnv(envId: number) {
    if (!confirm(t('environments.deleteConfirm'))) return
    await deleteEnvironment(envId)
    await loadApplication()
}

async function handleToggleMaintenance(env: Environment) {
    const envId = env.id!
    pendingMaintenanceByEnvId.value[envId] = true
    try {
        await toggleMaintenance(envId, !env.maintenance)
        await loadApplication()
    } finally {
        delete pendingMaintenanceByEnvId.value[envId]
    }
}

function addLogFile() {
    envForm.value.logFiles.push({ label: '', path: '' })
}

function removeLogFile(index: number) {
    envForm.value.logFiles.splice(index, 1)
}

onMounted(loadApplication)
</script>

<template>
    <div class="p-6 max-w-5xl mx-auto">
        <!-- Back link -->
        <NuxtLink to="/applications" class="text-m-muted hover:text-primary-500 text-sm mb-4 inline-flex items-center gap-1">
            <Icon name="mdi:arrow-left" size="16" />
            {{ t('applications.title') }}
        </NuxtLink>

        <!-- Loading -->
        <div v-if="loading" class="animate-pulse mt-4">
            <div class="h-8 bg-m-disabled rounded w-1/3 mb-4" />
            <div class="h-4 bg-m-disabled rounded w-2/3 mb-2" />
            <div class="h-4 bg-m-disabled rounded w-1/2" />
        </div>

        <template v-else-if="application">
            <!-- Application info -->
            <div class="bg-m-surface border border-m-border rounded-lg p-6 mt-4">
                <template v-if="!editingApp">
                    <div class="flex items-start justify-between">
                        <div>
                            <h1 class="text-2xl font-bold text-m-text">{{ application.name }}</h1>
                            <p v-if="application.description" class="text-m-muted mt-2">{{ application.description }}</p>
                        </div>
                        <div class="flex gap-2">
                            <MalioButton variant="secondary" size="sm" @click="startEditApp">
                                {{ t('applications.detail.editButton') }}
                            </MalioButton>
                            <MalioButton variant="danger" size="sm" @click="handleDeleteApp">
                                {{ t('applications.detail.deleteButton') }}
                            </MalioButton>
                        </div>
                    </div>
                    <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                        <div>
                            <span class="text-m-muted">{{ t('applications.detail.registryImage') }} :</span>
                            <span class="text-m-text ml-1 font-mono">{{ application.registryImage }}</span>
                        </div>
                        <div v-if="application.giteaUrl">
                            <span class="text-m-muted">{{ t('applications.detail.giteaUrl') }} :</span>
                            <a :href="application.giteaUrl" target="_blank" class="text-primary-500 hover:underline ml-1">
                                {{ application.giteaUrl }}
                            </a>
                        </div>
                    </div>
                </template>

                <!-- Edit form -->
                <form v-else @submit.prevent="saveApp" class="space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-m-text mb-1">{{ t('applications.form.name') }}</label>
                            <MalioInputText v-model="editForm.name" required />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-m-text mb-1">{{ t('applications.form.slug') }}</label>
                            <MalioInputText v-model="editForm.slug" required />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-m-text mb-1">{{ t('applications.form.registryImage') }}</label>
                            <MalioInputText v-model="editForm.registryImage" required />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-m-text mb-1">{{ t('applications.form.giteaUrl') }}</label>
                            <MalioInputText v-model="editForm.giteaUrl" />
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-m-text mb-1">{{ t('applications.form.description') }}</label>
                        <textarea
                            v-model="editForm.description"
                            class="w-full rounded border border-m-border bg-m-bg text-m-text p-2"
                            rows="2"
                        />
                    </div>
                    <div class="flex justify-end gap-2">
                        <MalioButton variant="secondary" @click="editingApp = false">
                            {{ t('applications.form.cancel') }}
                        </MalioButton>
                        <MalioButton type="submit" :loading="isSubmitting">
                            {{ t('applications.form.save') }}
                        </MalioButton>
                    </div>
                </form>
            </div>

            <!-- Environments section -->
            <div class="mt-8">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-xl font-bold text-m-text">{{ t('environments.title') }}</h2>
                    <MalioButton size="sm" @click="startCreateEnv">
                        {{ t('environments.addButton') }}
                    </MalioButton>
                </div>

                <!-- Environment form -->
                <div v-if="showEnvForm" class="bg-m-surface border border-m-border rounded-lg p-6 mb-4">
                    <form @submit.prevent="saveEnv" class="space-y-4">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-m-text mb-1">{{ t('environments.form.name') }}</label>
                                <MalioInputText v-model="envForm.name" required />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-m-text mb-1">{{ t('environments.form.containerName') }}</label>
                                <MalioInputText v-model="envForm.containerName" required />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-m-text mb-1">{{ t('environments.form.deployScriptPath') }}</label>
                                <MalioInputText v-model="envForm.deployScriptPath" required />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-m-text mb-1">{{ t('environments.form.maintenanceFilePath') }}</label>
                                <MalioInputText v-model="envForm.maintenanceFilePath" required />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-m-text mb-1">{{ t('environments.form.appUrl') }}</label>
                                <MalioInputText v-model="envForm.appUrl" />
                            </div>
                        </div>

                        <!-- Log files -->
                        <div>
                            <div class="flex items-center justify-between mb-2">
                                <label class="text-sm font-medium text-m-text">{{ t('environments.logFiles.title') }}</label>
                                <button type="button" @click="addLogFile" class="text-primary-500 hover:underline text-sm">
                                    + {{ t('environments.logFiles.addButton') }}
                                </button>
                            </div>
                            <div v-for="(lf, index) in envForm.logFiles" :key="index" class="flex gap-2 mb-2 items-center">
                                <MalioInputText v-model="lf.label" :placeholder="t('environments.logFiles.label')" class="flex-1" required />
                                <MalioInputText v-model="lf.path" :placeholder="t('environments.logFiles.path')" class="flex-[2]" required />
                                <button type="button" @click="removeLogFile(index)" class="text-m-danger hover:text-red-700 p-1">
                                    <Icon name="mdi:close" size="18" />
                                </button>
                            </div>
                        </div>

                        <div class="flex justify-end gap-2">
                            <MalioButton variant="secondary" @click="showEnvForm = false">
                                {{ t('environments.form.cancel') }}
                            </MalioButton>
                            <MalioButton type="submit" :loading="isSubmittingEnv">
                                {{ t('environments.form.save') }}
                            </MalioButton>
                        </div>
                    </form>
                </div>

                <!-- Environments list -->
                <div v-if="!application.environments?.length && !showEnvForm" class="text-center py-8 text-m-muted">
                    {{ t('applications.card.noEnvironments') }}
                </div>

                <div v-for="env in application.environments" :key="env.id" class="bg-m-surface border border-m-border rounded-lg p-6 mb-4">
                    <div class="flex items-start justify-between">
                        <div>
                            <div class="flex items-center gap-3">
                                <h3 class="text-lg font-semibold text-m-text">{{ env.name }}</h3>
                                <span
                                    class="px-2 py-0.5 rounded-full text-xs font-medium"
                                    :class="env.maintenance
                                        ? 'bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300'
                                        : 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300'"
                                >
                                    {{ env.maintenance ? t('environments.maintenance.active') : t('environments.maintenance.inactive') }}
                                </span>
                            </div>
                            <p class="text-m-muted text-sm mt-1 font-mono">{{ env.containerName }}</p>
                            <a
                                v-if="env.appUrl"
                                :href="env.appUrl"
                                target="_blank"
                                class="text-primary-500 hover:underline text-sm mt-1 inline-flex items-center gap-1"
                            >
                                {{ env.appUrl }}
                                <Icon name="mdi:open-in-new" size="14" />
                            </a>
                        </div>
                        <div class="flex gap-2">
                            <MalioButton
                                size="sm"
                                :variant="env.maintenance ? 'secondary' : 'danger'"
                                :loading="!!pendingMaintenanceByEnvId[env.id!]"
                                @click="handleToggleMaintenance(env)"
                            >
                                {{ pendingMaintenanceByEnvId[env.id!]
                                    ? t('environments.maintenance.pending')
                                    : env.maintenance
                                        ? t('environments.maintenance.deactivate')
                                        : t('environments.maintenance.activate')
                                }}
                            </MalioButton>
                            <MalioButton variant="secondary" size="sm" @click="startEditEnv(env)">
                                {{ t('environments.editButton') }}
                            </MalioButton>
                            <MalioButton variant="danger" size="sm" @click="handleDeleteEnv(env.id!)">
                                {{ t('environments.deleteButton') }}
                            </MalioButton>
                        </div>
                    </div>

                    <!-- Log files -->
                    <div v-if="env.logFiles.length" class="mt-4 border-t border-m-border pt-3">
                        <p class="text-sm font-medium text-m-muted mb-2">{{ t('environments.logFiles.title') }}</p>
                        <div v-for="lf in env.logFiles" :key="lf.id" class="text-sm text-m-text flex gap-2">
                            <span class="font-medium">{{ lf.label }} :</span>
                            <span class="font-mono text-m-muted">{{ lf.path }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </div>
</template>
