<script lang="ts">
    import { followUser, unfollowUser } from '$lib/api/user';
    import * as ContextMenu from '$lib/components/ui/context-menu';
    import { followingUserCache } from '$lib/stores/cache';
    import type { User } from '$lib/types';
    import { UserMinus, UserPlus } from 'lucide-svelte';
    import * as AlertDialog from '$lib/components/ui/alert-dialog';

    export let user: User;

    let isFollowing = false;
    // followingUserCache.get(user_id).then((value) => (isFollowing = value || false));
    $: {
        followingUserCache.get(user.id).then((value) => (isFollowing = value || false));
    }

    followingUserCache.subscribeKey_autoDispose(user.id, 'update', (data) => {
        isFollowing = data || false;
    });

    function handleFollow() {
        if (isFollowing) {
            unfollowUser(user.id);
        } else {
            followUser(user.id);
        }
    }

    let unfollowDialogOpen = false;
</script>

<AlertDialog.Root bind:open={unfollowDialogOpen}>
    <AlertDialog.Trigger></AlertDialog.Trigger>
    <AlertDialog.Content>
        <AlertDialog.Header>
            <AlertDialog.Title>Are you absolutely sure?</AlertDialog.Title>
            <AlertDialog.Description>
                This action <strong>cannot</strong> be undone.
            </AlertDialog.Description>
        </AlertDialog.Header>
        <AlertDialog.Footer>
            <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
            <AlertDialog.Action on:click={() => unfollowUser(user.id)}>Continue</AlertDialog.Action>
        </AlertDialog.Footer>
    </AlertDialog.Content>
</AlertDialog.Root>

<ContextMenu.Root closeOnEscape={false}>
    <ContextMenu.Trigger>
        <slot />
    </ContextMenu.Trigger>
    <ContextMenu.Content>
        <ContextMenu.Label>
            <span class="font-bold">{user.username}</span>
        </ContextMenu.Label>
        {#if isFollowing}
            <ContextMenu.Item on:click={() => (unfollowDialogOpen = true)}>
                <UserMinus />
                <span class="ml-2">Unfollow</span>
            </ContextMenu.Item>
        {:else}
            <ContextMenu.Item on:click={() => followUser(user.id)}>
                <UserPlus />
                <span class="ml-2">Follow</span>
            </ContextMenu.Item>
        {/if}
    </ContextMenu.Content>
</ContextMenu.Root>
