<script setup>
    import AuthenticatedLayout from '@/layouts/AuthenticatedLayout.vue';
    import Modal from '@/Components/Modal.vue';
    import SecondaryButton from '@/Components/SecondaryButton.vue';
    import DangerButton from '@/Components/DangerButton.vue';

    import { Head, usePage, useForm, Link, router } from '@inertiajs/vue3';
    import { computed, onMounted, ref } from 'vue';
    import { initFlowbite } from 'flowbite';

    onMounted(() => {
        initFlowbite();
    });

    const page = usePage();
    const userRoles = computed(() => page.props.userRoles);
    const userPermissions = computed(() => page.props.userPermissions);

    const {
        builtPages,
    } = defineProps({
        builtPages: {
            type: Object,
            required: true
        }
    });

    // Check user permissions from Laravel

    const hasPermission = (permissionName) => {
        return userPermissions.value.some(userPermissions => userPermissions.name === permissionName);
    };

    // Get thumbnail picture from the content property

    const getThumbs = (lPage) => {
        try {
            const blocks = typeof lPage.content === 'string'
                ? JSON.parse(lPage.content)
                : lPage.content;

            return blocks
                .filter(block => block.thumbUrl)
                .map(block => block.thumbUrl);
        } catch (e) {
            console.warn('Invalid JSON in page content:', e);
            return [];
        }
    };

    // Confirm deletion modal

    const deleteModal = ref(false);

    const deleteForm = useForm({
        id: null
    });

    const openDeleteModal = (lPage) => {
        deleteForm.id = lPage.id;
        deleteModal.value = true;
    };

    const closeDeleteModal = () => {
        deleteForm.reset();
        deleteModal.value = false;
    };

    const deletePage = () => {
        deleteForm.delete(route('page-builder.landing-page.delete'), {
            preserveScroll: true,
            onSuccess: () => closeDeleteModal(),
        });
    };

</script>

<template>
    <Modal :show="deleteModal" @close="closeDeleteModal()">
        <div class="p-6 bg-white dark:bg-gray-800 rounded-md">
            <h2 class="text-lg font-medium text-gray-900 dark:text-gray-400">
                Bekreft sletting av side
            </h2>

            <p class="mt-1 text-sm text-gray-600 dark:text-gray-200">
                Denne operasjonen er permanent og kan ikke angres. All data
                knyttet til siden vil bli slettet. Hvis siden er satt som
                hovedsiden, vil alle besøkende bli redirigert til brukersiden
                (hvis brukeren er innlogget), eller innloggingsiden hvis
                den besøkende ikke er autentisert, inntill du setter en ny
                forside.
            </p>

            <div class="mt-6 flex justify-end">
                <SecondaryButton @click="closeDeleteModal()"> Avbryt </SecondaryButton>

                <DangerButton
                    class="ml-3"
                    :class="{ 'opacity-25': deleteForm.processing }"
                    :disabled="deleteForm.processing"
                    @click="deletePage"
                >
                    Slett side
                </DangerButton>
            </div>
        </div>
    </Modal>

    <Head title="Sidebygger" />

    <AuthenticatedLayout>
        <template #header>
            <div class="flex justify-between items-center">
                <div>
                    <h2 class="font-semibold text-xl text-gray-800 leading-tight dark:text-gray-400">Administrering av sider</h2>
                    <h4 class="text-sm mt-2 text-gray-800 leading-tight dark:text-gray-400">Her kan du opprette en ny, eller administrere eksisterende sider</h4>
                </div>
                <Link :href="route('page-builder.landing-page.create')" v-if="hasPermission('create-article')" class="relative inline-flex items-center justify-center p-0.5 mb-2 mr-2 overflow-hidden text-sm font-medium text-gray-900 rounded-lg group bg-gradient-to-br from-cyan-500 to-blue-500 group-hover:from-cyan-500 group-hover:to-blue-500 hover:text-white dark:text-white focus:ring-4 focus:outline-none focus:ring-cyan-200 dark:focus:ring-cyan-800">
                    <span class="flex items-center relative px-5 py-2.5 transition-all ease-in duration-75 bg-white dark:bg-gray-700 rounded-md group-hover:bg-opacity-0">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 -960 960 960" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 mr-2">
                            <path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h440l200 200v440q0 33-23.5 56.5T760-120H200Zm0-80h560v-400H600v-160H200v560Zm80-80h400v-80H280v80Zm0-320h200v-80H280v80Zm0 160h400v-80H280v80Zm-80-320v160-160 560-560Z" />
                        </svg>
                        Ny side
                    </span>
                </Link>
            </div>
        </template>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-4">
            <div
                v-for="page in builtPages"
                :key="page.id"
                class="flex flex-col items-center bg-white border border-gray-200 rounded-lg shadow-sm md:flex-row md:max-w-xl dark:border-gray-700 dark:bg-gray-800"
            >
                <div class="flex flex-col md:w-48 w-full rounded-t-lg md:rounded-none md:rounded-s-lg overflow-hidden">
                    <img
                        v-for="(thumb, index) in getThumbs(page)"
                        :key="index"
                        :src="thumb"
                        alt="Forhåndsvisning"
                        class="object-cover w-full h-24 md:h-24 border-b dark:border-gray-700"
                    />
                </div>

                <div class="flex flex-col justify-between p-4 leading-normal h-full w-full">
                    <div>
                        <h3 class="mb-2 text-xl font-semibold tracking-tight text-gray-900 dark:text-white">{{ page.title }}</h3>
                        <p class="mb-3 font-normal text-gray-700 dark:text-gray-400">Av: {{ page.author.name }} — Revisjoner: {{ page.revisions_count }}</p>
                    </div>

                    <div class="flex justify-end gap-2 mt-4">
                        <Link
                            v-if="page.activeRevision"
                            :href="route('page-builder.builder.edit', page.activeRevision.uuid)"
                            class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
                        >
                            Rediger
                        </Link>
                        <button
                            @click="openDeleteModal(page)"
                            class="text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900"
                        >
                            Slett
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>
