<template>
    <SMPage permission="admin/media">
        <SMMastHead
            title="Media"
            :back-link="{ name: 'dashboard' }"
            back-title="Return to Dashboard" />
        <SMContainer class="flex-grow-1">
            <SMToolbar>
                <SMButton
                    :to="{ name: 'dashboard-media-create' }"
                    type="primary"
                    label="Upload Media" />
                <SMInput
                    v-model="itemSearch"
                    label="Search"
                    class="toolbar-search"
                    @keyup.enter="handleSearch">
                    <template #append>
                        <SMButton
                            type="primary"
                            label="Search"
                            icon="search-outline"
                            @click="handleSearch" />
                    </template>
                </SMInput>
            </SMToolbar>
            <SMLoading large v-if="itemsLoading" />
            <template v-else>
                <SMPagination
                    v-if="items.length < itemsTotal"
                    v-model="itemsPage"
                    :total="itemsTotal"
                    :per-page="itemsPerPage" />
                <SMNoItems v-if="items.length == 0" text="No Media Found" />
                <SMTable
                    v-else
                    :headers="headers"
                    :items="items"
                    @row-click="handleSelect">
                    <template #item-select="item">
                        <SMInput
                            type="checkbox"
                            v-model="itemsSelected[item.id]"
                            @click.stop />
                    </template>
                    <template #item-size="item">
                        {{ bytesReadable(item.size) }}
                    </template>
                    <template #item-title="item"
                        >{{ item.title }}<br /><span class="small"
                            >({{ item.name }})</span
                        ></template
                    >
                    <template #item-actions="item">
                        <SMButton
                            label="Edit"
                            :dropdown="{
                                download: 'Download',
                                delete: 'Delete',
                            }"
                            size="medium"
                            @click="
                                handleActionButton(item, $event)
                            "></SMButton>
                    </template>
                </SMTable>
                <SMToolbar class="align-items-center">
                    <div>
                        <SMButton
                            type="danger"
                            label="Delete Selected"
                            :disabled="computedSelectedCount == 0"
                            @click="handleDeleteSelected" />
                        <SMButton
                            type="primary"
                            label="Edit Selected"
                            :disabled="computedSelectedCount == 0"
                            @click="handleEditSelected" />
                    </div>
                    <div>{{ computedSelectedCount }} selected</div>
                </SMToolbar>
            </template>
        </SMContainer>
    </SMPage>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { openDialog } from "../../components/SMDialog";
import SMDialogConfirm from "../../components/dialogs/SMDialogConfirm.vue";
import SMButton from "../../components/SMButton.vue";
import SMToolbar from "../../components/SMToolbar.vue";
import { api } from "../../helpers/api";
import { Media, MediaCollection } from "../../helpers/api.types";
import { SMDate } from "../../helpers/datetime";
import { bytesReadable } from "../../helpers/types";
import { useToastStore } from "../../store/ToastStore";
import SMInput from "../../components/SMInput.vue";
import SMMastHead from "../../components/SMMastHead.vue";
import SMTable from "../../components/SMTable.vue";
import SMPagination from "../../components/SMPagination.vue";
import SMNoItems from "../../components/SMNoItems.vue";
import SMLoading from "../../components/SMLoading.vue";
import { updateRouterParams } from "../../helpers/url";

const route = useRoute();
const router = useRouter();
const toastStore = useToastStore();

const items = ref([]);
const itemsLoading = ref(true);
const itemSearch = ref((route.query.search as string) || "");
const itemsTotal = ref(0);
const itemsPerPage = 25;
const itemsPage = ref(parseInt((route.query.page as string) || "1"));
const itemsSelected = ref({});

const headers = [
    { text: "", value: "select", sortable: false },
    { text: "Title (Name)", value: "title", sortable: true },
    { text: "Size", value: "size", sortable: true },
    { text: "Uploaded By", value: "user.display_name", sortable: true },
    { text: "Actions", value: "actions" },
];

/**
 * Watch if page number changes.
 */
watch(itemsPage, () => {
    handleLoad();
});

/**
 * Handle searching for item.
 */
const handleSearch = () => {
    itemsPage.value = 1;
    handleLoad();
};

/**
 * Handle user selecting option in action button.
 *
 * @param {Media} item The media item.
 * @param {string} extra The option selected.
 * @param option
 */
const handleActionButton = (item: Media, option: string): void => {
    if (option.length == 0) {
        handleEdit(item);
    } else if (option.toLowerCase() == "download") {
        handleDownload(item);
    } else if (option.toLowerCase() == "delete") {
        handleDelete(item);
    }
};

/**
 * Handle loading the page and list
 */
