<script>
  import { writable, get as svelteGet } from "svelte/store"
  import {
    notifications,
    Input,
    ModalContent,
    Dropzone,
    Body,
    Checkbox,
  } from "@budibase/bbui"
  import { store, automationStore, hostingStore } from "builderStore"
  import { string, mixed, object } from "yup"
  import api, { get } from "builderStore/api"
  import { post } from "builderStore/api"
  import analytics from "analytics"
  import { onMount } from "svelte"
  import { capitalise } from "helpers"
  import { goto } from "@roxi/routify"

  export let template

  const values = writable({ name: null })
  const errors = writable({})
  const touched = writable({})
  const validator = {
    name: string().required("Your application must have a name"),
    file: mixed().required("Please choose a file to import"),
  }

  let submitting = false
  let valid = false
  $: checkValidity($values, validator)

  onMount(async () => {
    await hostingStore.actions.fetchDeployedApps()
    const existingAppNames = svelteGet(hostingStore).deployedAppNames
    validator.name = string()
      .required("Your application must have a name")
      .test(
        "non-existing-app-name",
        "Another app with the same name already exists",
        value => {
          return !existingAppNames.some(
            appName => appName.toLowerCase() === value.toLowerCase()
          )
        }
      )
  })

  const checkValidity = async (values, validator) => {
    const obj = object().shape(validator)
    Object.keys(validator).forEach(key => ($errors[key] = null))
    try {
      await obj.validate(values, { abortEarly: false })
    } catch (validationErrors) {
      validationErrors.inner.forEach(error => {
        $errors[error.path] = capitalise(error.message)
      })
    }
    valid = await obj.isValid(values)
  }

  async function createNewApp() {
    submitting = true

    // Check a template exists if we are important
    if (template && !$values.file) {
      $errors.file = "Please choose a file to import"
      valid = false
      submitting = false
      return false
    }

    try {
      // Create form data to create app
      let data = new FormData()
      data.append("name", $values.name)
      data.append("useTemplate", template != null)
      if (template) {
        data.append("templateName", template.name)
        data.append("templateKey", template.key)
        data.append("templateFile", $values.file)
      }

      // Create App
      const appResp = await post("/api/applications", data, {})
      const appJson = await appResp.json()
      if (!appResp.ok) {
        throw new Error(appJson.message)
      }

      analytics.captureEvent("App Created", {
        name: $values.name,
        appId: appJson._id,
        template,
      })

      // Select Correct Application/DB in prep for creating user
      const applicationPkg = await get(
        `/api/applications/${appJson._id}/appPackage`
      )
      const pkg = await applicationPkg.json()
      if (applicationPkg.ok) {
        await store.actions.initialise(pkg)
        await automationStore.actions.fetch()
      } else {
        throw new Error(pkg)
      }

      // Create user
      const user = {
        roleId: $values.roleId,
      }
      const userResp = await api.post(`/api/users/metadata/self`, user)
      await userResp.json()
      $goto(`/builder/app/${appJson._id}`)
    } catch (error) {
      console.error(error)
      notifications.error(error)
      submitting = false
    }
  }
</script>

<ModalContent
  title={template ? "Import app" : "Create new app"}
  confirmText={template ? "Import app" : "Create app"}
  onConfirm={createNewApp}
  disabled={!valid}
>
  {#if template}
    <Dropzone
      error={$touched.file && $errors.file}
      gallery={false}
      label="File to import"
      value={[$values.file]}
      on:change={e => {
        $values.file = e.detail?.[0]
        $touched.file = true
      }}
    />
  {/if}
  <Body size="S">
    Give your new app a name, and choose which groups have access (paid plans
    only).
  </Body>
  <Input
    bind:value={$values.name}
    error={$touched.name && $errors.name}
    on:blur={() => ($touched.name = true)}
    label="Name"
  />
  <Checkbox label="Group access" disabled value={true} text="All users" />
</ModalContent>

<!--<div class="container">-->
<!--  <div class="sidebar">-->
<!--    <img src={Logo} alt="budibase icon" />-->
<!--    <div class="steps">-->
<!--      {#each steps as component, i}-->
<!--        <Indicator-->
<!--          active={$currentStep === i}-->
<!--          done={i < $currentStep}-->
<!--          step={i + 1}-->
<!--        />-->
<!--      {/each}-->
<!--    </div>-->
<!--  </div>-->
<!--  <div class="body">-->
<!--    <div class="heading">-->
<!--      <Heading size="L">Get started with Budibase</Heading>-->
<!--    </div>-->
<!--    <div class="step">-->
<!--      {#each steps as component, i (i)}-->
<!--        <div class:hidden={$currentStep !== i}>-->
<!--          <svelte:component-->
<!--            this={component}-->
<!--            {template}-->
<!--            {values}-->
<!--            {errors}-->
<!--            {touched}-->
<!--          />-->
<!--        </div>-->
<!--      {/each}-->
<!--    </div>-->
<!--    <div class="footer">-->
<!--      {#if $currentStep > 0}-->
<!--        <Button medium secondary on:click={() => $currentStep&#45;&#45;}>Back</Button>-->
<!--      {/if}-->
<!--      {#if $currentStep < steps.length - 1}-->
<!--        <Button medium cta on:click={() => $currentStep++} disabled={!valid}>-->
<!--          Next-->
<!--        </Button>-->
<!--      {/if}-->
<!--      {#if $currentStep === steps.length - 1}-->
<!--        <Button-->
<!--          medium-->
<!--          cta-->
<!--          on:click={createNewApp}-->
<!--          disabled={!valid || submitting}-->
<!--        >-->
<!--          {submitting ? "Loading..." : "Submit"}-->
<!--        </Button>-->
<!--      {/if}-->
<!--    </div>-->
<!--  </div>-->
<!--  {#if submitting}-->
<!--    <div in:fade class="spinner-container">-->
<!--      <Spinner />-->
<!--      <span class="spinner-text">Creating your app...</span>-->
<!--    </div>-->
<!--  {/if}-->
