<script setup>
import { ref } from "vue";
import { Inertia } from "@inertiajs/inertia";
import { Link, useForm } from "@inertiajs/inertia-vue3";
import JetButton from "@/Jetstream/Button.vue";
import JetFormSection from "@/Jetstream/FormSection.vue";
import JetInput from "@/Jetstream/Input.vue";
import JetInputError from "@/Jetstream/InputError.vue";
import JetLabel from "@/Jetstream/Label.vue";
import JetActionMessage from "@/Jetstream/ActionMessage.vue";
import JetSecondaryButton from "@/Jetstream/SecondaryButton.vue";
import CurrencySelect from "@/components/CurrencySelect";

const props = defineProps({
    user: Object,
});

const form = useForm({
    _method: "PUT",
    name: props.user.name,
    email: props.user.email,
    tag_line: props.user?.tag_line || null,
    photo: null,
    cover_photo: null,
});

const resend = useForm({});

const verificationLinkSent = ref(null);

const photoPreview = ref(null);

const coverPhotoPreview = ref(null);

const photoInput = ref(null);

const coverPhotoInput = ref(null);

const updateProfileInformation = () => {
    if (photoInput.value) {
        form.photo = photoInput.value.files[0];
    }
    if (coverPhotoInput.value) {
        form.cover_photo = coverPhotoInput.value.files[0];
    }

    form.post(route("user-profile-information.update"), {
        errorBag: "updateProfileInformation",
        preserveScroll: true,
        onSuccess: () => clearPhotoFileInput(),
    });
};

const sendEmailVerification = () => {
    resend.post(route("verification.send"), {
        preserveScroll: true,
        onSuccess: (res) => {
            verificationLinkSent.value = true;
        },
    });
};

const selectNewPhoto = () => {
    photoInput.value.click();
};
const selectNewCoverPhoto = () => {
    coverPhotoInput.value.click();
};

const updatePhotoPreview = () => {
    const photo = photoInput.value?.files[0];

    if (!photo) return;

    const reader = new FileReader();

    reader.onload = (e) => {
        photoPreview.value = e.target.result;
    };

    reader.readAsDataURL(photo);
};

const updateCoverPhotoPreview = () => {
    const photo = coverPhotoInput.value?.files[0];

    if (!photo) return;

    const reader = new FileReader();

    reader.onload = (e) => {
        coverPhotoPreview.value = e.target.result;
    };

    reader.readAsDataURL(photo);
};

const deletePhoto = () => {
    Inertia.delete(route("current-user-photo.destroy"), {
        preserveScroll: true,
        onSuccess: () => {
            photoPreview.value = null;
            clearPhotoFileInput();
        },
    });
};

const clearPhotoFileInput = () => {
    if (photoInput.value?.value) {
        photoInput.value.value = null;
    }
};
</script>

