<template>
    <div class="">
        <MaghaleSecondTitle title="تعریف نویسنده" />
        <form @submit.prevent="submit" class="max-w-sm mx-auto" dir="rtl">
            <!-- activity -->
            <div>
                <!-- title -->
                <div class="mt-4">
                    <label for="title" class="block mb-2 font-medium text-zinc-900 dark:text-white">عنوان</label>
                    <input v-model="activity.title" type="text" id="title"
                        class="shadow-sm bg-zinc-50 border border-zinc-300 text-zinc-900 rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 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 dark:shadow-sm-light"
                        required />
                </div>
                <!-- abstract -->
                <div class="mt-4">
                    <label for="message" class="block mb-2 text-sm font-medium text-zinc-900 dark:text-white">
                        توضیحات مختصر
                    </label>
                    <textarea v-model="activity.abstract" id="message" rows="4"
                        class="block mb-2 p-2.5 w-full text-sm text-zinc-900 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"
                        placeholder=""></textarea>
                </div>
                <!-- image -->
                <div v-if="imagePreview" class="flex flex-col space-y-1 mt-4">
                    <img :src="imagePreview" alt="Preview" class="rounded-lg size-20 mx-auto">
                    <button type="button" @click="remove(image.id)" class="w-20 rounded-lg bg-yellow-300 mx-auto">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                            stroke="currentColor" class="size-6 mx-auto p-0.5">
                            <path stroke-linecap="round" stroke-linejoin="round"
                                d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
                        </svg>
                    </button>
                </div>
                <div class="">
                    <label class="block mb-2 text-sm font-medium text-zinc-900 dark:text-white">انتخاب عکس</label>
                    <input type="file" accept="image/*" @change="compressAndUpload"
                        class="block mb-2 p-2.5 w-full text-sm text-zinc-900 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>
            <!-- submit -->
            <div class="flex mt-4">
                <button type="submit"
                    class="text-white ml-2 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg px-3 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">ثبت
                    و برگشت </button>

                <button type="button" @click="edit = 1 && submit()"
                    class="text-white ml-2 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg px-3 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">ثبت
                    و تکمیل</button>
                <button type="button" @click="edit = 2 && submit()"
                    class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg px-3 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">ثبت
                    و افزودن بعدی
                </button>
            </div>
        </form>
    </div>
</template>

<script setup>
import axios from 'axios';
import { useMaghaleStore } from '~/store'
const { $CustomAlert } = useNuxtApp();
const store = useMaghaleStore()
const router = useRouter()
// submit
const form = reactive({
})
const activity = reactive({
    title: '',
    abstract: '',
})
const edit = ref(0)
async function submit() {
    await axios
        .post(useRuntimeConfig().public.BaseUrl + 'maghale/activities/', activity)
        .then((r) => {
            if (image.value) {
                const formData = new FormData();
                formData.append('image', image.value);
                formData.append('activity', r.data.id);
                axios.post(useRuntimeConfig().public.BaseUrl + 'maghale/images/', formData)
            }
            form.activity = r.data.id
            axios.post(useRuntimeConfig().public.BaseUrl + 'authors/authors/', form)
                .then((rr) => {
                    store.setAuthorId(rr.data.id)
                    if (edit.value == 1) {
                        router.push(useRuntimeConfig().public.router.AuthorEdit + rr.data.id)
                    } else if (edit.value == 2) {
                        $CustomAlert('ثبت شد', 4)
                    } else {
                        router.go(-1)
                    }
                })
        })
}
// upload image
import Compressor from 'compressorjs';
const image = ref(null);
const imagePreview = ref(null);
function remove() {
    imagePreview.value = null
    image.value = null
}
const compressAndUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;
    if (file && file.type.match('image.*')) {
        const reader = new FileReader();
        reader.onload = (e) => {
            imagePreview.value = e.target.result;
        };
        reader.readAsDataURL(file);
    }

    // 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
        }
    } catch (error) {
        console.error('Error:', error);
    }
};
</script>