<script setup lang="ts">
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import AppLayout from "@/layouts/AppLayout.vue";
import { Head, Link, router } from "@inertiajs/vue3";
import {
    BoxesIcon,
    ChevronDownIcon,
    ExternalLinkIcon,
    GitBranchIcon,
    KeyRoundIcon,
    PencilIcon,
    PlusIcon,
    RocketIcon,
} from "lucide-vue-next";

defineProps<{
    application: Record<string, any>;
    deploymentRequirements: Record<string, any>;
}>();
</script>

<template>
    <Head title="Dashboard" />

    <AppLayout
        :breadcrumbs="[
            {
                title: 'Applications',
                href: route('applications.index', { organisation: $page.props.organisation.id }),
            },
            {
                title: application.name,
                href: route('applications.show', {
                    organisation: $page.props.organisation.id,
                    application: application.id,
                }),
            },
        ]"
    >
        <div class="flex h-full flex-1 flex-col gap-4 rounded-xl p-4">
            <div class="flex items-center gap-3">
                <div>
                    <h2 class="text-3xl font-bold tracking-tight">{{ application.name }}</h2>
                    <p class="mt-1 text-sm text-muted-foreground">
                        {{ application.source_provider?.name ?? "No source provider" }} ·
                        {{ application.repository_type }}
                    </p>
                </div>
                <Button
                    :as="Link"
                    size="sm"
                    variant="secondary"
                    :href="
                        route('applications.edit', {
                            organisation: $page.props.organisation.id,
                            application: application.id,
                        })
                    "
                >
                    <PencilIcon class="size-4" />
                    Edit
                </Button>
            </div>

            <Card v-if="application.deploy_key_public">
                <CardHeader>
                    <div class="flex items-start justify-between gap-4">
                        <div class="min-w-0 space-y-3">
                            <div class="flex items-center gap-2">
                                <KeyRoundIcon class="size-4" />
                                <CardTitle>Repository Deploy Key</CardTitle>
                                <Badge
                                    :variant="
                                        application.deploy_key_installed_at
                                            ? 'success'
                                            : 'secondary'
                                    "
                                >
                                    {{
                                        application.deploy_key_installed_at
                                            ? "verified"
                                            : "not verified"
                                    }}
                                </Badge>
                            </div>
                            <div
                                v-if="application.deploy_key_fingerprint"
                                class="text-sm text-muted-foreground"
                            >
                                Fingerprint: {{ application.deploy_key_fingerprint }}
                            </div>
                            <pre
                                class="max-w-full overflow-x-auto rounded border bg-muted p-3 text-xs"
                                >{{ application.deploy_key_public }}</pre
                            >
                        </div>
                        <div class="flex shrink-0 flex-wrap gap-2">
                            <Button
                                variant="secondary"
                                @click="
                                    router.post(
                                        route('applications.deploy-key.rotate', {
                                            organisation: $page.props.organisation.id,
                                            application: application.id,
                                        }),
                                    )
                                "
                            >
                                <KeyRoundIcon class="size-4" />
                                Rotate key
                            </Button>
                            <Button
                                @click="
                                    router.post(
                                        route('applications.verify-repository', {
                                            organisation: $page.props.organisation.id,
                                            application: application.id,
                                        }),
                                    )
                                "
                            >
                                <GitBranchIcon class="size-4" />
                                Verify access
                            </Button>
                        </div>
                    </div>
                </CardHeader>
            </Card>

            <Card v-if="deploymentRequirements.registryRequired">
                <CardHeader>
                    <div class="flex flex-wrap items-center justify-between gap-3">
                        <div>
                            <CardTitle>Registry required before deployment</CardTitle>
                            <CardDescription>
                                This organisation has {{ deploymentRequirements.serverCount }}
                                servers and no registry. Multi-server deployments need a registry so
                                every server can pull the same build artifact.
                            </CardDescription>
                        </div>
                        <Button
                            :as="Link"
                            :href="
                                route('registries.create', {
                                    organisation: $page.props.organisation.id,
                                })
                            "
                        >
                            Configure registry
                        </Button>
                    </div>
                </CardHeader>
            </Card>

            <div>
                <div class="mb-3 flex items-center justify-between">
                    <h3 class="text-2xl font-semibold tracking-tight">Environments</h3>
                    <Button
                        :as="Link"
                        size="sm"
                        :href="
                            route('environments.create', {
                                organisation: $page.props.organisation.id,
                                application: application.id,
                            })
                        "
                    >
                        <PlusIcon class="size-4" />
                        Add environment
                    </Button>
                </div>
                <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                    <Card
                        v-for="environment in application.environments"
                        :key="environment.id"
                        class="relative"
                    >
                        <CardHeader>
                            <div class="flex items-start justify-between gap-3">
                                <div>
                                    <div class="flex items-center gap-2">
                                        <BoxesIcon class="size-4" />
                                        <CardTitle>{{ environment.name }}</CardTitle>
                                        <Badge
                                            :variant="
                                                environment.status === 'active'
                                                    ? 'success'
                                                    : 'secondary'
                                            "
                                            >{{ environment.status.replace("-", " ") }}</Badge
                                        >
                                    </div>
                                    <CardDescription>
                                        Branch: {{ environment.branch }} &bull;
                                        {{ environment.services?.length ?? 0 }} services
                                    </CardDescription>
                                    <div class="mt-3 grid gap-1 text-sm text-muted-foreground">
                                        <div>
                                            Last deploy:
                                            {{
                                                environment.operations?.[0]?.finished_at ??
                                                environment.operations?.[0]?.created_at ??
                                                "never"
                                            }}
                                        </div>
                                        <div>
                                            Current commit:
                                            {{
                                                environment.services?.find(
                                                    (service) => service.desired_revision,
                                                )?.desired_revision ?? "unknown"
                                            }}
                                        </div>
                                        <div>
                                            Current image:
                                            {{
                                                environment.services?.find(
                                                    (service) =>
                                                        service.current_image_digest ||
                                                        service.available_image_digest,
                                                )?.current_image_digest ??
                                                environment.services?.find(
                                                    (service) => service.available_image_digest,
                                                )?.available_image_digest ??
                                                "unknown"
                                            }}
                                        </div>
                                    </div>
                                    <div
                                        v-if="environment.variables?.length"
                                        class="mt-3 flex flex-wrap gap-2"
                                    >
                                        <Badge
                                            v-for="variable in environment.variables"
                                            :key="variable.id"
                                            :variant="
                                                variable.source === 'user' ? 'secondary' : 'outline'
                                            "
                                        >
                                            {{ variable.key }} ·
                                            {{ variable.source.replace("_", " ") }}
                                            <span v-if="!variable.overridable"> · locked</span>
                                        </Badge>
                                    </div>
                                </div>
                                <div class="flex shrink-0 flex-wrap gap-2">
                                    <Button
                                        :as="Link"
                                        size="xs"
                                        variant="secondary"
                                        :href="
                                            route('environments.show', {
                                                organisation: $page.props.organisation.id,
                                                application: application.id,
                                                environment: environment.id,
                                            })
                                        "
                                    >
                                        <ExternalLinkIcon class="size-4" />
                                        Open
                                    </Button>
                                    <Button
                                        size="xs"
                                        :disabled="deploymentRequirements.registryRequired"
                                        :title="
                                            deploymentRequirements.registryRequired
                                                ? 'Configure a registry before deploying to multiple servers.'
                                                : undefined
                                        "
                                        @click="
                                            router.post(
                                                route('environment-deployments.store', {
                                                    organisation: $page.props.organisation.id,
                                                    application: application.id,
                                                    environment: environment.id,
                                                }),
                                            )
                                        "
                                    >
                                        <RocketIcon class="size-4" />
                                        Deploy
                                    </Button>
                                    <DropdownMenu>
                                        <DropdownMenuTrigger :as-child="true">
                                            <Button size="xs" variant="secondary">
                                                More
                                                <ChevronDownIcon class="size-4" />
                                            </Button>
                                        </DropdownMenuTrigger>
                                        <DropdownMenuContent align="end">
                                            <DropdownMenuItem
                                                :as="Link"
                                                :href="
                                                    route('environments.edit', {
                                                        organisation: $page.props.organisation.id,
                                                        application: application.id,
                                                        environment: environment.id,
                                                    })
                                                "
                                            >
                                                Settings
                                            </DropdownMenuItem>
                                            <DropdownMenuItem
                                                @click="
                                                    router.post(
                                                        route('environment-migrations.store', {
                                                            organisation:
                                                                $page.props.organisation.id,
                                                            application: application.id,
                                                            environment: environment.id,
                                                        }),
                                                    )
                                                "
                                            >
                                                Migrate
                                            </DropdownMenuItem>
                                            <DropdownMenuItem
                                                :as="Link"
                                                :href="
                                                    route('environment-variables.create', {
                                                        organisation: $page.props.organisation.id,
                                                        application: application.id,
                                                        environment: environment.id,
                                                    })
                                                "
                                            >
                                                Variables
                                            </DropdownMenuItem>
                                            <DropdownMenuItem
                                                @click="
                                                    router.post(
                                                        route('environment-workers.store', {
                                                            organisation:
                                                                $page.props.organisation.id,
                                                            application: application.id,
                                                            environment: environment.id,
                                                        }),
                                                    )
                                                "
                                            >
                                                Add worker
                                            </DropdownMenuItem>
                                            <DropdownMenuItem
                                                :as="Link"
                                                :href="
                                                    route('environment-attachments.create', {
                                                        organisation: $page.props.organisation.id,
                                                        application: application.id,
                                                        environment: environment.id,
                                                    })
                                                "
                                            >
                                                Attach service
                                            </DropdownMenuItem>
                                        </DropdownMenuContent>
                                    </DropdownMenu>
                                </div>
                            </div>
                            <div
                                v-if="environment.build_artifacts?.length"
                                class="mt-4 grid gap-2 rounded-md bg-muted/40 p-3 text-sm"
                            >
                                <div class="font-medium">Recent builds</div>
                                <div
                                    v-for="artifact in environment.build_artifacts"
                                    :key="artifact.id"
                                    class="flex flex-wrap items-center gap-2 text-muted-foreground"
                                >
                                    <Badge variant="outline">{{ artifact.status }}</Badge>
                                    <span>{{ artifact.commit_sha }}</span>
                                    <span v-if="artifact.image_digest">{{
                                        artifact.image_digest
                                    }}</span>
                                </div>
                            </div>
                        </CardHeader>
                    </Card>
                </div>
            </div>
        </div>
    </AppLayout>
</template>
