<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-back-button></ion-back-button>
        </ion-buttons>
        <ion-title>
          Signup
        </ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content class='ion-padding'>

          <ion-input label="Username"  ref="username" label-placement="floating" fill="outline" placeholder="Example, john"
                                                                                                ></ion-input>
          <ion-input label="Email" label-placement="floating" ref='email' fill="outline" type="email" placeholder="Example, hello@gmail.com"></ion-input>
          <ion-input label="Password" label-placement='floating' fill='outline' ref="password" type="password" placeholder="Password"></ion-input>
          <ion-input label="Password Confirmation" label-placement='floating' fill='outline' ref="password2" type="password" placeholder="Password Confirmation"></ion-input>
          <ion-text color="danger" v-if="formError">{{ formError }}</ion-text>
          <ion-button @click="signup" class=' ion-margin-top'>Signup</ion-button>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonButton, onIonViewWillEnter, IonList, IonSearchbar, IonLabel,
IonItem, IonBackButton, IonProgressBar, IonButtons, IonInfiniteScroll,
    IonInfiniteScrollContent, InfiniteScrollCustomEvent, IonInput, toastController, useIonRouter } from '@ionic/vue';
import { defineComponent, onMounted } from 'vue';
import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';
import { searchMat, callUrl,restSignup } from '@/composable/settings';

import { ref } from 'vue';
import SearchItem from '@/components/SearchItem.vue';

const results = ref();
const is_empty = ref(false);
const processing = ref(false)
let next_url = null

const username = ref(null)
const password = ref(null)
const password2 = ref(null)
const email = ref(null)
const input = ref(null)
const ionRouter = useIonRouter();
const formError = ref(null)

const signup = async () => { 
  clearError(username)
  clearError(email)
  clearError(password)
  clearError(password2)
  formError.value = null
  try {
    console.log("username = ", username.value.$el.value)
    const data = await restSignup(username.value.$el.value, email.value.$el.value, password.value.$el.value, password2.value.$el.value)
    console.log(data)
    await presentToast("Sign up successful", "top")
    ionRouter.navigate('/tabs/tab4', 'forward', 'replace');
  }catch( err ) {
    console.log("-- error --")
    console.log(err)
    for(const [k,v] of Object.entries(err.response.data))  {
      if( k == "username" ){
        showError(username, v[0])
      }
      if( k == "email" ){
        showError(email, v[0])
      }
      if( k == "password1" ){
        showError(password, v[0])
      }
      if( k == "password2" ){
        showError(password2, v[0])
      }
      if( k == "non_field_errors" ) {
        formError.value = v[0]
      }
    }
  }
}

const showError = (obj, error) => {
  obj.value.$el.errorText = error
  obj.value.$el.classList.add('ion-invalid')
  obj.value.$el.classList.add('ion-touched');
}
const clearError = (obj) => {
  obj.value.$el.classList.remove("ion-valid")
  obj.value.$el.classList.remove("ion-invalid")
}

const validateEmail = (email) => {
        return email.match(
          /^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
        );
      }

  const validate = (ev) => {
        const value = ev.target.value;

        input.value.$el.classList.remove('ion-valid');
        input.value.$el.classList.remove('ion-invalid');

        if (value === '') return;

        validateEmail(value)
          ? input.value.$el.classList.add('ion-valid')
          : input.value.$el.classList.add('ion-invalid');
      }

const markTouched = () => {
  input.value.$el.classList.add('ion-touched');
}
const markTouched2 = () => {
  username.value.$el.classList.add('ion-touched');
}
const presentToast = async (msg, position: 'top' | 'middle' | 'bottom') => {
  console.log("present toast")
  const toast = await toastController.create({
    message: msg,
    duration: 3000,
    position: position,
    positionAnchor: "header",
    color: "success"
  });

  await toast.present();
}
</script>
