<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 { currentLocation } from "@/composables/location";
import Mobile from "@/components/Inputs/Mobile";
import GeneralRadioGroup from "@/components/Inputs/Selects/Radios/GeneralRadioGroup.vue";
import CurrencySelect from "@/components/CurrencySelect";

const props = defineProps({
    engineer: Object,
    levelsOfExperience: Array,
});

const photoPreview = ref(null);

const coverPhotoPreview = ref(null);

const photoInput = ref(null);

const coverPhotoInput = ref(null);

const form = useForm({
    photo: null,
    cover_photo: null,
    email: props.engineer.email,
    name: props.engineer.name,
    tag_line: props.engineer.tag_line,
    about: props.engineer.about,
    location: props.engineer.location,
    phone: props.engineer.phone,
    level_of_experience_id: props.engineer.level_of_experience_id,
});

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

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

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;
    }
    if (coverPhotoInput.value?.value) {
        coverPhotoInput.value.value = null;
    }
};

const getCurrentLocation = async () => {
    currentLocation().then((location) => {
        form.location.address = location.address;
        form.location.lat = location.lat;
        form.location.lng = location.lng;
    });
};
</script>

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

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

        <template #form="{ valid }">
            <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="engineer.user.cover_photo_path"
                        :alt="engineer.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>
            <!-- Profile Photo -->

            <div class="col-span-6 sm:col-span-4">
                <!-- Profile Photo File Input -->
                <input
                    ref="photoInput"
                    id="photoInput"
                    accept="image/*"
                    type="file"
                    class="hidden"
                    @change="updatePhotoPreview"
                />

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

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

                <!-- 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 no-magnify"
                        :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="engineer.user.profile_photo_url"
                    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>

            <!-- Tagline -->
            <div class="col-span-6 sm:col-span-4">
                <FormKit
                    outer-class="mb-0"
                    id="tagline"
                    v-model="form.tag_line"
                    type="text"
                    :label="$t('Register.Profile_tagline')"
                    placeholder="Add your postion title and company"
                    validation="length:2,100"
                />
                <JetInputError :message="form.errors.tag_line" class="mt-2" />
            </div>

            <!-- About -->
            <div class="col-span-6">
                <FormKit
                    id="about"
                    v-model="form.about"
                    :classes="{ outer: 'mb-0' }"
                    :label="$t('profile.about')"
                    name="About"
                    placeholder="Let us know more about you ..."
                    required
                    rows="5"
                    type="textarea"
                    validation="required|length:2,3500"
                    validation-label="about"
                />
                <JetInputError :message="form.errors.about" class="mt-2" />
            </div>

            <!-- Location -->
            <div class="col-span-6">
                <FormKit
                    id="location"
                    v-model="form.location.address"
                    :classes="{
                        outer: 'mb-0',
                    }"
                    disabled
                    help="Your location helps us to let you contacted by clients near to you ..."
                    :label="$t('Register.your_location')"
                    name="location"
                    placeholder="Ex. Alazizyah, Dammam ..."
                    required
                    type="text"
                    validation="required"
                    validation-label="address"
                >
                    <template #suffix>
                        <button
                            class="p-0.5"
                            type="button"
                            @click="getCurrentLocation"
                        >
                            <svg
                                fill="none"
                                height="16"
                                viewBox="0 0 16 16"
                                width="16"
                                xmlns="http://www.w3.org/2000/svg"
                            >
                                <path
                                    d="M8 9.33337C9.10457 9.33337 10 8.43794 10 7.33337C10 6.2288 9.10457 5.33337 8 5.33337C6.89543 5.33337 6 6.2288 6 7.33337C6 8.43794 6.89543 9.33337 8 9.33337Z"
                                    stroke="#AAAAAA"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                />
                                <path
                                    d="M11.7714 11.1047L8.94275 13.9334C8.69274 14.1831 8.35381 14.3234 8.00042 14.3234C7.64703 14.3234 7.30809 14.1831 7.05808 13.9334L4.22875 11.1047C3.4829 10.3588 2.97497 9.40852 2.76921 8.37396C2.56344 7.3394 2.66908 6.26706 3.07275 5.29254C3.47643 4.31801 4.16002 3.48508 5.03707 2.89905C5.91413 2.31303 6.94526 2.00024 8.00008 2.00024C9.05491 2.00024 10.086 2.31303 10.9631 2.89905C11.8402 3.48508 12.5237 4.31801 12.9274 5.29254C13.3311 6.26706 13.4367 7.3394 13.231 8.37396C13.0252 9.40852 12.5173 10.3588 11.7714 11.1047V11.1047Z"
                                    stroke="#AAAAAA"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                />
                            </svg>
                        </button>
                    </template>
                </FormKit>
                <JetInputError :message="form.errors.location" class="mt-2" />
            </div>

            <!-- Phone -->
            <div class="col-span-6">
                <Mobile
                    v-model:phone="form.phone"
                    :label="$t('Register.phone')"
                />
                <JetInputError :message="form.errors.phone" class="mt-2" />
            </div>

            <!-- Experience -->
            <div class="col-span-6">
                <GeneralRadioGroup
                    v-model:selected="form.level_of_experience_id"
                    :items="levelsOfExperience"
                    :label="$t('Register.Level_experience')"
                    name="experience"
                />
                <JetInputError
                    :message="form.errors.level_of_experience_id"
                    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>