const handleLoad = async () => {
    itemsLoading.value = true;
    items.value = [];
    itemsTotal.value = 0;

    updateRouterParams(router, {
        search: itemSearch.value,
        page: itemsPage.value == 1 ? "" : itemsPage.value.toString(),
    });

    try {
        let params = {
            page: itemsPage.value,
            limit: itemsPerPage,
        };

        if (itemSearch.value.length > 0) {
            params[
                "filter"
            ] = `title:${itemSearch.value},OR,name:${itemSearch.value},OR,description:${itemSearch.value}`;
        }

        let result = await api.get({
            url: "/media",
            params: params,
        });

        const data = result.data as MediaCollection;
        data.media.forEach(async (row) => {
            if (row.created_at !== "undefined") {
                row.created_at = new SMDate(row.created_at, {
                    format: "ymd",
                    utc: true,
                }).relative();
            }
            if (row.updated_at !== "undefined") {
                row.updated_at = new SMDate(row.updated_at, {
                    format: "ymd",
                    utc: true,
                }).relative();
            }

            if (
                Object.prototype.hasOwnProperty.call(
                    itemsSelected.value,
                    row.id
                ) == false
            ) {
                itemsSelected.value[row.id] = false;
            }

            items.value.push(row);
        });

        itemsTotal.value = data.total;
    } catch (error) {
        if (error.status != 404) {
            toastStore.addToast({
                title: "Server Error",
                content:
                    "An error occurred retrieving the list from the server.",
                type: "danger",
            });
        }
    } finally {
        itemsLoading.value = false;
    }
};

const handleSelect = (item: Media) => {
    if (Object.prototype.hasOwnProperty.call(itemsSelected.value, item.id)) {
        itemsSelected.value[item.id] = !itemsSelected.value[item.id];
    } else {
        itemsSelected.value[item.id] = true;
    }
};

/**
 * User requests to edit the item
 *
 * @param {Media} item The media item.
 */
const handleEdit = (item: Media) => {
    router.push({
        name: "dashboard-media-edit",
        params: { id: item.id },
        query: {
            return: encodeURIComponent(
                window.location.pathname + window.location.search
            ),
        },
    });
};

/**
 * Request to delete a media item from the server.
 *
 * @param {Media} item The media object to delete.
 */
const handleDelete = async (item: Media) => {
    let result = await openDialog(SMDialogConfirm, {
        title: "Delete File?",
        text: `Are you sure you want to delete the file <strong>${item.title}</strong>?`,
        cancel: {
            type: "secondary",
            label: "Cancel",
        },
        confirm: {
            type: "danger",
            label: "Delete File",
        },
    });

    if (result == true) {
        try {
            await api.delete({
                url: "/media/{id}",
                params: {
                    id: item.id,
                },
            });

            toastStore.addToast({
                title: "File Deleted",
                content: `The file ${item.title} has been deleted.`,
                type: "success",
            });
            handleLoad();
        } catch (error) {
            toastStore.addToast({
                title: "Error Deleting File",
                content:
                    error.data?.message ||
                    "An unexpected server error occurred",
                type: "danger",
            });
        }
    }
};

/**
 * Request to delete selected media item from the server.
 */
const handleDeleteSelected = async () => {
    let result = await openDialog(SMDialogConfirm, {
        title: "Delete Files?",
        text: `Are you sure you want to delete the <strong>${computedSelectedCount.value}</strong> selected files?`,
        cancel: {
            type: "secondary",
            label: "Cancel",
        },
        confirm: {
            type: "danger",
            label: "Delete File",
        },
    });

    if (result == true) {
        let errorCount = 0;
        let successCount = 0;

        const deleteItems = Object.entries(itemsSelected.value).filter(
            ([key, value]) => value === true
        );

        await Promise.all(
            deleteItems.map(async ([key, value]) => {
                // Perform actions for each item that is true
                console.log(key, value);

                // Perform asynchronous operation
                try {
                    await api.delete({
                        url: "/media/{id}",
                        params: {
                            id: key,
                        },
                    });

                    successCount++;
                } catch (error) {
                    errorCount++;
                }
            })
        );

        if (errorCount === 0) {
            toastStore.addToast({
                title: "Files Deleted",
                content: `The selected files have been deleted.`,
                type: "success",
            });
        } else if (successCount === 0) {
            toastStore.addToast({
                title: "Error Deleting Files",
                content: "An unexpected server error occurred.",
                type: "danger",
            });
        } else {
            toastStore.addToast({
                title: "Some Files Deleted",
                content: `Only ${successCount} files where deleted. ${errorCount} could not because of an unexpected error.`,
                type: "warning",
            });
        }

        handleLoad();
    }
};

/**
 * Request to edit selected media item from the server.
 */
const handleEditSelected = async () => {
    const editItems = Object.entries(itemsSelected.value)
        .filter(([key, value]) => value === true)
        .map(([key, value]) => key)
        .join(",");

    router.push({
        name: "dashboard-media-edit",
        params: { id: editItems },
        query: {
            return: encodeURIComponent(
                window.location.pathname + window.location.search
            ),
        },
    });
};

/**
 * Handle the user requesting to download the item.
 *
 * @param {Media} item The media item.
 */
const handleDownload = (item: Media) => {
    window.open(`${item.url}?download=1`, "_blank");
};

const computedSelectedCount = computed(() => {
    const selectedValues = Object.values(itemsSelected.value);
    const trueValues = selectedValues.filter((value) => value === true);
    return trueValues.length;
});

handleLoad();
</script>

<style lang="scss">
.page-dashboard-media-list {
    .toolbar-search {
        max-width: 350px;
    }

    .table tr {
        td:first-of-type,
        td:nth-of-type(2) {
            word-break: break-all;
        }

        td:not(:first-of-type) {
            white-space: nowrap;
        }
    }
}

@media only screen and (max-width: 768px) {
    .page-dashboard-media-list {
        .toolbar-search {
            max-width: none;
        }
    }
}
</style>
