<script lang="ts">
  import {getRelaysFromList} from "@welshman/util"
  import {waitForThunkError, setMessagingRelays, userRelayList, setRelays} from "@welshman/app"
  import {preventDefault} from "@lib/html"
  import AltArrowLeft from "@assets/icons/alt-arrow-left.svg?dataurl"
  import AltArrowRight from "@assets/icons/alt-arrow-right.svg?dataurl"
  import Icon from "@lib/components2/Icon.svelte"
  import Button from "@lib/components2/Button.svelte"
  import Spinner from "@lib/components2/Spinner.svelte"
  import Text from "@lib/components2/Text.svelte"
  import Modal from "@lib/components2/Modal.svelte"
  import ModalBody from "@lib/components2/ModalBody.svelte"
  import ModalHeader from "@lib/components2/ModalHeader.svelte"
  import ModalTitle from "@lib/components2/ModalTitle.svelte"
  import ModalFooter from "@lib/components2/ModalFooter.svelte"
  import {DEFAULT_RELAYS, DEFAULT_MESSAGING_RELAYS} from "@app/env"
  import {pushToast} from "@app/toast"

  type Props = {
    next: () => void
  }

  const {next}: Props = $props()

  let loading = $state(false)

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

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

    try {
      if (getRelaysFromList($userRelayList).length === 0) {
        const error = await waitForThunkError(await setRelays(DEFAULT_RELAYS.map(r => ["r", r])))

        if (error) {
          pushToast({theme: "error", message: error})
          return
        }
      }

      const error = await waitForThunkError(await setMessagingRelays(DEFAULT_MESSAGING_RELAYS))

      if (error) {
        pushToast({theme: "error", message: error})
        return
      }

      await next()
    } finally {
      loading = false
    }
  }
</script>

<Modal tag="form" onsubmit={preventDefault(enable)}>
  <ModalBody>
    <ModalHeader>
      <ModalTitle>Enable direct messaging?</ModalTitle>
    </ModalHeader>
    <Text>Direct messaging isn't currently enabled. Would you like to turn it on?</Text>
  </ModalBody>
  <ModalFooter>
    <Button variant="ghost" onclick={back}>
      <Icon icon={AltArrowLeft} />
      Go back
    </Button>
    <Button type="submit" variant="primary" disabled={loading}>
      <Spinner {loading}>Enable direct messaging</Spinner>
      <Icon icon={AltArrowRight} />
    </Button>
  </ModalFooter>
</Modal>
