<script setup lang="ts">
import InputError from "@/components/InputError.vue";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import AppLayout from "@/layouts/AppLayout.vue";
import { Head, router, useForm } from "@inertiajs/vue3";

const props = defineProps<{
    server: Record<string, any>;
    service: Record<string, any>;
    deployPolicies: string[];
}>();

const serviceConfig = props.service.config ?? {};

const form = useForm({
    name: props.service.name,
    desired_replicas: props.service.desired_replicas,
    default_cpu_limit: props.service.default_cpu_limit,
    default_memory_limit_mb: props.service.default_memory_limit_mb,
    deploy_policy: props.service.deploy_policy,
    version_track: props.service.version_track,
    available_image_digest: props.service.available_image_digest ?? "",
    process_roles: props.service.process_roles?.join(", ") ?? "",
    migration_mode: serviceConfig.migration_mode ?? "",
    migration_timing: serviceConfig.migration_timing ?? "",
    migration_command: serviceConfig.migration_command ?? "",
    health_path: serviceConfig.health_path ?? "/up",
    backup_enabled: Boolean(serviceConfig.backup_enabled),
    backup_command: serviceConfig.backup_command ?? "",
});

const destroyService = (): void => {
    if (!window.confirm(`Delete ${props.service.name}?`)) {
        return;
    }

    router.delete(
        route("services.destroy", {
            organisation: props.server.organisation_id,
            server: props.server.id,
            service: props.service.id,
        }),
    );
};
</script>

<template>
    <Head :title="`Edit ${service.name}`" />

    <AppLayout
        :breadcrumbs="[
            {
                title: 'Servers',
                href: route('servers.index', { organisation: $page.props.organisation.id }),
            },
            {
                title: server.name,
                href: route('servers.show', {
                    organisation: $page.props.organisation.id,
                    server: server.id,
                }),
            },
            {
                title: service.name,
                href: route('services.show', {
                    organisation: $page.props.organisation.id,
                    server: server.id,
                    service: service.id,
                }),
            },
            { title: 'Edit' },
        ]"
    >
        <form
            class="flex h-full max-w-4xl flex-1 flex-col gap-5 p-4"
            @submit.prevent="
                form.put(
                    route('services.update', {
                        organisation: $page.props.organisation.id,
                        server: server.id,
                        service: service.id,
                    }),
                )
            "
        >
            <div>
                <h2 class="text-3xl font-bold tracking-tight">Edit {{ service.name }}</h2>
                <p class="mt-1 text-sm text-muted-foreground">
                    Deployment, runtime, migration, scheduler role, and health-check defaults.
                </p>
            </div>

            <Card>
                <CardHeader>
                    <CardTitle>Runtime</CardTitle>
                </CardHeader>
                <CardContent class="grid gap-4">
                    <div class="grid gap-2">
                        <Label for="name">Name</Label>
                        <Input id="name" v-model="form.name" type="text" required />
                        <InputError :message="form.errors.name" />
                    </div>

                    <div class="grid gap-4 md:grid-cols-3">
                        <div class="grid gap-2">
                            <Label for="desired_replicas">Replicas</Label>
                            <Input
                                id="desired_replicas"
                                v-model="form.desired_replicas"
                                type="number"
                                min="0"
                                max="25"
                            />
                            <InputError :message="form.errors.desired_replicas" />
                        </div>
                        <div class="grid gap-2">
                            <Label for="default_cpu_limit">CPU</Label>
                            <Input
                                id="default_cpu_limit"
                                v-model="form.default_cpu_limit"
                                type="number"
                                min="0.125"
                                max="64"
                                step="0.125"
                            />
                            <InputError :message="form.errors.default_cpu_limit" />
                        </div>
                        <div class="grid gap-2">
                            <Label for="default_memory_limit_mb">Memory MB</Label>
                            <Input
                                id="default_memory_limit_mb"
                                v-model="form.default_memory_limit_mb"
                                type="number"
                                min="64"
                                max="1048576"
                            />
                            <InputError :message="form.errors.default_memory_limit_mb" />
                        </div>
                    </div>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Deployment</CardTitle>
                    <CardDescription>Stateful services can track available image updates.</CardDescription>
                </CardHeader>
                <CardContent class="grid gap-4 md:grid-cols-2">
                    <div class="grid gap-2">
                        <Label for="deploy_policy">Deploy policy</Label>
                        <select
                            id="deploy_policy"
                            v-model="form.deploy_policy"
                            class="h-9 rounded-md border border-input bg-transparent px-3 text-sm"
                        >
                            <option v-for="policy in deployPolicies" :key="policy" :value="policy">
                                {{ policy.replace("_", " ") }}
                            </option>
                        </select>
                        <InputError :message="form.errors.deploy_policy" />
                    </div>
                    <div class="grid gap-2">
                        <Label for="version_track">Version track</Label>
                        <Input id="version_track" v-model="form.version_track" />
                        <InputError :message="form.errors.version_track" />
                    </div>
                    <div class="grid gap-2 md:col-span-2">
                        <Label for="available_image_digest">Available image digest</Label>
                        <Input id="available_image_digest" v-model="form.available_image_digest" />
                        <InputError :message="form.errors.available_image_digest" />
                    </div>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Roles, Migrations & Health</CardTitle>
                </CardHeader>
                <CardContent class="grid gap-4 md:grid-cols-2">
                    <div class="grid gap-2 md:col-span-2">
                        <Label for="process_roles">Process roles</Label>
                        <Input id="process_roles" v-model="form.process_roles" placeholder="web, scheduler" />
                        <InputError :message="form.errors.process_roles" />
                    </div>
                    <div class="grid gap-2">
                        <Label for="migration_mode">Migration mode</Label>
                        <Input id="migration_mode" v-model="form.migration_mode" />
                        <InputError :message="form.errors.migration_mode" />
                    </div>
                    <div class="grid gap-2">
                        <Label for="migration_timing">Migration timing</Label>
                        <Input id="migration_timing" v-model="form.migration_timing" />
                        <InputError :message="form.errors.migration_timing" />
                    </div>
                    <div class="grid gap-2">
                        <Label for="migration_command">Migration command</Label>
                        <Input id="migration_command" v-model="form.migration_command" />
                        <InputError :message="form.errors.migration_command" />
                    </div>
                    <div class="grid gap-2">
                        <Label for="health_path">Health path</Label>
                        <Input id="health_path" v-model="form.health_path" />
                        <InputError :message="form.errors.health_path" />
                    </div>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Backups</CardTitle>
                    <CardDescription>
                        Enabled backups can be run before guided stateful service updates.
                    </CardDescription>
                </CardHeader>
                <CardContent class="grid gap-4">
                    <label class="flex items-center gap-2 text-sm">
                        <input
                            v-model="form.backup_enabled"
                            type="checkbox"
                            class="rounded border-input"
                        />
                        Enable pre-update backup option
                    </label>
                    <InputError :message="form.errors.backup_enabled" />
                    <div class="grid gap-2">
                        <Label for="backup_command">Backup command</Label>
                        <Input
                            id="backup_command"
                            v-model="form.backup_command"
                            placeholder="pg_dump --format=custom app > /home/keystone/backups/pre-update.dump"
                        />
                        <InputError :message="form.errors.backup_command" />
                    </div>
                </CardContent>
            </Card>

            <div class="flex flex-wrap justify-between gap-2">
                <Button type="button" variant="destructive" @click="destroyService">
                    Delete service
                </Button>
                <Button type="submit" :disabled="form.processing">Save</Button>
            </div>
        </form>
    </AppLayout>
</template>
