<template>
  <div class="container">
    <FormHeader title="Registro de Usuario" />
    <form class="form" @submit.prevent="userRegister">
      <FormInput
        v-model="register.email"
        class="input"
        required
        type="text"
        label-text="Email"
        @input="register.email = $event"
      />
      <FormInput
        v-model="register.full_name"
        class="input"
        required
        type="text"
        label-text="Nombre completo"
        @input="register.full_name = $event"
      />

      <FormInput
        
        class="input"
        required
        type="password"
        label-text="Contraseña"
        @input="register.password = $event"
      />

      <small v-if="error" class="text-danger" >{{ error }}</small>

      <SubmitButton text="registrar" image-url="" />
    </form>
    
    <p class="help" align="center">
      *Si quieres que tu cooperativa forme parte de este proyecto registrate en
      el siguiente
      <NuxtLink to="/registro/cooperativa"><b>formulario</b></NuxtLink
      >.
    </p>
  </div>
</template>

<script>
export default {
  setup() {
    definePageMeta({
      layout: 'main',
    })
  },
  data() {
    return {
      error: null,
      register: {
        email: '',
        full_name: '',
        password: '',
      },
    }
  },
  methods: {
    async userRegister() {
      this.error = null
      const config = useRuntimeConfig()
      try {
        const response = await $fetch('/users/', {
          baseURL: config.public.baseURL,
          method: 'POST',
          body: JSON.stringify(this.register),
        })
        if (response) {
          this.$router.push(`/registro/bienvenidausuario/${this.register.full_name}`)
        }
      } catch (err) {
        if (err?.response?.status === 404) {
          this.error = 'Usuario no encontrado'
        } else {
          this.error = 'Ha habido un error'
        }
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  margin-top: 5rem;
  margin-bottom: 5rem;

  @include mobile {
    margin-top: 7rem;
    margin-bottom: 3rem;
  }
}

.form {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80px;

  @include mobile {
    margin-bottom: 40px;
  }

  .checkbox-container {
    text-align: left;
  }
  // input[type='checkbox'] {
  //   margin-left: 10px;
  // }
}

.help {
  color: $color-navy;
  margin-bottom: 80px;
  font-size: $m;
  @include mobile {
    font-size: $s;
  }
}
</style>
