<template>
    <div><FirstTitle title="ویرایش رشته" />
        <div>
            <label for="title" class="block mt-6 text-sm font-medium text-zinc-900 dark:text-white">عنوان</label>
            <input type="text" id="title" v-model="fieldData.activity.title" @change="update_activity"
                class="mt-2 bg-zinc-50 border border-zinc-300 text-zinc-900 text-sm 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"
                required />
        </div>
        <div>
            <label for="abstract" class="block mt-4 text-sm font-medium text-zinc-900 dark:text-white">
                خلاصه</label>
            <textarea type="text" id="abstract" v-model="fieldData.activity.abstract" @change="update_activity"
                class="mt-2 bg-zinc-50 border border-zinc-300 text-zinc-900 text-sm 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"></textarea>
        </div>

        <!-- images -->
        <div class="mt-4 grid gap-2 grid-cols-4 text-zinc-800 dark:text-white">
            <div v-for="image in fieldData.activity.images" :key="image.id" class="text-center">
                <img :src="useRuntimeConfig().public.MediaUrl + image.image" class="size-20 rounded-lg mx-auto">
                <!-- remove button -->
                <button type="button" @click="remove(image.id)" class="w-20 mt-1 rounded-lg bg-zinc-300">
                    <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>

        <!-- image upload -->
        <div class="mt-4">
            <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>
    </div>
</template>

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

const { $CustomAlert } = useNuxtApp();
const store = useMaghaleStore()
const id = useRoute().params.id

const fieldData = reactive({ data: { field: 0, }, activity: {} })

// init
get_field()

// get field
async function get_field() {
    axios.defaults.headers.common.Authorization = store.token
    await axios.get(useRuntimeConfig().public.BaseUrl + 'fields/get_edit/' + id)
        .then((r) => {
            fieldData.activity = r.data.activity
            fieldData.data = r.data
            delete fieldData.data.activity
        })
}

// async function update() {
//     await axios
//         .patch(`${useRuntimeConfig().public.BaseUrl}fields/fields/${id}/`, fieldData.data)
//         .then(() => { $CustomAlert('تغییرات ثبت شد', 4) })
// }

async function update_activity() {
    await axios
        .patch(`${useRuntimeConfig().public.BaseUrl}activities/activities/${fieldData.activity.id}/`, fieldData.activity)
        .then(() => { $CustomAlert('تغییرات ثبت شد', 4) })
}

async function submit() {
    const formData = new FormData();
    formData.append('image', image.value);
    formData.append('activity', fieldData.activity.id);
    axios.post(useRuntimeConfig().public.BaseUrl + 'activities/images/', formData)
        .then((r) => {
            r.data.image = r.data.image.split('8010')[1]
            fieldData.activity.images.push(r.data)
        })
}

function remove(pk) {
    if (confirm('آیا از حذف عکس اطمینان دارید؟')) {
        axios
            .delete(`${useRuntimeConfig().public.BaseUrl}activities/images/${pk}/`)
            .then(() => {
                fieldData.activity.images = fieldData.activity.images.filter(x => x.id !== pk)
            })
            .catch((e) => { console.log(e) })
    }
}

// upload image
import Compressor from 'compressorjs';
const image = ref(null);
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
        }
        submit()
    } catch (error) {
        console.error('Error:', error);
    }
};

</script>