<script setup lang="ts">
import type { Application, ApplicationWrite, Environment, EnvironmentWrite } from '~/services/dto/application'
import { getApplication, updateApplication, deleteApplication } from '~/services/applications'
import { createEnvironment, updateEnvironment, deleteEnvironment, toggleMaintenance } from '~/services/environments'
import type { DeployResult } from '~/services/dto/deploy'
import { getAvailableTags, deploy } from '~/services/deploy'
import type { EnvironmentHealth } from '~/services/dto/dashboard'
import { getEnvironmentHealth } from '~/services/dashboard'
import type { LogOutput } from '~/services/dto/logs'
import { getDockerLogs, getSymfonyLog } from '~/services/logs'

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 pendingMaintenanceByEnvId = ref<Record<number, boolean>>({})

// Deploy modal
const showDeployModal = ref(false)
const deployEnvId = ref<number | null>(null)
const deployTags = ref<string[]>([])
const selectedTag = ref('')
const loadingTags = ref(false)
const isDeploying = ref(false)
const deployResult = ref<DeployResult | null>(null)

// Health data per env
const healthByEnvId = ref<Record<number, EnvironmentHealth>>({})
const loadingHealth = ref(false)

// Log modals
const showLogModal = ref(false)
const logContent = ref('')
const logLoading = ref(false)
const logTitle = ref('')
const logEnvId = ref<number | null>(null)
const logFileId = ref<number | null>(null)
const logIsSymfony = ref(false)

// App edit modal
const showAppModal = ref(false)
const editForm = ref<ApplicationWrite>({ name: '', slug: '', registryImage: '', description: '', giteaUrl: '' })
const isSubmittingApp = ref(false)

// Env modal
const showEnvModal = ref(false)
const editingEnvId = ref<number | null>(null)
const envForm = ref<EnvironmentWrite>({
    name: '',
    containerName: '',
    deployScriptPath: '',
    maintenanceFilePath: '',
    appUrl: '',
    logFiles: [],
})
const isSubmittingEnv = ref(false)

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

// Application edit
function openEditAppModal() {
    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 ?? '',
    }
    showAppModal.value = true
}

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

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

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

function openEditEnvModal(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 })),
    }
    showEnvModal.value = true
}

async function saveEnv() {
    isSubmittingEnv.value = true
    try {
        if (editingEnvId.value) {
            await updateEnvironment(editingEnvId.value, envForm.value)
        } else {
            await createEnvironment(slug, envForm.value)
        }
        showEnvModal.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)
}

async function openDeployModal(env: Environment) {
    deployEnvId.value = env.id!
    selectedTag.value = ''
    deployResult.value = null
    deployTags.value = []
    showDeployModal.value = true
    loadingTags.value = true
    try {
        const response = await getAvailableTags(slug)
        deployTags.value = response.tags ?? []
        if (deployTags.value.length > 0) {
            selectedTag.value = deployTags.value[0]
        }
    } finally {
        loadingTags.value = false
    }
}

async function handleDeploy() {
    if (!deployEnvId.value || !selectedTag.value) return
    isDeploying.value = true
    deployResult.value = null
    try {
        deployResult.value = await deploy(deployEnvId.value, selectedTag.value)
        if (deployResult.value.success) {
            await loadApplication()
        }
    } finally {
        isDeploying.value = false
    }
}

function closeDeployModal() {
    showDeployModal.value = false
    deployResult.value = null
}

async function loadHealthData() {
    if (!application.value?.environments?.length) return
    loadingHealth.value = true
    try {
        const promises = application.value.environments.map(async (env) => {
            try {
                const health = await getEnvironmentHealth(env.id!)
                healthByEnvId.value[env.id!] = health
            } catch {
                // silently ignore individual env health failures
            }
        })
        await Promise.all(promises)
    } finally {
        loadingHealth.value = false
    }
}

function formatUptime(startedAt: string): string {
    if (!startedAt) return '-'
    const start = new Date(startedAt)
    const now = new Date()
    const diffMs = now.getTime() - start.getTime()
    const days = Math.floor(diffMs / 86400000)
    const hours = Math.floor((diffMs % 86400000) / 3600000)
    const minutes = Math.floor((diffMs % 3600000) / 60000)
    if (days > 0) return `${days}j ${hours}h`
    if (hours > 0) return `${hours}h ${minutes}m`
    return `${minutes}m`
}

