<script lang="ts">
  import UserAvatar from '$lib/components/shared-components/user-avatar.svelte';
  import { handleAddUsersToAlbum } from '$lib/services/album.service';
  import { searchUsers, type AlbumResponseDto, type UserResponseDto } from '@immich/sdk';
  import { FormModal, ListButton, Stack, Text } from '@immich/ui';
  import { onMount } from 'svelte';
  import { t } from 'svelte-i18n';
  import { SvelteMap } from 'svelte/reactivity';

  type Props = {
    album: AlbumResponseDto;
    onClose: () => void;
  };

  const { album, onClose }: Props = $props();

  let users: UserResponseDto[] = $state([]);
  const excludedUserIds = $derived([album.ownerId, ...album.albumUsers.map(({ user: { id } }) => id)]);
  const filteredUsers = $derived(users.filter(({ id }) => !excludedUserIds.includes(id)));
  const selectedUsers = new SvelteMap<string, UserResponseDto>();

  const handleToggle = (user: UserResponseDto) => {
    if (selectedUsers.has(user.id)) {
      selectedUsers.delete(user.id);
    } else {
      selectedUsers.set(user.id, user);
    }
  };

  const onSubmit = async () => {
    const success = await handleAddUsersToAlbum(album, [...selectedUsers.values()]);
    if (success) {
      onClose();
    }
  };

  onMount(async () => {
    users = await searchUsers();
  });
</script>

<FormModal title={$t('users')} submitText={$t('add')} {onSubmit} disabled={selectedUsers.size === 0} {onClose}>
  <Stack>
    {#each filteredUsers as user (user.id)}
      <ListButton selected={selectedUsers.has(user.id)} onclick={() => handleToggle(user)}>
        <UserAvatar {user} size="md" />
        <div class="text-start grow">
          <Text>{user.name}</Text>
          <Text size="small">{user.email}</Text>
        </div>
      </ListButton>
    {:else}
      <Text>{$t('album_share_no_users')}</Text>
    {/each}
  </Stack>
</FormModal>
