<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import axios from 'axios'
import {API_URL} from "@/main.js";
import { parseError, errors, clearErrors, addError, getError } from "@/components/request/HandleGlobalError.vue";
import LoadButtonWhileAwait from "@/components/request/LoadButtonWhileAwait.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";

const employees = ref([]);

const employee_key = ref('');
const user_id = ref('');

const error = ref('');

const store = useStore();
const router = useRouter();

const login = async () => {
  // Reset the error
  clearErrors();
  try {
    const response = await axios.post(API_URL + '/auth/employee/login', {
      user_id: user_id.value,
      password: employee_key.value,
      g_recaptcha_response: reCAPTCHA_data.value.enabled ? grecaptcha.getResponse() : null,
    });
    // Save the token in the local storage
    localStorage.setItem('token', response.data.data.token);
    // Redirect to the dashboard
    window.location.href = '/admin';
  } catch (e) {
    parseError(e, 'auth');
    // Reset the reCAPTCHA
    if (reCAPTCHA_data.value.enabled) {
      grecaptcha.reset();
    }
  }
};

const getEmployees = async () => {
  try {
    const response = await axios.get(API_URL + '/public/employees');
    employees.value = response.data.data;
  } catch (e) {
    parseError(e, 'employees');
  }
};

getEmployees();




const doNothing = () => {
  // Do nothing
};

const reCAPTCHA_data = ref({
  enabled: false,
  site_key: '',
});

const ratelimit_data = ref({
  enabled: false,
  limit: 0,
  remaining: 0,
  reset: 0,
  warning: null,
});

SessionUser.auth.reCAPTCHA.preCheck.get().then((response) => {
  console.log(response.data.data);
  reCAPTCHA_data.value = response.data.data.recaptcha;
  ratelimit_data.value = response.data.data.rate_limit;
  // If the reCAPTCHA is enabled, load the reCAPTCHA script
  if (reCAPTCHA_data.value.enabled) {
    const script = document.createElement('script');
    script.src = 'https://www.google.com/recaptcha/api.js';
    script.async = true;
    script.defer = true;
    document.head.appendChild(script);
  }
});
</script>

<template>
  <div>
    <div class="columns is-multiline is-centered">
      <div class="column is-3" v-for="employee in employees" :key="employee.id">
        <div class="card is-clickable is-hoverable-custom" @click="user_id = employee.id" :class="{ 'is-selected-custom': user_id === employee.id }">
          <div class="card-content">
            <div class="content">
              <p><strong>{{ employee.display_name}}</strong></p>
            </div>
          </div>
          <footer class="card-footer">
            <a class="card-footer-item" @click="user_id = employee.id">
              <span v-if="user_id === employee.id">
                <i class="fas fa-check"></i>
              </span>
              <span v-else>
                Select
              </span>
            </a>
          </footer>
        </div>
      </div>
    </div>
    <form @submit.prevent="doNothing" v-if="employees.length > 0 && user_id !== ''">
      <div class="field is-hidden">
        <label class="label">User ID</label>
        <div class="control">
          <input disabled class="input" type="text" v-model="user_id" />
        </div>
      </div>
      <div class="field">
        <label class="label">Adgangskode</label>
        <div class="control">
          <input class="input" type="password" v-model="employee_key" />
        </div>
      </div>
    </form>
      <!-- reCAPTCHA, if enabled -->
      <div class="field mt-6" v-if="reCAPTCHA_data.enabled">
        <div class="control">
          <div class="g-recaptcha" :data-sitekey="reCAPTCHA_data.site_key" id="g-recaptcha"></div>
        </div>
      </div>
    <form @submit.prevent="doNothing" v-if="employees.length > 0 && user_id !== ''">
      <!-- Display the error -->
      <div class="field">
        <p class="help is-danger" v-if="getError('auth')">
          {{ getError('auth') }}
        </p>
      </div>
      <div class="field">
        <div class="control">
          <LoadButtonWhileAwait :loadFunction="login" class="button is-dark is-fullwidth">Login</LoadButtonWhileAwait>
        </div>
      </div>
    <div class="field">
      <div class="control">
        <button class="button is-text" @click="router.push('/login')">Truck Wash kunde login</button>
      </div>
    </div>
    </form>
  </div>
</template>

<style scoped>
.is-hoverable-custom {
  border: 1px solid transparent;
  transition: border 0.3s ease-in-out;
}
.is-hoverable-custom:hover {
  border: 1px solid #3273dc;
}
.is-selected-custom {
  border: 1px solid #3273dc;
}
</style>