<script setup lang="ts">
    import { computed } from 'vue';
    import AppLayout from '@/layouts/AppLayout.vue';
    import { type BreadcrumbItem } from '@/types';
    import { Head, Link, usePage, useForm } from '@inertiajs/vue3';
    import { Button } from '@/components/ui/button';
    import { Input } from '@/components/ui/input';
    import { Label } from '@/components/ui/label';

    interface Department {
        id: number
        name: string
    };

    // Hent Inertia-props
    const page = usePage<{ department: Department }>();

    // Reaktiv avdeling
    const department = computed(() => page.props.department);

    // Sett opp skjema med eksisterende verdier
    const form = useForm({
        name: department.value.name,
    });

    // Breadcrumbs (Dashbord > Avdelinger > Rediger)
    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Dashbord',   href: '/dashboard' },
        { title: 'Avdelinger', href: '/smartdok/departments' },
        {
            title: 'Rediger',
            href: route('smartdok.departments.edit', department.value.id),
        },
    ];

    function submit() {
        form.put(
            route('smartdok.departments.update', department.value.id),
            { onSuccess: () => { /* Inertia håndterer redirect */ } }
        );
    }
</script>

<template>
    <Head title="Rediger avdeling" />   
    <AppLayout :breadcrumbs="breadcrumbs">
      <div class="p-6 space-y-8">
        <!-- Header -->
        <div class="flex items-center justify-between">
          <h3 class="scroll-m-20 text-2xl font-extrabold tracking-tight lg:text-3xl">
            Rediger avdeling
          </h3>
        </div>  
        <!-- Centered form -->
        <div class="flex justify-center items-center">
          <form
            @submit.prevent="submit"
            class="space-y-6 min-w-2xl lg:min-w-3xl xl:min-w-4xl"
          >
            <!-- Navn -->
            <div>
              <Label for="name">Navn</Label>
              <Input
                id="name"
                v-model="form.name"
                type="text"
                placeholder="Skriv inn avdelingsnavn"
                class="mt-2"
              />
              <p v-if="form.errors.name" class="mt-1 text-sm text-red-600">
                {{ form.errors.name }}
              </p>
            </div>  
            <!-- Actions -->
            <div class="flex items-center justify-end space-x-4">
              <Link :href="route('smartdok.departments.index')">
                <Button variant="outline">Avbryt</Button>
              </Link>
              <Button type="submit" :disabled="form.processing">
                Oppdater
              </Button>
            </div>
          </form>
        </div>
      </div>
    </AppLayout>
</template>
