<script setup>

import { ref, useTemplateRef, onMounted } from 'vue';
import { Button, Checkbox, FormGroup, TextInput, PasswordInput, EmailInput } from '@cloudron/pankow';
import ProvisionModel from '../models/ProvisionModel.js';
import { redirectIfNeeded, startAuthFlow } from '../utils.js';

const provisionModel = ProvisionModel.create();

const formError = ref({});
const busy = ref(false);
const displayName = ref('');
const email = ref('');
const username = ref('');
const password = ref('');
const acceptLicense = ref(false);

const form = useTemplateRef('form');
const isFormValid = ref(false);
function checkValidity() {
  isFormValid.value = form.value ? form.value.checkValidity() : false;
}

async function onOwnerSubmit() {
  if (!form.value.reportValidity()) return;

  busy.value = true;
  formError.value = {};

  const data = {
    username: username.value,
    password: password.value,
    email: email.value,
    displayName: displayName.value,
  };

  const [error, result] = await provisionModel.createAdmin(data);
  if (error) {
    if (error.status === 400) {
      if (error.body.message === 'Invalid email') {
        formError.value.email = error.body.message;
        email.value = '';
      } else if (error.body.message === 'Password must be atleast 8 characters') {
        formError.value.password = error.body.message;
        password.value = '';
      } else {
        formError.value.username = error.body.message;
        username.value = '';
      }
    } else {
      formError.value.generic = error.body ? error.body.message : 'Internal error';
      console.error('Internal error', error);
    }

    busy.value = false;
    return;
  }

  // set token to autologin on first oidc flow
  localStorage.cloudronFirstTimeToken = result;

  window.location.href = await startAuthFlow('cid-webadmin', '');
}

onMounted(async () => {
  const [error, result] = await provisionModel.status();
  if (error) return console.error(error);

  if (redirectIfNeeded(result, 'activation')) return; // redirected to some other view...
});

</script>

<template>
  <div class="container">
    <div class="view">
      <h1 style="text-align: center;">Welcome to Cloudron</h1>
      <h3 style="text-align: center;">Create Admin Account</h3>

      <div class="has-error" v-if="formError.generic">{{ formError.generic }}</div>

      <form @submit.prevent="onOwnerSubmit()" autocomplete="off" ref="form" @input="checkValidity()">
        <fieldset :disabled="busy">
          <input type="submit" style="display: none;"/>

          <FormGroup :has-error="formError.displayName">
            <label for="displayNameInput">Full name</label>
            <TextInput id="displayNameInput" v-model="displayName" required />
            <small class="text-danger">{{ formError.displayName }}</small>
          </FormGroup>

          <FormGroup :has-error="formError.email">
            <label for="emailInput">Email <sup><a href="https://docs.cloudron.io/installation/#admin-account" target="_blank" tabIndex="-1"><i class="fa fa-question-circle"></i></a></sup></label>
            <EmailInput id="emailInput" v-model="email" required />
            <small class="text-danger">{{ formError.email }}</small>
            <small class="helper-text">A valid email is required for Let's Encrypt certificates. This email is local to your Cloudron.</small>
          </FormGroup>

          <FormGroup :has-error="formError.username">
            <label for="usernameInput">Username</label>
            <TextInput id="usernameInput" v-model="username" required />
            <small class="text-danger">{{ formError.username }}</small>
          </FormGroup>

          <FormGroup :has-error="formError.password">
            <label for="passwordInput">Password</label>
            <PasswordInput id="passwordInput" v-model="password" required />
            <small class="text-danger">{{ formError.password }}</small>
          </FormGroup>

          <Checkbox v-model="acceptLicense" label="Accept Cloudron license" helpUrl="https://www.cloudron.io/legal/terms.html" required />
        </fieldset>

        <div class="actions">
          <Button :disabled="busy || !isFormValid" :loading="busy" @click="onOwnerSubmit()">Create admin</Button>
        </div>
      </form>
    </div>
  </div>
</template>

<style scoped>

.actions {
  margin-top: 1.5em;
  display: flex;
  flex-direction: column;
  align-items: center;
}

</style>
