<script lang="ts" setup>
import { computed, Ref, ref } from 'vue';
import { useForm, usePage } from '@inertiajs/vue3';
import ActionMessage from '@/Components/action-message.vue'
import FormControl from '@/Components/FormControl.vue';
import FormField from '@/Components/FormField.vue';
import CardBox from '@/Components/CardBox.vue';
import { mdiAccount } from '@mdi/js';
import BaseButton from '@/Components/BaseButton.vue';
import BaseButtons from '@/Components/BaseButtons.vue'
import { stardust } from '@eidellev/adonis-stardust/client';
import AvatarInput from '@/Components/avatar-input.vue';

const props = defineProps({
    user: {
        type: Object,
        required: true,
    },
    defaultUrl: {
        type: String,
        required: false,
    },
});

const errors: Ref<any> = computed(() => {
    return usePage().props.errors || {}
});
const flash: Ref<any> = computed(() => {
    return usePage().props.flash;
});

const fullName = computed(() => `${props.user.first_name} ${props.user.last_name}`);
const recentlyHasError = ref(false);

const form = useForm({
    first_name: props.user.first_name,
    last_name: props.user.last_name,
    login: props.user.login,
    email: props.user.email,
    // mobile: `${props.user.mobile}`,
    avatar: undefined as File | undefined,
});

// const verificationLinkSent = ref(null);
const avatarInput: Ref<HTMLInputElement | null> = ref(null);

const updateProfileInformation = () => {
    // if (avatarInput.value) {
    //     form.avatar = avatarInput.value?.files ? avatarInput.value.files[0] : undefined;
    // }

    form.put(stardust.route('settings.profile.update', [props.user.id]), {
        errorBag: 'updateProfileInformation',
        preserveScroll: true,
        onSuccess: () => {
            // clearPhotoFileInput();
        },
        onError: () => {
            if (form.errors.avatar) {
                if (avatarInput.value) {
                    avatarInput.value.value = '';
                }
            }
            recentlyHasError.value = true
            setTimeout(() => {
                recentlyHasError.value = false
            }, 5000)
        },
    });
};
// const sendEmailVerification = () => {
//     verificationLinkSent.value = true;
// };

</script>

<template>   
    <CardBox id="passwordForm" title="Basic Info" :icon="mdiAccount" form :show-header-icon="false">
        <!-- <FormValidationErrors v-bind:errors="errors" /> -->

        <AvatarInput class="h-24 w-24 rounded-full" v-model="form.avatar" ref="avatarInput"
            :default-src="defaultUrl ? defaultUrl : '/api/avatar?name=' + fullName + '&size=50'">
        </AvatarInput>
        <div class="text-red-400 text-sm" v-if="errors.avatar && Array.isArray(errors.avatar)">
            {{ errors.avatar.join(', ') }}
        </div>
      
        <FormField label="First Name" :class="{ 'text-red-400': form.errors.first_name }">
            <FormControl id="first_name" label="First Name" v-model="form.first_name" :error="form.errors.first_name"
                type="text" :placeholder="'First Name'" class="w-full" autocomplete="first_name">
                <div class="text-red-400 text-sm" v-if="errors.first_name && Array.isArray(errors.first_name)">
                    {{ errors.first_name.join(', ') }}
                </div>
            </FormControl>
        </FormField>

        <FormField label="Last Name" :class="{ 'text-red-400': form.errors.last_name }">
            <FormControl id="last_name" label="Last Name" v-model="form.last_name" :error="form.errors.last_name"
                type="text" :placeholder="'Last Name'" class="w-full" autocomplete="last_name">
                <div class="text-red-400 text-sm" v-if="errors.last_name && Array.isArray(errors.last_name)">
                    {{ errors.last_name.join(', ') }}
                </div>
            </FormControl>
        </FormField>

        <FormField label="Username" :class="{ 'text-red-400': form.errors.login }">
            <FormControl id="username" label="Username" v-model="form.login" class="w-full"
                :is-read-only="!user.is_admin">
                <div class="text-red-400 text-sm" v-if="errors.login && Array.isArray(errors.login)">
                    {{ errors.login.join(', ') }}
                </div>
            </FormControl>

        </FormField>

        <FormField label="Enter Email">
            <FormControl v-model="form.email" type="text" placeholder="Email" :errors="form.errors.email"
                :is-read-only="!user.is_admin">
                <div class="text-red-400 text-sm" v-if="errors.email && Array.isArray(errors.email)">
                    {{ errors.email.join(', ') }}
                </div>
            </FormControl>
        </FormField>

        <!-- Email -->
        <!-- <div>
            <FormControl label="Email" id="email" v-model="form.email" :readonly="!user.is_super_admin"
                :disabled="!user.is_super_admin" class="w-full" />

            <div v-if="user.email_verified_at === null">
                <p class="text-sm mt-2">
                    {{ 'Your email address is unverified.' }}

                    <Link :href="route('verification.send')" method="post" as="button"
                        class="underline text-gray-600 hover:text-gray-900" @click.prevent="sendEmailVerification">
                    {{ 'Click here to re-send the verification email.' }}
                    </Link>
                </p>

                <div v-show="verificationLinkSent" class="mt-2 font-medium text-sm text-green-600">
                    {{ 'A new verification link has been sent to your email address.' }}
                </div>
            </div>
        </div> -->

        <!-- <div class="relative">
            <FormControl label="Mobile" id="mobile" class="w-full" input-class="w-full pl-5" v-model="form.mobile"
                :readonly="!user.is_super_admin" :disabled="!user.is_super_admin" />
            <span class="absolute top-9 left-0 inline-flex items-center ml-2 font-bold text-secondary-light">+</span>
        </div> -->

        <!-- <div class="col-span-2 flex justify-end items-center mt-5"> -->
        <template #footer>
            <div class="flex items-center justify-end gap-3 ">
                <ActionMessage :on="recentlyHasError" color="warning">
                    <ul class="list-disc list-inside space-y-2 text-sm">
                        <li v-for="(messages, field) in errors" :key="field" class="flex flex-col">
                            <span class="font-semibold capitalize text-gray-700 dark:text-gray-300">{{ field }}:</span>
                            <span class="text-red-600 dark:text-red-400 ml-4">{{ messages.join(', ') }}</span>
                        </li>
                    </ul>
                </ActionMessage>
                <ActionMessage v-if="flash.message" :on="form.recentlySuccessful" color="success">
                    {{ flash.message }}
                </ActionMessage>
                <ActionMessage v-if="flash.warning" :on="form.recentlySuccessful" color="warning">
                    {{ flash.warning }}
                </ActionMessage>
                <BaseButtons>
                    <BaseButton type="submit" color="info" label="Save Changes"
                        @click.prevent="updateProfileInformation" :disabled="form.processing" />
                </BaseButtons>
            </div>
        </template>
    </CardBox>

    <!-- </div>
    </div> -->
</template>