<script setup lang="ts">
import type { Application, ApplicationWrite } from '~/services/dto/application'
import { getApplications, createApplication } from '~/services/applications'

const { t } = useI18n()
const router = useRouter()

const applications = ref<Application[]>([])
const loading = ref(true)
const showCreateForm = ref(false)
const createForm = ref<ApplicationWrite>({
    name: '',
    slug: '',
    registryImage: '',
    description: '',
    giteaUrl: '',
})
const isSubmitting = ref(false)

async function loadApplications() {
    loading.value = true
    try {
        applications.value = await getApplications()
    } finally {
        loading.value = false
    }
}

async function handleCreate() {
    isSubmitting.value = true
    try {
        const created = await createApplication(createForm.value)
        showCreateForm.value = false
        createForm.value = { name: '', slug: '', registryImage: '', description: '', giteaUrl: '' }
        router.push(`/applications/${created.slug}`)
    } finally {
        isSubmitting.value = false
    }
}

function generateSlug(name: string) {
    createForm.value.slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')
}

onMounted(loadApplications)
</script>

<template>
    <div class="p-6 max-w-6xl mx-auto">
        <div class="flex items-center justify-between mb-6">
            <div>
                <h1 class="text-2xl font-bold text-m-text">{{ t('applications.title') }}</h1>
                <p class="text-m-muted mt-1">{{ t('applications.description') }}</p>
            </div>
            <MalioButton @click="showCreateForm = !showCreateForm">
                {{ t('applications.addButton') }}
            </MalioButton>
        </div>

        <!-- Create form -->
        <div v-if="showCreateForm" class="bg-m-surface border border-m-border rounded-lg p-6 mb-6">
            <form @submit.prevent="handleCreate" 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="createForm.name"
                            @update:model-value="generateSlug"
                            required
                        />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-m-text mb-1">{{ t('applications.form.slug') }}</label>
                        <MalioInputText v-model="createForm.slug" required />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-m-text mb-1">{{ t('applications.form.registryImage') }}</label>
                        <MalioInputText v-model="createForm.registryImage" required />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-m-text mb-1">{{ t('applications.form.giteaUrl') }}</label>
                        <MalioInputText v-model="createForm.giteaUrl" />
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-m-text mb-1">{{ t('applications.form.description') }}</label>
                    <textarea
                        v-model="createForm.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="showCreateForm = false">
                        {{ t('applications.form.cancel') }}
                    </MalioButton>
                    <MalioButton type="submit" :loading="isSubmitting">
                        {{ t('applications.form.save') }}
                    </MalioButton>
                </div>
            </form>
        </div>

        <!-- Loading -->
        <div v-if="loading" class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            <div v-for="i in 3" :key="i" class="bg-m-surface border border-m-border rounded-lg p-6 animate-pulse">
                <div class="h-5 bg-m-disabled rounded w-1/2 mb-3" />
                <div class="h-4 bg-m-disabled rounded w-3/4 mb-2" />
                <div class="h-4 bg-m-disabled rounded w-1/3" />
            </div>
        </div>

        <!-- Empty state -->
        <div v-else-if="applications.length === 0" class="text-center py-12">
            <h3 class="text-lg font-medium text-m-text">{{ t('applications.emptyTitle') }}</h3>
            <p class="text-m-muted mt-1">{{ t('applications.emptyDescription') }}</p>
        </div>

        <!-- Application cards -->
        <div v-else class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            <NuxtLink
                v-for="app in applications"
                :key="app.slug"
                :to="`/applications/${app.slug}`"
                class="bg-m-surface border border-m-border rounded-lg p-6 hover:border-primary-500 transition-colors"
            >
                <div class="flex items-start justify-between">
                    <h3 class="text-lg font-semibold text-m-text">{{ app.name }}</h3>
                    <a
                        v-if="app.giteaUrl"
                        :href="app.giteaUrl"
                        target="_blank"
                        class="text-m-muted hover:text-primary-500"
                        @click.stop
                    >
                        <Icon name="mdi:open-in-new" size="18" />
                    </a>
                </div>
                <p v-if="app.description" class="text-m-muted text-sm mt-2 line-clamp-2">{{ app.description }}</p>
                <p class="text-m-muted text-xs mt-3">
                    <Icon name="mdi:server" size="14" class="mr-1" />
                    {{ app.environments?.length ?? 0 }} {{ t('applications.card.environments', app.environments?.length ?? 0) }}
                </p>
            </NuxtLink>
        </div>
    </div>
</template>
