<script lang="ts">
  import {onMount} from "svelte"
  import {setKey, popKey} from "@lib/implicit"
  import {sleep} from "@welshman/lib"
  import {Profiles} from "@welshman/app"
  import {app} from "@app/welshman"
  import AltArrowLeft from "@assets/icons/alt-arrow-left.svg?dataurl"
  import Spinner from "@lib/components/Spinner.svelte"
  import Button from "@lib/components/Button.svelte"
  import Field from "@lib/components/Field.svelte"
  import Icon from "@lib/components/Icon.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 Modal from "@lib/components/Modal.svelte"
  import ModalBody from "@lib/components/ModalBody.svelte"
  import Confirm from "@lib/components/Confirm.svelte"
  import RoomName from "@app/components/RoomName.svelte"
  import ProfileMultiSelect from "@app/components/ProfileMultiSelect.svelte"
  import {pushToast} from "@app/toast"
  import {pushModal} from "@app/modal"
  import {deriveRoom} from "@app/groups"
  import {deriveSpaceMembers, addRoomMembers} from "@app/members"

  interface Props {
    url: string
    h: string
  }

  const {url, h}: Props = $props()

  const room = deriveRoom(url, h)
  const spaceMembers = deriveSpaceMembers(url)

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

  const addMembers = async () => {
    loading = true

    try {
      // Show loading for auto submit callback
      await sleep(500)

      // TODO(welshman-migration): addRoomMembers now expects a RoomMeta domain
      // Reader, but deriveRoom yields the plain `Room` object. Passing it through
      // as `any` preserves prior runtime behavior; verify Rooms.addMember accepts
      // the plain Room shape (url/h/...) or resolve a real RoomMeta reader here.
      const error = await addRoomMembers(url, $room as any, pubkeys)

      if (error) {
        pushToast({theme: "error", message: error})
      } else {
        pushToast({message: "Members have successfully been added!"})
        back()
      }
    } finally {
      loading = false
    }
  }

  const onSubmit = async () => {
    if (!$spaceMembers) {
      addMembers()
      return
    }

    const pubkeysSnapshot = $state.snapshot(pubkeys)
    const nonSpaceMembers = pubkeysSnapshot.filter(pubkey => !$spaceMembers.includes(pubkey))

    if (nonSpaceMembers.length > 0) {
      setKey("RoomMembersAdd.pubkeys", pubkeysSnapshot)

      pushModal(Confirm, {
        title: "New Space Members",
        subtitle: "Automatically add members to space",
        message:
          nonSpaceMembers.length === 1
            ? `${app.use(Profiles).display(nonSpaceMembers[0]).get()} is not a member of this space. Add them?`
            : `${nonSpaceMembers.length} people are not members of this space. Add them?`,
        confirm: async () => {
          setKey("RoomMembersAdd.confirm", true)
          back()
        },
      })
    } else {
      addMembers()
    }
  }

  let loading = $state(false)
  let pubkeys: string[] = $state(popKey("RoomMembersAdd.pubkeys") || [])

  onMount(() => {
    if (popKey("RoomMembersAdd.confirm")) {
      addMembers()
    }
  })
</script>

<Modal>
  <ModalBody>
    <ModalHeader>
      <ModalTitle>Add Members</ModalTitle>
      <ModalSubtitle>to <RoomName {url} {h} class="text-primary" /></ModalSubtitle>
    </ModalHeader>
    <Field>
      {#snippet label()}
        <p>Search for People</p>
      {/snippet}
      {#snippet input()}
        <ProfileMultiSelect bind:value={pubkeys} />
      {/snippet}
    </Field>
  </ModalBody>
  <ModalFooter>
    <Button class="btn btn-link" onclick={back}>
      <Icon icon={AltArrowLeft} />
      Go back
    </Button>
    <Button class="btn btn-primary" onclick={onSubmit} disabled={loading}>
      <Spinner {loading}>Save changes</Spinner>
    </Button>
  </ModalFooter>
</Modal>
