<template>
  <div class="flex flex-col justify-center h-screen items-center px-2 pb-20">
    <h1 class="font-bold text-3xl text-center mb-20">Reddingsbrigade Waddinxveen</h1>
    <div class="max-w-sm w-full">
      <form v-if="!creatingAccount" @submit.prevent="submitLoginForm" class="flex flex-col">
        <label class="font-bold">Email</label>
        <input v-model="form.email" required="true" placeholder="user@example.com" class="input mb-5" type="email">

        <label class="font-bold">Wachtwoord</label>
        <input v-model="form.password" required="true" class="input" :type="showPassword ? 'text' : 'password'">
        <div class="mb-5 mt-1 flex items-center text-default">
          <input v-model="showPassword" type="checkbox" class="mr-1 checkbox ">
          <span>Toon wachtwoord</span>
        </div>

        <div class="w-full flex flex-wrap justify-between">
          <input :disabled="disableButtons" type="submit" value="Login" class="btn w-full sm:w-24 mb-1">
          <button @click="forgotPassword" class="hover:underline font-bold w-full sm:w-max sm:ml-auto">Wachtwoord vergeten?</button>
        </div>

        <i class="mt-10 text-black dark:text-gray-200">Is dit jouw eerste keer inloggen? Gebruik dan als email het email dat gebruikt is bij de inschrijving en het wachtwoord is uw Lidnummmer / Sportlinknummer</i>
      </form>
      <form v-else @submit.prevent="submitCreateForm" class="flex flex-col">
        <h3 class="text-center text-default text-lg mb-5">Account aanmaken voor <br><b>{{ form.email }}</b></h3>
        <label class="font-bold">Nieuw wachtwoord</label>
        <input v-model="form.newPassword" required="true" class="input mb-1" :type="showPassword ? 'text' : 'password'">
        <span class="mb-5 text-default italic text-sm">Minimaal 8 karakters</span>

        <label class="font-bold">Herhaal nieuw wachtwoord</label>
        <input v-model="form.confirmNewPassword" required="true" class="input" :type="showPassword ? 'text' : 'password'">
        <div class="mb-5 mt-1 flex items-center text-default">
          <input v-model="showPassword" type="checkbox" class="mr-1 checkbox ">
          <span>Toon wachtwoord</span>
        </div>

        <div class="w-full flex flex-wrap">
          <input :disabled="disableButtons" type="submit" value="Account Aanmaken" class="btn w-full sm:w-40 mb-1">
          <button @click="goBack" class="hover:underline font-bold w-full sm:w-max sm:ml-auto">Jij niet? Ga terug</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { useToast } from 'vue-toastification'
import { createUserWithEmailAndPassword, signInWithEmailAndPassword, sendPasswordResetEmail } from "firebase/auth";
import { doc, setDoc, getFirestore } from "firebase/firestore"; 

const toast = useToast()
const userStore = useUserStore()

const showPassword = ref(false)
const creatingAccount = ref(false)
const disableButtons = ref(false)

const db = getFirestore()

const form = ref({
  email: '',
  password: '',
  newPassword: '',
  confirmNewPassword: ''
})

const submitLoginForm = () => {
  disableButtons.value = true
  signInWithEmailAndPassword(userStore.auth, form.value.email, form.value.password)
    .then(() => disableButtons.value = false)
    .catch(async (error) => {

      if (error.code === 'auth/user-not-found') {
        const { error: err, data } = await useFetch('/api/checkrelatiecode', {
          method: 'post',
          body: { email: form.value.email, relatiecode: form.value.password.toUpperCase()  } 
        })

        if (err.value) {
          console.log(err.value)
          disableButtons.value = false
          return toast.error('Error tijdens het controleren van relatiecode')
        }

        disableButtons.value = false
        if (data.value.code === 'incorrect') return toast.error('Email, wachtwoord of relatiecode onjuist')
        else if (data.value.code === 'correct') return creatingAccount.value = true

      } else if (error.code === 'auth/wrong-password') {
          toast.error('Verkeerde wachtwoord')
      } else {
          toast.error('Error met inloggen')
      }

      disableButtons.value = false
      console.log(error.message)
    });
}

const submitCreateForm = () => {
  if (form.value.newPassword !== form.value.confirmNewPassword) return toast.error('Wachtwoorden zijn niet hetzelfde');
  if (form.value.newPassword.length < 8) return toast.error('Wachtwoord heeft te weinig karakters');

  disableButtons.value = true

  createUserWithEmailAndPassword(userStore.auth, form.value.email, form.value.newPassword)
    .then(async (userCredential) => {
      const idToken = await userStore.auth.currentUser.getIdToken(true)
      const { error, data } = await useFetch('/api/getrelatiecodes', {
        method: 'post',
        body: { email: form.value.email, token: idToken } 
      })

      if (error.value) {
        console.log(error.value)
        disableButtons.value = false
        return toast.error('Error tijdens het controleren van relatiecode')
      }

      disableButtons.value = false
      if (data.value.code === 'error') return toast.error('Error tijdens maken van account')
      else if (data.value.code === 'success') {
        await setDoc(doc(db, "users", userCredential.user.uid), {
          email: form.value.email,
          relatiecodes: [form.value.password.toUpperCase()],
          allRelatiecodes: data.value.relatiecodes,
          id: userCredential.user.uid,
        });

        data.value.persons.forEach(person => {
          if (person.relatiecode === form.value.password.toUpperCase()) {
            person.checked = true
          } else {
            person.checked = false
          }
        }) 

        userStore.userAllPersons = data.value.persons

        if (data.value.relatiecodes.length > 1) {
          return navigateTo('/settings/config/managerelatiecodes')
        }
      }
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      
      console.log(error)

      toast.error('Error tijdens het maken van account')
    });
}

const forgotPassword = () => {
  sendPasswordResetEmail(userStore.auth, form.value.email)
    .then(() => {
      toast.info('Wachtwoord vergeten email verstuurd!')
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;

      console.log(error)

      toast.error('Error tijdens het versturen van het wachtwoord vergeten email')
    });
}

const goBack = () => {
  creatingAccount.value = false
  form.value = {
    email: form.value.email,
    password: form.value.password,
    newPassword: '',
    confirmNewPassword: ''
  }
}

</script>