<script lang="ts">
  import {sortBy} from "@welshman/lib"
  import {ManagementMethod} from "@welshman/util"
  import {manageRelay, displayProfileByPubkey} from "@welshman/app"
  import MenuDots from "@assets/icons/menu-dots.svg?dataurl"
  import UserMinus from "@assets/icons/user-minus.svg?dataurl"
  import MinusCircle from "@assets/icons/minus-circle.svg?dataurl"
  import AddCircle from "@assets/icons/add-circle.svg?dataurl"
  import AltArrowLeft from "@assets/icons/alt-arrow-left.svg?dataurl"
  import {fly} from "@lib/transition"
  import Button from "@lib/components/Button.svelte"
  import Icon from "@lib/components/Icon.svelte"
  import Popover from "@lib/components/Popover.svelte"
  import Confirm from "@lib/components/Confirm.svelte"
  import Modal from "@lib/components/Modal.svelte"
  import ModalBody from "@lib/components/ModalBody.svelte"
  import ModalHeader from "@lib/components/ModalHeader.svelte"
  import ModalTitle from "@lib/components/ModalTitle.svelte"
  import ModalSubtitle from "@lib/components/ModalSubtitle.svelte"
  import ModalFooter from "@lib/components/ModalFooter.svelte"
  import RoleBadge from "@app/components/RoleBadge.svelte"
  import RelayName from "@app/components/RelayName.svelte"
  import Profile from "@app/components/Profile.svelte"
  import SpaceMembersAdd from "@app/components/SpaceMembersAdd.svelte"
  import SpaceMembersBanned from "@app/components/SpaceMembersBanned.svelte"
  import type {RoomMember} from "@app/core/roles"
  import {
    deriveSpaceMembers,
    deriveSpaceBannedPubkeyItems,
    deriveSupportedMethods,
  } from "@app/core/state"
  import {
    deriveSpaceMemberRoleInfo,
    deriveUserHasSpacePermission,
    ROOM_PERMISSION_ADD_MEMBER,
    ROOM_PERMISSION_REMOVE_MEMBER,
    ROOM_PERMISSION_BAN_USER,
  } from "@app/core/roles"
  import {pushModal} from "@app/util/modal"
  import {pushToast} from "@app/util/toast"

  interface Props {
    url: string
  }

  const {url}: Props = $props()

  const members = deriveSpaceMembers(url)
  const bans = deriveSpaceBannedPubkeyItems(url)
  const spaceMemberRoles = deriveSpaceMemberRoleInfo(url)
  const canAddMember = deriveUserHasSpacePermission(url, ROOM_PERMISSION_ADD_MEMBER)
  const canBanByPermission = deriveUserHasSpacePermission(url, ROOM_PERMISSION_BAN_USER)
  const canUnallowByPermission = deriveUserHasSpacePermission(url, ROOM_PERMISSION_REMOVE_MEMBER)
  const supportedMethods = deriveSupportedMethods(url)
  const canBan = $derived(
    $canBanByPermission && $supportedMethods.includes(ManagementMethod.BanPubkey),
  )
  const canUnallow = $derived(
    $canUnallowByPermission && $supportedMethods.includes(ManagementMethod.UnallowPubkey),
  )

  type SpaceMemberWithRoles = RoomMember & {
    roleDefinitions: Array<{name: string; label?: string; color?: number; order?: number}>
    primaryRole?: {name: string; label?: string; color?: number}
    sortKey: number
  }

  const memberGroups = $derived.by(() => {
    const byRole = new Map<
      string,
      {
        key: string
        label: string
        color?: number
        order?: number
        members: SpaceMemberWithRoles[]
      }
    >()
    const defaultGroup = {
      key: "members",
      label: "Members",
      members: [] as SpaceMemberWithRoles[],
    }

    for (const pubkey of $members) {
      const roleInfo = $spaceMemberRoles.get(pubkey)
      const member = {
        pubkey,
        roles: roleInfo?.roles.map(role => role.name) || [],
        roleDefinitions: roleInfo?.roles || [],
        primaryRole: roleInfo?.primaryRole,
        sortKey: roleInfo?.sortKey ?? -Infinity,
      }

      if (!member.primaryRole) {
        defaultGroup.members.push(member)
        continue
      }

      const roleName = member.primaryRole.name

      if (!byRole.has(roleName)) {
        byRole.set(roleName, {
          key: roleName,
          label: member.primaryRole.label || roleName,
          color: member.primaryRole.color,
          order: member.sortKey,
          members: [],
        })
      }

      byRole.get(roleName)!.members.push(member)
    }

    const groups = sortBy(group => -(group.order ?? -Infinity), Array.from(byRole.values()))

    for (const group of groups) {
      group.members = sortBy(member => -member.sortKey, group.members)
    }

    if (defaultGroup.members.length > 0) {
      groups.push(defaultGroup)
    }

    return groups
  })

  const back = () => history.back()

  const toggleMenu = (pubkey: string) => {
    menuPubkey = menuPubkey === pubkey ? undefined : pubkey
  }

  const closeMenu = () => {
    menuPubkey = undefined
  }

  const showBannedPubkeyItems = () => pushModal(SpaceMembersBanned, {url})

  const addMember = () => pushModal(SpaceMembersAdd, {url})

  const unallowMember = (pubkey: string) =>
    pushModal(Confirm, {
      title: "Remove User",
      message: `Are you sure you want to remove @${displayProfileByPubkey(pubkey)} from the space?`,
      confirm: async () => {
        const {error} = await manageRelay(url, {
          method: ManagementMethod.UnallowPubkey,
          params: [pubkey],
        })

        if (error) {
          pushToast({theme: "error", message: error})
        } else {
          pushToast({message: "User has successfully been removed!"})
          back()
        }
      },
    })

  const banMember = (pubkey: string) =>
    pushModal(Confirm, {
      title: "Ban User",
      message: `Are you sure you want to ban @${displayProfileByPubkey(pubkey)} from the space?`,
      confirm: async () => {
        const {error} = await manageRelay(url, {
          method: ManagementMethod.BanPubkey,
          params: [pubkey],
        })

        if (error) {
          pushToast({theme: "error", message: error})
        } else {
          pushToast({message: "User has successfully been banned!"})
          back()
        }
      },
    })

  let menuPubkey = $state<string | undefined>()