function statusClass(status: string): string {
    switch (status) {
        case 'running': return 'bg-green-100 text-green-700'
        case 'exited': return 'bg-red-100 text-red-700'
        case 'restarting': return 'bg-orange-100 text-orange-700'
        default: return 'bg-neutral-100 text-neutral-500'
    }
}

// Log functions
async function openDockerLogs(env: Environment) {
    logEnvId.value = env.id!
    logFileId.value = null
    logIsSymfony.value = false
    logTitle.value = `${t('logs.docker')} — ${env.name}`
    logContent.value = ''
    showLogModal.value = true
}

async function openSymfonyLog(env: Environment, lf: { id?: number, label: string }) {
    logEnvId.value = env.id!
    logFileId.value = lf.id!
    logIsSymfony.value = true
    logTitle.value = `${t('logs.symfony')} — ${lf.label}`
    logContent.value = ''
    showLogModal.value = true
}

async function refreshLogs(lines: number, level: string) {
    if (!logEnvId.value) return
    logLoading.value = true
    try {
        let result: LogOutput
        if (logIsSymfony.value && logFileId.value) {
            result = await getSymfonyLog(logEnvId.value, logFileId.value, lines, level || undefined)
        } else {
            result = await getDockerLogs(logEnvId.value, lines)
        }
        logContent.value = result.content
    } finally {
        logLoading.value = false
    }
}

const envModalTitle = computed(() =>
    editingEnvId.value ? t('environments.editButton') : t('environments.addButton')
)

onMounted(loadApplication)
</script>