<template>
    <JetFormSection @submitted="updateProfileInformation">
        <template #title> {{ $t("Register.Profile_information") }} </template>

        <template #description>
            {{ $t("Register.updated_data") }}
        </template>

        <template #form="{ valid }">
            <!-- Profile Photo -->
            <div
                v-if="$page.props.jetstream.managesProfilePhotos"
                class="col-span-6"
            >
                <!-- Profile Photo File Input -->
                <input
                    class="hidden"
                    type="file"
                    ref="coverPhotoInput"
                    id="coverPhotoInput"
                    accept="image/*"
                    @change="updateCoverPhotoPreview"
                />

                <JetLabel
                    for="coverPhotoInput"
                    :value="$t('Register.cover_photo')"
                />

                <!-- Current Profile Photo -->
                <div v-show="!coverPhotoPreview" class="mt-2">
                    <img
                        :src="user.cover_photo_path"
                        :alt="user.name"
                        @click.prevent="selectNewCoverPhoto"
                        class="object-cover w-full h-40 cursor-pointer rounded-2xl no-magnify"
                    />
                </div>
                <!-- cover_photo_path -->

                <!-- New Profile Photo Preview -->
                <div v-show="coverPhotoPreview" class="mt-2">
                    <span
                        class="block w-full h-40 bg-center bg-no-repeat bg-cover cursor-pointer rounded-2xl no-magnify"
                        @click.prevent="selectNewCoverPhoto"
                        :style="
                            'background-image: url(\'' +
                            coverPhotoPreview +
                            '\');'
                        "
                    />
                </div>

                <JetSecondaryButton
                    class="mt-2 mr-2"
                    type="button"
                    @click.prevent="selectNewCoverPhoto"
                >
                    {{ $t("Register.select_photo") }}
                </JetSecondaryButton>

                <JetInputError
                    :message="form.errors.cover_photo"
                    class="mt-2"
                />
            </div>
            <div
                v-if="$page.props.jetstream.managesProfilePhotos"
                class="col-span-6 sm:col-span-4"
            >
                <!-- Profile Photo File Input -->
                <input
                    class="hidden"
                    type="file"
                    ref="photoInput"
                    id="photoInput"
                    accept="image/*"
                    @change="updatePhotoPreview"
                />

                <JetLabel for="photoInput" :value="$t('Register.photo')" />

                <!-- Current Profile Photo -->
                <div v-show="!photoPreview" class="mt-2">
                    <img
                        :src="user.profile_photo_url"
                        :alt="user.name"
                        @click.prevent="selectNewPhoto"
                        class="object-cover w-20 h-20 rounded-full cursor-pointer no-magnify"
                    />
                </div>
                <!-- cover_photo_path -->

                <!-- New Profile Photo Preview -->
                <div v-show="photoPreview" class="mt-2">
                    <span
                        class="block w-20 h-20 bg-center bg-no-repeat bg-cover rounded-full cursor-pointer no-magnify"
                        @click.prevent="selectNewPhoto"
                        :style="
                            'background-image: url(\'' + photoPreview + '\');'
                        "
                    />
                </div>

                <JetSecondaryButton
                    class="mt-2 mr-2"
                    type="button"
                    @click.prevent="selectNewPhoto"
                >
                    {{ $t("Register.select_photo") }}
                </JetSecondaryButton>

                <JetSecondaryButton
                    v-if="user.profile_photo_path"
                    class="mt-2"
                    type="button"
                    @click.prevent="deletePhoto"
                >
                    {{ $t("Register.remove_photo") }}
                </JetSecondaryButton>

                <JetInputError :message="form.errors.photo" class="mt-2" />
            </div>

            <!-- Name -->
            <div class="col-span-6 sm:col-span-4">
                <FormKit
                    id="name"
                    v-model="form.name"
                    :label="$t('Register.Full_name')"
                    outer-class="mb-0"
                    placeholder="Enter your name"
                    type="text"
                    validation="required|length:2,100"
                />
                <JetInputError :message="form.errors.name" class="mt-2" />
            </div>

            <!-- Email -->
            <div class="col-span-6 sm:col-span-4">
                <FormKit
                    id="email"
                    v-model="form.email"
                    :label="$t('CurrentStatus.Email')"
                    outer-class="mb-0"
                    placeholder="Enter your email address"
                    type="email"
                    validation="required|email"
                />
                <JetInputError :message="form.errors.email" class="mt-2" />
            </div>

            <div
                class="col-span-6"
                v-if="
                    $page.props.jetstream.hasEmailVerification &&
                    user.email_verified_at === null
                "
            >
                <div
                    id="alert-4"
                    class="flex p-4 bg-[#fefce8] rounded-lg dark:bg-yellow-200"
                    role="alert"
                >
                    <svg
                        aria-hidden="true"
                        class="flex-shrink-0 w-5 h-5 text-[#ca8a04]"
                        fill="currentColor"
                        viewBox="0 0 20 20"
                        xmlns="http://www.w3.org/2000/svg"
                    >
                        <path
                            fill-rule="evenodd"
                            d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
                            clip-rule="evenodd"
                        ></path>
                    </svg>
                    <span class="sr-only">Info</span>
                    <div
                        v-if="!verificationLinkSent"
                        class="ml-3 text-sm font-medium text-[#ca8a04]"
                    >
                        Your email address is unverified. Click
                        <button
                            type="button"
                            @click="sendEmailVerification"
                            :disabled="resend.processing"
                            class="font-semibold underline disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            here
                        </button>
                        to re-send the verification email.
                    </div>
                    <div v-else class="ml-3 text-sm font-medium text-[#ca8a04]">
                        A new verification link has been sent to the email
                        address you provided during registration.
                    </div>
                </div>
            </div>

            <!-- Tagline -->
            <div class="col-span-6 sm:col-span-4">
                <FormKit
                    outer-class="mb-0"
                    id="tag_line"
                    v-model="form.tag_line"
                    type="text"
                    :label="$t('Register.postion')"
                    placeholder="Add your postion title and company"
                    validation="required|length:2,100"
                />
                <JetInputError :message="form.errors.tag_line" class="mt-2" />
            </div>
            <div class="flex items-center justify-between col-span-6">
                <p class="text-xs font-semibold">
                    {{ $t("Register.currency") }}
                </p>
                <currency-select />
            </div>
        </template>

        <template #actions="{ valid }">
            <JetActionMessage :on="form.recentlySuccessful" class="mr-3">
                {{ $t("Register.saved") }}
            </JetActionMessage>

            <JetButton type="submit" :disabled="!valid || form.processing">
                {{ $t("Register.save") }}
            </JetButton>
        </template>
    </JetFormSection>
</template>
