<script setup lang="ts">
import { Head, useForm } from '@inertiajs/vue3';
import { mdiAccountKey, mdiArrowLeftBoldOutline, mdiFormTextarea } from '@mdi/js';
import LayoutAuthenticated from '@/Layouts/LayoutAuthenticated.vue';
import SectionMain from '@/Components/SectionMain.vue';
import SectionTitleLineWithButton from '@/Components/SectionTitleLineWithButton.vue';
import CardBox from '@/Components/CardBox.vue';
import FormField from '@/Components/FormField.vue';
import FormControl from '@/Components/FormControl.vue';
import FormCheckRadioGroup from '@/Components/FormCheckRadioGroup.vue';
import BaseDivider from '@/Components/BaseDivider.vue';
import BaseButton from '@/Components/BaseButton.vue';
import BaseButtons from '@/Components/BaseButtons.vue';
import { stardust } from '@eidellev/adonis-stardust/client';

const props = defineProps({
    role: { type: Object, default: () => ({}) },
    permissions: { type: Object, default: () => ({}) },
    roleHasPermissions: { type: Object, default: () => ({}) },
});

const form = useForm({
    _method: 'put',
    name: props.role.name,
    display_name: props.role.display_name || '', // Neu hinzugefügt
    description: props.role.description || '',
    permissions: props.roleHasPermissions || [],
});

const submit = () => {
    form.put(stardust.route('settings.role.update', [props.role.id]), {
        preserveScroll: true,
    });
};

/**
 * Sicherer Helper für die Fehleranzeige
 */
// const formatError = (error: string | string[] | undefined) => {
//     if (!error) return '';
//     return Array.isArray(error) ? error.join(', ') : error;
// };

/**
 * AUTOMATISCHER ERROR-CLEANER
 * Löscht Fehlermeldungen sofort, wenn der User mit der Korrektur beginnt.
 */
// watch(() => ({ ...form.data() }), (newData, oldData) => {
//     for (const key in newData) {
//         // Vergleich via JSON.stringify für Arrays (permissions)
//         if (JSON.stringify(newData[key]) !== JSON.stringify(oldData[key]) && form.errors[key]) {
//             form.clearErrors(key as any);
//         }
//     }
// }, { deep: true });
</script>

<template>
    <LayoutAuthenticated>
        <Head title="Update role" />
        <SectionMain>
            <SectionTitleLineWithButton :icon="mdiAccountKey" title="Update role" main>
                <BaseButton
                    :route-name="stardust.route('settings.role.index')"
                    :icon="mdiArrowLeftBoldOutline"
                    label="Back"
                    color="white"
                    rounded-full
                    small
                />
            </SectionTitleLineWithButton>

            <CardBox form @submit.prevent="submit">
                <FormField label="System Name" help="Technical identifier, cannot be changed." :errors="form.errors.name">
                    <FormControl v-model="form.name" :error="form.errors.name" :is-read-only="true" />
                </FormField>

                <FormField label="Display Name" help="User-friendly name for this role." :errors="form.errors.display_name">
                    <FormControl v-model="form.display_name" placeholder="e.g. Administrator" :error="form.errors.display_name" />
                </FormField>

                <FormField label="Description" :errors="form.errors.description">
                    <FormControl
                        v-model="form.description"
                        :icon="mdiFormTextarea"
                        type="textarea"
                        placeholder="Role description..."
                        :error="form.errors.description"
                    />
                </FormField>

                <BaseDivider />

                <FormField label="Permissions" :errors="form.errors.permissions">
                    <FormCheckRadioGroup v-model="form.permissions" name="permissions" is-column :options="props.permissions" />
                </FormField>

                <template #footer>
                    <BaseButtons>
                        <BaseButton
                            type="submit"
                            color="info"
                            label="Update Role"
                            :class="{ 'opacity-25': form.processing }"
                            :disabled="form.processing"
                        />
                    </BaseButtons>
                </template>
            </CardBox>
        </SectionMain>
    </LayoutAuthenticated>
</template>