<template>
    <div class="px-4 py-8 sm:px-8 lg:px-16">
        <!-- Back link -->
        <NuxtLink to="/applications" class="text-neutral-400 hover:text-primary-500 text-sm mb-6 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-10 bg-neutral-200 rounded w-1/3 mb-4" />
            <div class="h-4 bg-neutral-200 rounded w-2/3 mb-2" />
            <div class="h-4 bg-neutral-200 rounded w-1/2" />
        </div>

        <template v-else-if="application">
            <!-- Application header -->
            <div class="flex items-start justify-between pb-6">
                <div>
                    <h1 class="text-2xl font-bold text-primary-500 sm:text-4xl">{{ application.name }}</h1>
                    <p v-if="application.description" class="text-neutral-500 mt-2">{{ application.description }}</p>
                </div>
                <div class="flex gap-2">
                    <div class="flex items-center">
                        <MalioButtonIcon
                            :aria-label="t('applications.detail.editButton')"
                            variant="filled"
                            icon="mdi:pencil"
                            @click="openEditAppModal"
                        />
                    </div>
                    <div class="flex items-center">
                        <MalioButtonIcon
                            :aria-label="t('applications.detail.editButton')"
                            variant="filled"
                            icon="mdi:trash-can-outline"
                            button-class="bg-m-btn-danger hover:bg-m-btn-danger-hover active:bg-m-btn-danger-active text-white cursor-pointer"
                            @click="handleDeleteApp"
                        />
                    </div>
                </div>
            </div>

            <!-- Application info -->
            <div class="rounded-lg bg-tertiary-500 p-5 mb-8">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                    <div>
                        <span class="font-bold">{{ t('applications.detail.registryImage') }} :</span>
                        <span class="text-neutral-800 ml-1 font-mono">{{ application.registryImage }}</span>
                    </div>
                    <div v-if="application.giteaUrl">
                        <span class="font-bold">{{ t('applications.detail.giteaUrl') }} :</span>
                        <a :href="application.giteaUrl" target="_blank" class="text-primary-500 hover:underline ml-1">
                            {{ application.giteaUrl }}
                        </a>
                    </div>
                </div>
            </div>

            <!-- Environments section -->
            <div>
                <div class="flex items-center justify-between pb-4">
                    <h2 class="text-xl font-bold text-primary-500 sm:text-2xl">{{ t('environments.title') }}</h2>
                    <MalioButtonIcon
                        icon="mdi:plus"
                        aria-label="Retour"
                        @click="openCreateEnvModal"
                    />
                </div>

                <!-- Environments list -->
                <div v-if="!application.environments?.length" class="rounded-lg border border-neutral-200 bg-white p-6 text-center text-neutral-500">
                    {{ t('applications.card.noEnvironments') }}
                </div>

                <div v-for="env in application.environments" :key="env.id" class="rounded-lg bg-tertiary-500 p-5 mb-4">
                    <div class="flex items-start justify-between">
                        <div>
                            <div class="flex items-center gap-3">
                                <h3 class="text-lg font-semibold text-neutral-900">{{ env.name }}</h3>
                                <span
                                    class="inline-block rounded-full px-3 py-1 text-xs font-semibold"
                                    :class="env.maintenance
                                        ? 'bg-orange-100 text-orange-700'
                                        : 'bg-green-100 text-green-700'"
                                >
                                    {{ env.maintenance ? t('environments.maintenance.active') : t('environments.maintenance.inactive') }}
                                </span>
                            </div>
                            <p class="text-neutral-400 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
                                :label="t('logs.docker')"
                                variant="secondary"
                                icon-name="mdi:text-box-outline"
                                icon-position="left"
                                @click="openDockerLogs(env)"
                            />
                            <MalioButton
                                :label="t('environments.deploy.button')"
                                icon-name="mdi:rocket-launch-outline"
                                icon-position="left"
                                @click="openDeployModal(env)"
                            />
                            <MalioButton
                                :label="pendingMaintenanceByEnvId[env.id!]
                                    ? t('environments.maintenance.pending')
                                    : env.maintenance
                                        ? t('environments.maintenance.deactivate')
                                        : t('environments.maintenance.activate')"
                                :variant="env.maintenance ? 'danger' : 'primary'"
                                :icon-name="env.maintenance ? 'mdi:shield-check-outline' : 'mdi:alert-outline'"
                                icon-position="left"
                                :loading="!!pendingMaintenanceByEnvId[env.id!]"
                                @click="handleToggleMaintenance(env)"
                            />
                        </div>
                    </div>

                    <!-- Log files -->
                    <div v-if="env.logFiles.length" class="mt-4 border-t border-neutral-200 pt-3">
                        <p class="text-sm font-bold uppercase tracking-wider mb-2">{{ t('environments.logFiles.title') }}</p>
                        <div v-for="lf in env.logFiles" :key="lf.id" class="text-sm text-neutral-700 flex gap-2 items-center">
                            <span class="font-medium">{{ lf.label }}</span>
                            <span class="font-mono text-neutral-400">{{ lf.path }}</span>
                            <MalioButtonIcon
                                icon="mdi:console"
                                :aria-label="lf.label"
                                variant="ghost"
                                icon-size="16"
                                @click="openSymfonyLog(env, lf)"
                            />
                        </div>
                    </div>

                    <!-- Health metrics -->
                    <div v-if="healthByEnvId[env.id!]" class="mt-4 border-t border-neutral-200 py-3">
                        <p class="text-sm font-bold uppercase tracking-wider mb-2">{{ t('environments.health.title') }}</p>
                        <div class="grid grid-cols-2 sm:grid-cols-6 gap-3">
                            <div>
                                <p class="text-xs text-neutral-400">{{ t('environments.health.status') }}</p>
                                <span
                                    class="inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold mt-1"
                                    :class="statusClass(healthByEnvId[env.id!].status)"
                                >
                                    {{ t(`dashboard.status.${healthByEnvId[env.id!].status}`) }}
                                </span>
                            </div>
                            <div>
                                <p class="text-xs text-neutral-400">{{ t('environments.health.version') }}</p>
                                <p class="text-sm font-mono text-neutral-800 mt-1">{{ healthByEnvId[env.id!].version || '-' }}</p>
                            </div>
                            <div>
                                <p class="text-xs text-neutral-400">{{ t('environments.health.uptime') }}</p>
                                <p class="text-sm text-neutral-800 mt-1">{{ formatUptime(healthByEnvId[env.id!].startedAt) }}</p>
                            </div>
                            <div>
                                <p class="text-xs text-neutral-400">{{ t('environments.health.cpu') }}</p>
                                <p class="text-sm text-neutral-800 mt-1">{{ healthByEnvId[env.id!].cpuPercent }}%</p>
                            </div>
                            <div>
                                <p class="text-xs text-neutral-400">{{ t('environments.health.memory') }}</p>
                                <p class="text-sm text-neutral-800 mt-1">
                                    {{ healthByEnvId[env.id!].memoryUsage }} / {{ healthByEnvId[env.id!].memoryLimit }}
                                    <span class="text-neutral-400">({{ healthByEnvId[env.id!].memoryPercent }}%)</span>
                                </p>
                            </div>
                            <div>
                                <p class="text-xs text-neutral-400">{{ t('environments.health.ports') }}</p>
                                <div v-if="healthByEnvId[env.id!].ports?.length" class="mt-1 flex flex-wrap gap-1">
                                    <span
                                        v-for="(p, i) in healthByEnvId[env.id!].ports"
                                        :key="i"
                                        class="inline-block rounded bg-neutral-100 px-2 py-0.5 text-xs font-mono text-neutral-700"
                                    >
                                        {{ p.hostPort }}:{{ p.containerPort }}
                                    </span>
                                </div>
                                <p v-else class="text-sm text-neutral-400 mt-1">-</p>
                            </div>
                        </div>
                    </div>
                    <div class="flex justify-center gap-4 mt-4">
                        <MalioButton
                            :label="t('environments.editButton')"
                            variant="secondary"
                            icon-name="mdi:pencil"
                            icon-position="left"
                            @click="openEditEnvModal(env)"
                        />
                        <MalioButton
                            :label="t('environments.deleteButton')"
                            variant="danger"
                            icon-name="mdi:trash-can-outline"
                            icon-position="left"
                            @click="handleDeleteEnv(env.id!)"
                        />
                    </div>
                </div>
            </div>
        </template>

        <!-- Edit application modal -->
        <AppModal
            v-model="showAppModal"
            :submit-label="t('applications.form.save')"
            :cancel-label="t('applications.form.cancel')"
            :loading="isSubmittingApp"
            @submit="saveApp"
        >
            <template #title>{{ t('applications.detail.editButton') }}</template>

            <form @submit.prevent="saveApp" class="space-y-4">
                <div class="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2">
                    <MalioInputText
                        v-model="editForm.name"
                        :label="t('applications.form.name')"
                        required
                    />
                    <MalioInputText
                        v-model="editForm.slug"
                        :label="t('applications.form.slug')"
                        required
                    />
                    <MalioInputText
                        v-model="editForm.registryImage"
                        :label="t('applications.form.registryImage')"
                        hint="Ex : gitea.malio.fr/malio-dev/sirh"
                        required
                    />
                    <MalioInputText
                        v-model="editForm.giteaUrl"
                        :label="t('applications.form.giteaUrl')"
                        hint="Ex : https://gitea.malio.fr/malio-dev/sirh"
                    />
                </div>
                <div>
                    <label class="mb-1 block text-sm font-medium text-neutral-700">{{ t('applications.form.description') }}</label>
                    <textarea
                        v-model="editForm.description"
                        class="w-full rounded-md border border-neutral-300 px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:ring-2 focus:ring-secondary-500/20"
                        rows="3"
                    />
                </div>
            </form>
        </AppModal>

        <!-- Environment modal -->
        <AppModal
            v-model="showEnvModal"
            :submit-label="t('environments.form.save')"
            :cancel-label="t('environments.form.cancel')"
            :loading="isSubmittingEnv"
            @submit="saveEnv"
        >
            <template #title>{{ envModalTitle }}</template>

            <form @submit.prevent="saveEnv" class="space-y-4">
                <div class="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2">
                    <MalioInputText
                        v-model="envForm.name"
                        :label="t('environments.form.name')"
                        groupClass="mt-0"
                        required
                    />
                    <MalioInputText
                        v-model="envForm.containerName"
                        :label="t('environments.form.containerName')"
                        groupClass="mt-0"
                        required
                    />
                    <MalioInputText
                        v-model="envForm.deployScriptPath"
                        :label="t('environments.form.deployScriptPath')"
                        :hint="t('environments.form.pathHint')"
                        required
                    />
                    <MalioInputText
                        v-model="envForm.maintenanceFilePath"
                        :label="t('environments.form.maintenanceFilePath')"
                        :hint="t('environments.form.pathHint')"
                        required
                    />
                    <MalioInputText
                        v-model="envForm.appUrl"
                        :label="t('environments.form.appUrl')"
                        groupClass="mt-0"
                    />
                </div>

                <!-- Log files -->
                <div>
                    <div class="flex items-center justify-between mb-4">
                        <p class="text-md font-bold">{{ t('environments.logFiles.title') }}</p>
                        <button type="button" @click="addLogFile" class="text-primary-500 hover:underline text-sm font-semibold">
                            + {{ t('environments.logFiles.addButton') }}
                        </button>
                    </div>
                    <div v-for="(lf, index) in envForm.logFiles" :key="index" class="flex gap-2 mb-2">
                        <div class="w-1/3">
                            <MalioInputText v-model="lf.label" :label="t('environments.logFiles.label')" groupClass="mt-0" inputClass="flex-1" required />
                        </div>
                        <div class="w-2/3">
                            <MalioInputText v-model="lf.path" :label="t('environments.logFiles.path')" groupClass="mt-0" inputClass="flex-[2]" :hint="`${t('environments.form.pathHint')}/${application?.slug ?? ''}`" required />
                        </div>
                        <div class="h-[46px] flex items-center">
                            <MalioButtonIcon
                                icon="mdi:delete-outline"
                                :aria-label="t('environments.logFiles.remove')"
                                variant="ghost"
                                icon-size="18"
                                button-class="text-red-500 hover:bg-red-50 hover:text-red-700 my-1"
                                @click="removeLogFile(index)"
                            />
                        </div>
                    </div>
                </div>
            </form>
        </AppModal>

        <!-- Deploy modal -->
        <AppModal
            v-model="showDeployModal"
            :submit-label="isDeploying ? t('environments.deploy.deploying') : t('environments.deploy.confirm')"
            :cancel-label="t('applications.form.cancel')"
            :loading="isDeploying"
            max-width="xl"
            @submit="handleDeploy"
            @update:model-value="!$event && closeDeployModal()"
        >
            <template #title>{{ t('environments.deploy.title') }}</template>

            <!-- Tag selection -->
            <div v-if="!deployResult">
                <div v-if="loadingTags" class="py-8 text-center text-neutral-400">
                    <Icon name="mdi:loading" size="24" class="animate-spin" />
                    <p class="mt-2 text-sm">{{ t('environments.deploy.loadingTags') }}</p>
                </div>

                <div v-else-if="deployTags.length === 0" class="py-8 text-center text-neutral-400">
                    <Icon name="mdi:package-variant" size="32" />
                    <p class="mt-2 text-sm">{{ t('environments.deploy.noTags') }}</p>
                </div>

                <div v-else>
                    <label class="mb-1 block text-sm font-medium text-neutral-700">
                        {{ t('environments.deploy.selectTag') }}
                    </label>
                    <select
                        v-model="selectedTag"
                        class="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
                    >
                        <option v-for="tag in deployTags" :key="tag" :value="tag">
                            {{ tag }}
                        </option>
                    </select>
                </div>
            </div>

            <!-- Deploy result -->
            <div v-else>
                <div
                    class="mb-4 flex items-center gap-2 rounded-lg px-4 py-3"
                    :class="deployResult.success
                        ? 'bg-green-50 text-green-700'
                        : 'bg-red-50 text-red-700'"
                >
                    <Icon
                        :name="deployResult.success ? 'mdi:check-circle' : 'mdi:alert-circle'"
                        size="20"
                    />
                    <span class="text-sm font-semibold">
                        {{ deployResult.success
                            ? t('environments.deploy.success')
                            : t('environments.deploy.error')
                        }}
                    </span>
                    <span class="ml-auto text-xs font-mono">{{ deployResult.tag }}</span>
                </div>

                <div>
                    <p class="mb-2 text-xs font-semibold uppercase tracking-wider text-neutral-400">
                        {{ t('environments.deploy.output') }}
                    </p>
                    <pre class="max-h-80 overflow-auto rounded-lg bg-neutral-900 p-4 text-xs text-green-400 font-mono whitespace-pre-wrap">{{ deployResult.output }}</pre>
                </div>
            </div>

            <!-- Override footer when showing result -->
            <template v-if="deployResult" #footer>
                <MalioButton
                    :label="t('applications.form.cancel')"
                    variant="tertiary"
                    @click="closeDeployModal"
                />
            </template>
        </AppModal>

        <!-- Log modal -->
        <LogModal
            v-model="showLogModal"
            :title="logTitle"
            :content="logContent"
            :loading="logLoading"
            :show-level-filter="logIsSymfony"
            @refresh="refreshLogs"
        />
    </div>
</template>
