<script>
  import { ModalContent, Input, Select } from "@budibase/bbui"
  import sanitizeUrl from "builderStore/store/screenTemplates/utils/sanitizeUrl"
  import { selectedAccessRole, allScreens } from "builderStore"
  import { get } from "svelte/store"
  import { roles } from "stores/backend"

  export let onConfirm
  export let onCancel
  export let screenUrl
  export let confirmText = "Continue"

  let routeError
  let touched = false
  let screenAccessRole = $selectedAccessRole + ""

  const routeChanged = event => {
    if (!event.detail.startsWith("/")) {
      screenUrl = "/" + event.detail
    }
    touched = true
    screenUrl = sanitizeUrl(screenUrl)
    if (routeExists(screenUrl)) {
      routeError = "This URL is already taken for this access role"
    } else {
      routeError = null
    }
  }

  const routeExists = url => {
    const roleId = get(selectedAccessRole) || "BASIC"
    return get(allScreens).some(
      screen =>
        screen.routing.route.toLowerCase() === url.toLowerCase() &&
        screen.routing.roleId === roleId
    )
  }

  const confirmScreenDetails = async () => {
    await onConfirm({
      screenUrl,
      screenAccessRole,
    })
  }
</script>

<ModalContent
  size="M"
  title={"Enter details"}
  {confirmText}
  onConfirm={confirmScreenDetails}
  {onCancel}
  cancelText={"Back"}
  disabled={!screenAccessRole || !screenUrl || routeError || !touched}
>
  <!-- <Input label="Name" bind:value={screenName} /> -->
  <Input
    label="URL"
    error={routeError}
    bind:value={screenUrl}
    on:change={routeChanged}
  />
  <Select
    bind:value={screenAccessRole}
    label="Screen access"
    getOptionLabel={role => role.name}
    getOptionValue={role => role._id}
    getOptionColor={role => role.color}
    options={$roles}
  />
</ModalContent>

<style>
</style>
