<script setup>
import { onMounted, ref } 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 GoogleIcon    from '@Shared/GoogleIcon.vue'
import Error         from '@Holos/Form/Elements/Error.vue'

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

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

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

const showPassword = ref(false);
const isLoading = ref(false);

/** Métodos */
const login = () => {
    isLoading.value = true;
    form.post(route('auth.login'), {
        onSuccess: (res) => {
          defineApiToken(res.token)
          defineUser(res.user)
          defineCsrfToken(res.csrf)
          location.replace('/')
        },
        onError: () => {
          isLoading.value = false;
        },
        onFinish: () => {
          isLoading.value = false;
        }
    });
};

const togglePassword = () => {
    showPassword.value = !showPassword.value;
};

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

<template>
  <div class="w-full">
    <!-- Header del formulario -->
    <div class="mb-8">
      <h1 class="text-2xl font-bold text-page-t dark:text-page-dt mb-2">
        Iniciar Sesion
      </h1>
      <p class="text-page-t/60 dark:text-page-dt/60 text-sm">
        Ingrese sus credenciales.
      </p>
    </div>

    <form @submit.prevent="login" class="space-y-6">
      <!-- Campo Email/Usuario -->
      <div class="space-y-2">
        <label for="email" class="block text-xs font-semibold text-page-t/70 dark:text-page-dt/70 uppercase tracking-wider">
          Email / Usuario
        </label>
        <div class="relative group">
          <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
            <GoogleIcon
              name="person"
              class="text-page-t/40 dark:text-page-dt/40 group-focus-within:text-primary dark:group-focus-within:text-primary-dt transition-colors"
            />
          </div>
          <input
            id="email"
            type="email"
            v-model="form.email"
            placeholder="ID de empleado"
            class="w-full pl-12 pr-4 py-3.5 bg-page dark:bg-page-d border border-primary/20 dark:border-primary-dt/20 rounded-lg
                   text-page-t dark:text-page-dt placeholder-page-t/40 dark:placeholder-page-dt/40
                   focus:outline-none focus:border-primary/50 dark:focus:border-primary-dt/50 focus:ring-2 focus:ring-primary/10 dark:focus:ring-primary-dt/10
                   hover:border-primary/30 dark:hover:border-primary-dt/30 transition-all duration-200"
            :class="{ 'border-danger! focus:border-danger! focus:ring-danger/20!': form.errors.email }"
            autocomplete="email"
          />
        </div>
        <Error :onError="form.errors.email" />
      </div>

      <!-- Campo Password -->
      <div class="space-y-2">
        <label for="password" class="block text-xs font-semibold text-page-t/70 dark:text-page-dt/70 uppercase tracking-wider">
          Contraseña
        </label>
        <div class="relative group">
          <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
            <GoogleIcon
              name="lock"
              class="text-page-t/40 dark:text-page-dt/40 group-focus-within:text-primary dark:group-focus-within:text-primary-dt transition-colors"
            />
          </div>
          <input
            id="password"
            :type="showPassword ? 'text' : 'password'"
            v-model="form.password"
            placeholder="••••••••••"
            class="w-full pl-12 pr-12 py-3.5 bg-page dark:bg-page-d border border-primary/20 dark:border-primary-dt/20 rounded-lg
                   text-page-t dark:text-page-dt placeholder-page-t/40 dark:placeholder-page-dt/40
                   focus:outline-none focus:border-primary/50 dark:focus:border-primary-dt/50 focus:ring-2 focus:ring-primary/10 dark:focus:ring-primary-dt/10
                   hover:border-primary/30 dark:hover:border-primary-dt/30 transition-all duration-200"
            :class="{ 'border-danger! focus:border-danger! focus:ring-danger/20!': form.errors.password }"
            autocomplete="current-password"
          />
          <button
            type="button"
            @click="togglePassword"
            class="absolute inset-y-0 right-0 pr-4 flex items-center text-page-t/40 dark:text-page-dt/40 hover:text-page-t dark:hover:text-page-dt transition-colors"
          >
            <GoogleIcon :name="showPassword ? 'visibility_off' : 'visibility'" />
          </button>
        </div>
        <Error :onError="form.errors.password" />
      </div>

      <!-- Boton de Login -->
      <PrimaryButton
        class="w-full! py-4! text-sm! font-semibold! rounded-lg! mt-2!
               bg-primary! hover:bg-primary/90! dark:bg-primary-d! dark:hover:bg-primary-d/90!
               transition-all duration-200"
        :disabled="isLoading || form.processing"
        :class="{ 'opacity-70 cursor-not-allowed': isLoading || form.processing }"
      >
        <span v-if="isLoading || form.processing" class="flex items-center justify-center gap-2">
          <svg class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          Verificando...
        </span>
        <span v-else>
          Acceder al Sistema
        </span>
      </PrimaryButton>
    </form>
  </div>
</template>
