<template>
    <div class="p-4 text-xs">
        <MaghaleSecondTitle title="ویرایش اطلاعات" />
        <div class="max-w-sm mx-auto" dir="rtl">

            <!-- title and abstract -->

            <div class="mt-4">
                <label for="first_name"
                    class="block mb-2 text-xs font-medium text-zinc-950 dark:text-white">نام</label>
                <input type="text" id="first_name" v-model="user.first_name" @change="update"
                    class="bg-zinc-50 border border-zinc-300 text-zinc-950 rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-1 dark:bg-zinc-700 dark:border-zinc-600 dark:placeholder-zinc-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
                    required />
            </div>

            <div class="mt-4">
                <label for="last_name" class="block mb-2 text-xs font-medium text-zinc-950 dark:text-white">نام
                    خانوادگی</label>
                <input type="text" id="last_name" v-model="user.last_name" @change="update"
                    class="bg-zinc-50 border border-zinc-300 text-zinc-950 rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-1 dark:bg-zinc-700 dark:border-zinc-600 dark:placeholder-zinc-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" />
            </div>

            <div class="mt-4">
                <label for="abstract" class="block mb-2 text-xs font-medium text-zinc-950 dark:text-white">شرح
                    مختصر</label>
                <input type="text" id="abstract" v-model="user.abstract" @change="update"
                    class="bg-zinc-50 border border-zinc-300 text-zinc-950 rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-1 dark:bg-zinc-700 dark:border-zinc-600 dark:placeholder-zinc-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" />
            </div>

            <div class="grid grid-cols-2 gap-2 mt-4">
                <div>
                    <label for="public_image" class="block mb-2 text-xs font-medium text-zinc-950 dark:text-white">عکس عمومی</label>
                    <img id="public_image" :src="useRuntimeConfig().public.MediaUrl + user.public_profile" class="rounded-full size-20" alt="">
                </div>
                <div>
                    <label for="private_image" class="block mb-2 text-xs font-medium text-zinc-950 dark:text-white">عکس خصوصی</label>
                    <img id="private_image" :src="useRuntimeConfig().public.MediaUrl + user.public_profile" class="rounded-full size-20" alt="">
                </div>
            </div>

            <!-- image upload -->
            <div class="mt-4">
                <label class="block mb-2 text-xs font-medium text-zinc-950 dark:text-white">انتخاب عکس</label>
                <input type="file" accept="image/*" @change="compressAndUpload"
                    class="block mb-2 p-1 w-full text-zinc-950 bg-zinc-50 rounded-lg border border-zinc-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-zinc-700 dark:border-zinc-600 dark:placeholder-zinc-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" />
            </div>

        </div>
    </div>
</template>

<script setup>
import axios from 'axios';
import { useMaghaleStore } from '~/store';
import Compressor from 'compressorjs';

const store = useMaghaleStore()
const { $CustomAlert } = useNuxtApp();
axios.defaults.headers.common['Authorization'] = store.token

const isLoadSendInformation = ref(false)
const image = ref(null);

// update
const user = ref({})
function update() {
    if (isLoadSendInformation.value) {
        return;
    }
    isLoadSendInformation.value = true
    axios
        .patch(`${useRuntimeConfig().public.BaseUrl}users/edit`, user.value)
        .then(() => {
            isLoadSendInformation.value = false
            $CustomAlert('با موفقیت ثبت شد', 4)
            store.setMyTitle(user.value.first_name + ' ' + user.value.last_name)
        })
}

function update_image() {
    const formData = new FormData();
    formData.append('image', image.value)
    formData.append('category', 0)
    axios.patch(useRuntimeConfig().public.BaseUrl + 'users/set_image', formData)
    .then((r) => {
        user.value.public_profile = r.data.image
        $CustomAlert('با موفقیت ثبت شد', 4)
        store.setMyImage(r.data.image)
    })
}

// image upload
const compressAndUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    // Get original file extension
    const originalName = file.name;
    const extension = originalName.split('.').pop().toLowerCase();

    try {
        // Compress the image
        const compressedBlob = await new Promise((resolve, reject) => {
            new Compressor(file, {
                quality: 0.6,
                maxWidth: 1024,
                maxHeight: 1024,
                success(result) {
                    resolve(result);
                },
                error(err) {
                    reject(err);
                },
            });
        });

        // Convert blob back to File with proper extension
        const compressedFile = new File([compressedBlob], `compressed.${extension}`, {
            type: compressedBlob.type,
            lastModified: Date.now()
        });

        // Verify file size
        if (compressedFile.size > 300000) {
            // Further compress if needed
            const furtherCompressed = await new Promise((resolve, reject) => {
                new Compressor(compressedFile, {
                    quality: 0.4,
                    maxWidth: 800,
                    maxHeight: 800,
                    success(result) {
                        resolve(result);
                    },
                    error(err) {
                        reject(err);
                    },
                });
            });
            const finalFile = new File([furtherCompressed], `compressed.${extension}`, {
                type: furtherCompressed.type,
                lastModified: Date.now()
            });

            image.value = finalFile
        } else {
            image.value = compressedFile
        }
        update_image()
    } catch (error) {
        console.error('Error:', error);
    }
};
</script>