<script>
  import {
    Body,
    Input,
    Select,
    ModalContent,
    notifications,
    Toggle,
    Label,
  } from "@budibase/bbui"
  import { createValidationStore, emailValidator } from "helpers/validation"
  import { users } from "stores/portal"

  export let disabled

  const options = ["Email onboarding", "Basic onboarding"]
  let selected = options[0]
  let builder, admin

  const [email, error, touched] = createValidationStore("", emailValidator)

  async function createUserFlow() {
    const res = await users.invite({ email: $email, builder, admin })
    if (res.status) {
      notifications.error(res.message)
    } else {
      notifications.success(res.message)
    }
  }
</script>

<ModalContent
  onConfirm={createUserFlow}
  size="M"
  title="Add new user"
  confirmText="Add user"
  confirmDisabled={disabled}
  cancelText="Cancel"
  disabled={$error}
  showCloseIcon={false}
>
  <Body size="S">
    If you have SMTP configured and an email for the new user, you can use the
    automated email onboarding flow. Otherwise, use our basic onboarding process
    with autogenerated passwords.
  </Body>
  <Select
    placeholder={null}
    bind:value={selected}
    on:change
    {options}
    label="Add new user via:"
  />
  <Input
    type="email"
    bind:value={$email}
    error={$touched && $error}
    placeholder="john@doe.com"
    label="Email"
  />
  <div>
    <div class="toggle">
      <Label size="L">Development access</Label>
      <Toggle text="" bind:value={builder} />
    </div>
    <div class="toggle">
      <Label size="L">Administration access</Label>
      <Toggle text="" bind:value={admin} />
    </div>
  </div>
</ModalContent>

<style>
  .toggle {
    display: grid;
    grid-template-columns: 78% 1fr;
    align-items: center;
    width: 50%;
  }
</style>
