<script lang="ts" setup>
import { useFetch } from 'nuxt/app';

import useDialogue from '~/composables/useDialogue.ts';

const { $translator: translator } = useNuxtApp();
const dialogue = useDialogue();

type Block = {
    id: string;
    to_userId: string;
    to_username: string;
};

const blocks = useFetch<Block[]>(`/api/user/blocks`, { lazy: true });

const unblock = async (block: Block) => {
    await dialogue.confirm(translator.translate('profile.blocks.unblock.confirm', { username: block.to_username }), 'danger');
    await dialogue.postWithAlertOnError(`/api/user/unblock/${block.to_userId}`);
    await blocks.refresh();
};
</script>

<template>
    <Loading :value="blocks.data.value">
        <ul v-if="blocks.data.value">
            <li v-if="blocks.data.value.length === 0">
                <T>profile.blocks.empty</T>
            </li>
            <li v-for="block in blocks.data.value" :key="block.id">
                @{{ block.to_username }}
                <small class="text-muted">({{ $datetime($ulidTime(block.id)) }})</small>
                <a href="#" :aria-label="$t('profile.blocks.unblock.action')" class="btn btn-link btn-sm" @click.prevent="unblock(block)">
                    <Icon v="trash" />
                </a>
            </li>
        </ul>
        <p class="small mb-0">
            <Icon v="info-circle" /> <T>profile.blocks.instruction</T>
        </p>
    </Loading>
</template>
