<script setup lang="ts">
import {reactive} from 'vue';
import axios from "axios";
import {useAuthStore} from "@/stores/auth.store.ts";
import {useRouter} from "vue-router";

const data = reactive({
  'username': null,
  'password': null,
  'loading': false,
  'errors': {}
});

const router = useRouter();

const onSubmit = () => {
  if (!data.username || !data.password) return;

  data.loading = true;

  axios.post('/login', {
    username: data.username,
    password: data.password,
  }).then(async (response) => {
    if (response.status === 200) {
      console.log(response);
      const timezone = await setTimezone(response.data);
      const auth = useAuthStore();
      const userStore = {
        user: response.data,
        password: data.password,
        timezone: timezone
      }
      auth.setUserData(userStore);

      router.push('/');
    } else {
      console.log(response)
    }
  }).catch((error) => {
    console.log(error);
    data.errors = error.response.data.errors
    data.loading = false;
    console.log(data)
  });

}

const setTimezone = (user): Promise<string> => {
  return axios.get("timezone").then((res) => {
    return res.data;
  }).catch(error => {
    console.log("Error: "+error);
    return null;
  })
}

const required = (v) => {
  return !!v || $t('login.errors.required');
}
</script>

<template>
  <v-container class="d-flex items-center justify-center">
    <v-card class="mx-auto px-6 py-8" min-width="500">
      <v-form
          v-model="data.form"
          @submit.prevent="onSubmit"
      >
        <v-card-item class="text-center">
          <v-card-title>{{ $t('login.title') }}</v-card-title>
          <v-card-subtitle>{{ $t('login.subtitle') }}</v-card-subtitle>
        </v-card-item>
        <v-card-text>
          <v-text-field
              v-model="data.username"
              class="mb-2"
              label="Username"
              name="username"
              autocomplete="username"
              :error-messages="data.errors?.username"
              hide-details="auto"
          ></v-text-field>
          <v-text-field
              v-model="data.password"
              label="Password"
              placeholder="Enter your password"
              name="password"
              type="password"
              autocomplete="current-password"
              :error-messages="data.errors?.username"
              hide-details="auto"
          ></v-text-field>
        </v-card-text>
        <v-card-actions>
          <v-btn
              :disabled="!data.username || !data.password"
              :loading="data.loading"
              color="primary"
              size="large"
              type="submit"
              variant="elevated"
              block
          >
            Sign In
          </v-btn>
        </v-card-actions>
      </v-form>
    </v-card>
  </v-container>
</template>

<style scoped>
.v-container {
  height: 100vh;
}
</style>