<script setup>

import { ref, useTemplateRef } from 'vue';
import { Dialog, TextInput, FormGroup } from '@cloudron/pankow';

const emit = defineEmits([ 'success' ]);

const dialog = useTemplateRef('dialog');

const formError = ref({});
const url = ref('');
const version = ref('latest');

function onSubmit() {
  formError.value = {};

  if (!url.value || !version.value) {
    formError.value.generic = 'URL and version are required';
    return;
  }

  emit('success', { url: url.value, version: version.value });
  dialog.value.close();
}

defineExpose({
  open() {
    url.value = '';
    version.value = 'latest';
    formError.value = {};
    dialog.value.open();
  }
});

</script>

<template>
  <Dialog ref="dialog"
    title="Install Community App"
    confirm-label="Continue"
    :confirm-active="url !== ''"
    reject-style="secondary"
    reject-label="Cancel"
    @confirm="onSubmit()"
  >
    <form @submit.prevent="onSubmit()" autocomplete="off">
      <input type="submit" style="display: none;" />

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

      <FormGroup>
        <label for="urlInput">CloudronVersions.json URL</label>
        <TextInput id="urlInput" v-model="url" required placeholder="https://example.com/CloudronVersions.json"/>
      </FormGroup>

      <FormGroup>
        <label for="versionInput">Version</label>
        <TextInput id="versionInput" v-model="version" required/>
      </FormGroup>
    </form>
  </Dialog>
</template>
