<script setup lang="ts">
import { BAlert, BCard, BLink } from "bootstrap-vue";
import { computed, onMounted, ref, watchEffect } from "vue";

import localize from "@/utils/localization";
import { wait } from "@/utils/utils";

import type { CleanableSummary, CleanupOperation } from "./model";

import LoadingSpan from "@/components/LoadingSpan.vue";

interface CleanupOperationSummaryProps {
    operation: CleanupOperation;
    refreshOperationId?: string;
    refreshDelay?: number;
}

const props = withDefaults(defineProps<CleanupOperationSummaryProps>(), {
    refreshOperationId: undefined,
    refreshDelay: 500,
});

const summary = ref<CleanableSummary>();
const loading = ref(true);
const errorMessage = ref<string>();

const canClearItems = computed(() => {
    return (summary.value?.totalItems ?? 0) > 0;
});

const emit = defineEmits<{
    (e: "onReviewItems", operation: CleanupOperation, totalItems: number): void;
}>();

onMounted(async () => {
    await refresh();
});

watchEffect(async () => {
    if (props.operation.id === props.refreshOperationId) {
        await refresh();
    }
});

async function refresh() {
    loading.value = true;
    try {
        const start = Date.now();
        summary.value = await props.operation.fetchSummary();
        const duration = Date.now() - start;
        await wait(props.refreshDelay - duration);
    } catch (error) {
        onError(String(error));
    } finally {
        loading.value = false;
    }
}

function onError(message: string) {
    errorMessage.value = message;
}

function onReviewItems() {
    emit("onReviewItems", props.operation, summary.value?.totalItems ?? 0);
}
</script>

<template>
    <BCard class="d-flex flex-column">
        <h5 class="mb-2">{{ props.operation.name }}</h5>
        <p class="text-muted small flex-grow-1">{{ operation.description }}</p>
        <div>
            <LoadingSpan v-if="loading" />
            <BAlert v-else-if="errorMessage" variant="danger" show data-test-id="error-alert">
                {{ errorMessage }}
            </BAlert>
            <BLink v-else-if="summary && canClearItems" href="#" data-test-id="review-link" @click="onReviewItems">
                <b>{{ localize("Review and clear") }} {{ summary.niceTotalSize }}</b>
            </BLink>
            <b v-else class="text-secondary" data-test-id="no-items-indicator">
                {{ localize("No items to clear") }}
            </b>
        </div>
    </BCard>
</template>
