<script setup lang="ts">
import InputError from "@/components/InputError.vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import AppLayout from "@/layouts/AppLayout.vue";
import { Head, useForm } from "@inertiajs/vue3";
import { computed, watch } from "vue";

const props = defineProps<{
    application: Record<string, any>;
    environment: Record<string, any>;
    services: Record<string, any>[];
    roles: string[];
    compatibility: Record<string, string[]>;
}>();

const form = useForm({
    service_id: String(props.services[0]?.id ?? ""),
    role: "database",
    name: "",
    env_prefix: "",
    is_primary: true,
    domain: "",
    path_prefix: "/",
    tls_enabled: true,
});

const compatibleServices = computed(() => {
    return props.services.filter((service) =>
        (props.compatibility[form.role] ?? props.services.map((item) => item.type)).includes(
            service.type,
        ),
    );
});

const selectedService = computed(() =>
    props.services.find((service) => String(service.id) === form.service_id),
);
const generatedSliceType = computed(() => {
    if (selectedService.value?.type === "postgres") {
        return "database user";
    }

    if (selectedService.value?.type === "valkey") {
        return "logical database";
    }

    if (selectedService.value?.type === "caddy") {
        return "route";
    }

    return "service link";
});

const envPrefix = computed(() => form.env_prefix || form.role.toUpperCase());
const variablePreview = computed(() => {
    if (form.role === "database") {
        return [
            `${envPrefix.value}_HOST`,
            `${envPrefix.value}_PORT`,
            `${envPrefix.value}_DATABASE`,
            `${envPrefix.value}_USERNAME`,
            `${envPrefix.value}_PASSWORD`,
        ];
    }

    if (["cache", "queue"].includes(form.role)) {
        return [
            `${envPrefix.value}_HOST`,
            `${envPrefix.value}_PORT`,
            `${envPrefix.value}_DATABASE`,
            `${envPrefix.value}_PASSWORD`,
        ];
    }

    if (form.role === "gateway") {
        return ["APP_URL", "KEYSTONE_ROUTE_HOST", "KEYSTONE_ROUTE_PORT", "KEYSTONE_ROUTE_TLS"];
    }

    return [`${envPrefix.value}_HOST`, `${envPrefix.value}_PORT`];
});

watch(
    compatibleServices,
    (services) => {
        if (services.length && !services.some((service) => service.id === form.service_id)) {
            form.service_id = services[0].id;
        }
    },
    { immediate: true },
);
</script>

<template>
    <Head title="Attach Managed Service" />

    <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,
                }),
            },
            {
                title: 'Attach Managed Service',
            },
        ]"
    >
        <form
            class="flex h-full max-w-2xl flex-1 flex-col gap-5 p-4"
            @submit.prevent="
                form.post(
                    route('environment-attachments.store', {
                        organisation: $page.props.organisation.id,
                        application: application.id,
                        environment: environment.id,
                    }),
                )
            "
        >
            <div>
                <h2 class="text-3xl font-bold tracking-tight">Attach Managed Service</h2>
            </div>

            <div class="grid gap-2">
                <Label for="service_id">Service</Label>
                <Select v-model="form.service_id">
                    <SelectTrigger id="service_id">
                        <SelectValue placeholder="Select a service" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem
                            v-for="service in compatibleServices"
                            :key="service.id"
                            :value="String(service.id)"
                        >
                            {{ service.name }} · {{ service.type }}
                        </SelectItem>
                    </SelectContent>
                </Select>
                <InputError :message="form.errors.service_id" />
            </div>

            <div class="rounded-md border bg-muted/30 p-3 text-sm">
                <div class="font-medium">Generated {{ generatedSliceType }}</div>
                <div class="mt-1 text-muted-foreground">
                    {{ selectedService?.name ?? "No compatible service" }} ·
                    {{ form.role.replace("_", " ") }}
                </div>
            </div>

            <div class="rounded-md border bg-muted/30 p-3 text-sm">
                <div class="font-medium">Environment variables preview</div>
                <div class="mt-2 flex flex-wrap gap-2">
                    <code
                        v-for="variable in variablePreview"
                        :key="variable"
                        class="rounded bg-background px-2 py-1 text-xs"
                    >
                        {{ variable }}
                    </code>
                </div>
            </div>

            <div class="grid gap-2">
                <Label for="role">Role</Label>
                <Select v-model="form.role">
                    <SelectTrigger id="role">
                        <SelectValue placeholder="Select a role" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem v-for="role in roles" :key="role" :value="role">
                            {{ role.replace("_", " ") }}
                        </SelectItem>
                    </SelectContent>
                </Select>
                <InputError :message="form.errors.role" />
            </div>

            <div class="grid gap-4 md:grid-cols-2">
                <div class="grid gap-2">
                    <Label for="name">Slice name</Label>
                    <Input
                        id="name"
                        v-model="form.name"
                        type="text"
                        placeholder="billing_api_production"
                    />
                    <InputError :message="form.errors.name" />
                </div>

                <div class="grid gap-2">
                    <Label for="env_prefix">Env prefix</Label>
                    <Input
                        id="env_prefix"
                        v-model="form.env_prefix"
                        type="text"
                        placeholder="READONLY"
                    />
                    <InputError :message="form.errors.env_prefix" />
                </div>
            </div>

            <div
                v-if="form.role === 'gateway'"
                class="grid gap-4 rounded-md border p-3 md:grid-cols-3"
            >
                <div class="grid gap-2">
                    <Label for="domain">Domain</Label>
                    <Input
                        id="domain"
                        v-model="form.domain"
                        type="text"
                        placeholder="app.example.com"
                    />
                    <InputError :message="form.errors.domain" />
                </div>
                <div class="grid gap-2">
                    <Label for="path_prefix">Path prefix</Label>
                    <Input
                        id="path_prefix"
                        v-model="form.path_prefix"
                        type="text"
                        placeholder="/"
                    />
                    <InputError :message="form.errors.path_prefix" />
                </div>
                <label class="flex items-center gap-2 pt-7 text-sm">
                    <input v-model="form.tls_enabled" type="checkbox" class="size-4" />
                    TLS enabled
                </label>
            </div>

            <label class="flex items-center gap-2 text-sm">
                <input v-model="form.is_primary" type="checkbox" class="size-4" />
                <span>
                    Primary attachment
                    <span class="block text-muted-foreground">
                        Primary attachments provide the default unprefixed variables for this role.
                    </span>
                </span>
            </label>

            <div class="flex items-center justify-end">
                <Button type="submit" :disabled="form.processing || !services.length"
                    >Attach</Button
                >
            </div>
        </form>
    </AppLayout>
</template>