</script>

<Modal>
  <ModalBody>
    <ModalHeader>
      <ModalTitle>Members</ModalTitle>
      <ModalSubtitle>of <RelayName {url} class="text-primary" /></ModalSubtitle>
    </ModalHeader>
    {#if canBan || canUnallow}
      {#if $bans.length > 0}
        <Button class="btn btn-neutral" onclick={showBannedPubkeyItems}>
          Banned users ({$bans.length})
        </Button>
      {/if}
    {/if}
    <div class="flex flex-col gap-2">
      {#if $members === undefined}
        <div class="card2 bg-base-200 p-4">
          <span class="text-error">Member list not available from this space</span>
        </div>
      {:else if $members.length === 0}
        <div class="card2 bg-base-200 p-4">
          <span class="text-base-content/70">No members yet</span>
        </div>
      {:else}
        {#each memberGroups as group (group.key)}
          <div class="pt-2 pb-1">
            {#if group.color !== undefined}
              <RoleBadge
                role={group.key}
                label={group.label}
                color={group.color}
                class="badge-md" />
            {:else}
              <span class="text-sm font-semibold opacity-75">{group.label}</span>
            {/if}
          </div>
          {#each group.members as member (member.pubkey)}
            <div class="card2 card2-sm bg-alt relative">
              <div class="flex items-center justify-between gap-2">
                <div class="min-w-0 flex-1">
                  <Profile pubkey={member.pubkey} {url} />
                  {#if member.roleDefinitions.length > 0}
                    <div class="mt-1 flex flex-wrap gap-1">
                      {#each member.roleDefinitions as role (role.name)}
                        <RoleBadge role={role.name} label={role.label} color={role.color} />
                      {/each}
                    </div>
                  {/if}
                </div>
                {#if canBan || canUnallow}
                  <div class="relative">
                    <Button
                      class="btn btn-circle btn-ghost btn-sm"
                      onclick={() => toggleMenu(member.pubkey)}>
                      <Icon icon={MenuDots} />
                    </Button>
                    {#if menuPubkey === member.pubkey}
                      <Popover hideOnClick onClose={closeMenu}>
                        <ul
                          transition:fly
                          class="menu absolute right-0 z-popover mt-2 w-48 gap-1 rounded-box bg-base-100 p-2 shadow-md">
                          {#if canUnallow}
                            <li>
                              <Button onclick={() => unallowMember(member.pubkey)}>
                                <Icon icon={UserMinus} />
                                Remove User
                              </Button>
                            </li>
                          {/if}
                          {#if canBan}
                            <li>
                              <Button class="text-error" onclick={() => banMember(member.pubkey)}>
                                <Icon icon={MinusCircle} />
                                Ban User
                              </Button>
                            </li>
                          {/if}
                        </ul>
                      </Popover>
                    {/if}
                  </div>
                {/if}
              </div>
            </div>
          {/each}
        {/each}
      {/if}
    </div>
  </ModalBody>
  <ModalFooter>
    <Button class="btn btn-link" onclick={back}>
      <Icon icon={AltArrowLeft} />
      Go back
    </Button>
    {#if $canAddMember}
      <Button class="btn btn-primary" onclick={addMember}>
        <Icon icon={AddCircle} />
        Add members
      </Button>
    {/if}
  </ModalFooter>
</Modal>
