<script setup>
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { defineApiToken, defineCsrfToken, hasToken, useForm } from '@Services/Api.js'
import { defineUser } from '@Services/Page';
import { viewTo } from './Module.js';

import PrimaryButton  from '@Holos/Button/Primary.vue'
import Input          from '@Holos/Form/InputWithIcon.vue'

/** Definidores */
const router = useRouter();

/** Propiedades */
defineProps({
    canResetPassword: Boolean,
    status: String,
});

const form = useForm({
    email: '',
    password: ''
});

/** Métodos */
const login = () => {
    form.post(route('auth.login'), {
        onSuccess: (res) => {
          defineApiToken(res.token)
          defineUser(res.user)
          defineCsrfToken(res.csrf)

          location.replace('/')
        }
    });
};

/** Ciclos */
onMounted(() => {
  if (hasToken()) {
    router.push({ name: 'dashboard.index' });
  }
})
</script>

<template>
  <div>
    <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-8">
      Bienvenido de nuevo
    </h1>

    <form @submit.prevent="login" class="space-y-6">
      <Input
        icon="mail"
        id="email"
        type="email"
        v-model="form.email"
        :onError="form.errors.email"
        :placeholder="$t('email.title')"
      />
      <Input
        v-model="form.password"
        icon="lock"
        id="password"
        type="password"
        :onError="form.errors.password"
        :placeholder="$t('password')"
      />

      <div class="flex justify-end">
        <RouterLink
          class="text-sm text-gray-600 dark:text-gray-400 hover:text-primary dark:hover:text-primary-dt transition-colors"
          :to="viewTo({ name: 'forgot-password' })"
        >
          {{ $t('auth.forgotPassword.ask') }}
        </RouterLink>
      </div>

      <PrimaryButton class="w-full! py-3! text-base! font-semibold!">
        {{$t('auth.login')}}
      </PrimaryButton>
    </form>
  </div>
</template>
