<script setup>
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 AppLayout from '@/layouts/AppLayout.vue';
import { Head, useForm } from '@inertiajs/vue3';
import { computed, watch } from 'vue';

const props = defineProps({
    application: {
        type: Object,
        required: true,
    },
    environment: {
        type: Object,
        required: true,
    },
    services: {
        type: Array,
        required: true,
    },
    roles: {
        type: Array,
        required: true,
    },
});

const form = useForm({
    service_id: props.services[0]?.id ?? null,
    role: 'database',
    name: '',
    env_prefix: '',
    is_primary: true,
});

const compatibleServices = computed(() => {
    const roleTypes = {
        database: ['postgres'],
        cache: ['valkey'],
        queue: ['valkey'],
        gateway: ['caddy'],
    };

    return props.services.filter((service) => (roleTypes[form.role] ?? props.services.map((item) => item.type)).includes(service.type));
});

const selectedService = computed(() => props.services.find((service) => 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';
});

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 id="service_id" v-model="form.service_id" class="h-9 rounded-md border border-input bg-transparent px-3 text-sm">
                    <option v-for="service in compatibleServices" :key="service.id" :value="service.id">
                        {{ service.name }} · {{ service.type }}
                    </option>
                </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="grid gap-2">
                <Label for="role">Role</Label>
                <select id="role" v-model="form.role" class="h-9 rounded-md border border-input bg-transparent px-3 text-sm">
                    <option v-for="role in roles" :key="role" :value="role">
                        {{ role.replace('_', ' ') }}
                    </option>
                </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>

            <label class="flex items-center gap-2 text-sm">
                <input v-model="form.is_primary" type="checkbox" class="size-4" />
                Primary attachment
            </label>

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