<script setup lang="ts">
import { ref } from 'vue';
import { Head, useForm } from '@inertiajs/vue3';
import { mdiAccountKey, mdiArrowLeftBoldOutline } 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';
import PasswordMeter from '@/Components/SimplePasswordMeter/password-meter.vue';

const props = defineProps({
    user: { type: Object, default: () => ({}) },
    roles: { type: Object, default: () => ({}) },
    userHasRoles: { type: Object, default: () => ({}) },
    errors: { type: Object, default: () => ({}) }, // Fallback
});

// enabled ist true, solange kein (schwaches) Passwort eingegeben wird
const enabled = ref(true); 

const form = useForm({
    _method: 'put',
    login: props.user.login,
    first_name: props.user.first_name,
    last_name:  props.user.last_name,
    email: props.user.email,
    new_password: '',
    password_confirmation: '',
    roles: props.userHasRoles, // fill actual user roles from db
});

const submit = () => {
    form.put(stardust.route('settings.user.update', [props.user.id]), {
        preserveScroll: true,
        onSuccess: () => {
            // Bei Erfolg Passwortfelder leeren
            form.reset('new_password', 'password_confirmation');
        },
        onError: () => {
            if (form.errors.new_password) {
                form.reset('new_password', 'password_confirmation');
                enabled.value = false;
            }
        },
    });
};

const formatError = (error: string | string[] | undefined) => {
    if (!error) return '';
    return Array.isArray(error) ? error.join(', ') : error;
};

const handleScore = (score: number) => {
    // Wenn das Feld leer ist, ist der Status egal (Passwort wird nicht geändert)
    // Wenn etwas drin steht, muss der Score >= 4 sein
    if (form.new_password === '') {
        enabled.value = true;
    } else {
        enabled.value = score >= 4;
    }
};
</script>

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

            <CardBox form @submit.prevent="submit">
                <FormField label="Login" :class="{ 'text-red-400': form.errors.login }">
                    <FormControl v-model="form.login" type="text" placeholder="Login" :errors="form.errors.login">
                        <div class="text-red-400 text-sm mt-1" v-if="form.errors.login">
                            {{ formatError(form.errors.login) }}
                        </div>
                    </FormControl>
                </FormField>

                <FormField label="First Name" :class="{ 'text-red-400': form.errors.first_name }">
                    <FormControl v-model="form.first_name" type="text" placeholder="First Name" :errors="form.errors.first_name">
                        <div class="text-red-400 text-sm mt-1" v-if="form.errors.first_name">
                            {{ formatError(form.errors.first_name) }}
                        </div>
                    </FormControl>
                </FormField>

                <FormField label="Last Name" :class="{ 'text-red-400': form.errors.last_name }">
                    <FormControl v-model="form.last_name" type="text" placeholder="Last Name" :errors="form.errors.last_name">
                        <div class="text-red-400 text-sm mt-1" v-if="form.errors.last_name">
                            {{ formatError(form.errors.last_name) }}
                        </div>
                    </FormControl>
                </FormField>

                <FormField label="Email" :class="{ 'text-red-400': form.errors.email }">
                    <FormControl v-model="form.email" type="text" placeholder="Email" :errors="form.errors.email">
                        <div class="text-red-400 text-sm mt-1" v-if="form.errors.email">
                            {{ formatError(form.errors.email) }}
                        </div>
                    </FormControl>
                </FormField>

                <div class="py-4">
                    <PasswordMeter 
                        field-label="Reset User Password (leave blank to keep current)" 
                        :show-required-message="false" 
                        v-model="form.new_password" 
                        :errors="form.errors" 
                        @score="handleScore" 
                    />
                    <!-- <div class="text-red-400 text-sm mt-1" v-if="form.errors.new_password">
                        {{ formatError(form.errors.new_password) }}
                    </div> -->
                </div>

                <FormField label="Password Confirmation" :class="{ 'text-red-400': form.errors.password_confirmation }">
                    <FormControl
                        v-model="form.password_confirmation"
                        type="password"
                        placeholder="Confirm New Password"
                        :errors="form.errors.password_confirmation"
                    >
                        <div class="text-red-400 text-sm mt-1" v-if="form.errors.password_confirmation">
                            {{ formatError(form.errors.password_confirmation) }}
                        </div>
                    </FormControl>
                </FormField>

                <BaseDivider />

                <FormField label="Roles" wrap-body :class="{ 'text-red-400': form.errors.roles }">
                    <FormCheckRadioGroup v-model="form.roles" name="roles" is-column :options="props.roles" />
                    <div class="text-red-400 text-sm mt-1" v-if="form.errors.roles">
                        {{ formatError(form.errors.roles) }}
                    </div>
                </FormField>

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