<script>
    import Avatar from "../account/Avatar.svelte";
    import {fly} from "svelte/transition";
    import {createEventDispatcher} from "svelte";

    const dispatch = createEventDispatcher();
    export let member;
    export let roles;


    function removeFrom(e, aRole) {
        e.preventDefault();
        let newRoles = member.roles.filter((r) => r !== aRole);
        dispatch("update", {
            user: member.id,
            roles: newRoles,
        });
    }

    function addTo(e, aRole) {
        e.preventDefault();

        let newRoles = [...member.roles, aRole];
        console.log(member.roles)
        console.log(aRole)
        console.log(newRoles)
        dispatch("update", {
            user: member.id,
            roles: newRoles,
        });
    }


</script>

<div
        transition:fly={{ duration: 200 }}
        class="d-flex justify-content-between align-items-center mb-3 "
>
    <div class="d-flex align-items-center status-{member.roles.includes('removed')  ? 'removed' : 'active'}">
        <Avatar name={member.name ?? "" } side={32}/>
        <div class="ms-3 ">
            <div>
                <span class="fs-5">
                            {member.name}
                        </span>
            </div>
            {member.email}
        </div>
    </div>
    <div>
        <div class="dropdown dropdown-center">
            <button
                    class="  dropdown-toggle btn btn-light"
                    type="button"
                    data-bs-toggle="dropdown"
                    aria-expanded="false"
            >
                Roles
            </button>
            <div class="dropdown-menu">
                <h6 class="dropdown-header">Remove role</h6>
                {#each roles as role}
                    {#if member.roles.includes(role)}
                        <button
                                class="dropdown-item text-capitalize"
                                on:click={(e) => removeFrom(e,role)}
                        >
                            {role}
                        </button>
                    {/if}
                {/each}
                <div>
                    <hr class="dropdown-divider">
                </div>

                <h6 class="dropdown-header">Add role</h6>
                {#each roles as role}
                    {#if !member.roles.includes(role)}
                        <button
                                class="dropdown-item text-capitalize"
                                on:click={(e) => addTo(e,role)}
                        >
                            {role}
                        </button>
                    {/if}
                {/each}

            </div>
        </div>

    </div>
</div>
<style>
    .status-removed {
        opacity: .5;
    }


</style>
