<template>
    <div class="form full-form auth-cover">
        <div class="form-container">
            <div class="form-form">
                <div class="form-form-wrap">
                    <div class="form-container">
                        <div class="form-content">
                            <h1 class="mb-1">Control Ganadero</h1>
                            <p class="text-muted mb-4">Iniciar sesión</p>
                            <div v-if="sessionNotice" class="alert alert-warning py-2 small">{{ sessionNotice }}</div>
                            <div v-if="loginAlert" class="alert alert-danger py-2 small" role="alert">{{ loginAlert }}</div>
                            <form novalidate class="text-start" ref="formComponent" @submit.stop.prevent="login">
                                <div class="form">
                                    <div id="username-field" class="field-wrapper input">
                                        <svg
                                            xmlns="http://www.w3.org/2000/svg"
                                            width="24"
                                            height="24"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                            class="feather feather-user"
                                        >
                                            <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                            <circle cx="12" cy="7" r="4"></circle>
                                        </svg>
                                        <input
                                            v-model="form.email"
                                            type="email"
                                            autocomplete="username"
                                            :class="fieldClass('email')"
                                            placeholder="Correo electrónico"
                                            @input="clearFieldError('email')"
                                        />
                                        <div class="invalid-feedback d-block" v-if="errors.email?.length">
                                            <div v-for="(item, index) in errors.email" :key="index">{{ item }}</div>
                                        </div>
                                    </div>

                                    <div id="password-field" class="field-wrapper input mb-2">
                                        <svg
                                            xmlns="http://www.w3.org/2000/svg"
                                            width="24"
                                            height="24"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                            class="feather feather-lock"
                                        >
                                            <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                                            <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                                        </svg>
                                        <input
                                            v-model="form.password"
                                            :type="passwordField"
                                            autocomplete="current-password"
                                            :class="fieldClass('password')"
                                            placeholder="Contraseña"
                                            @input="clearFieldError('password')"
                                        />
                                        <div class="invalid-feedback d-block" v-if="errors.password?.length">
                                            <div v-for="(item, index) in errors.password" :key="index">{{ item }}</div>
                                        </div>
                                    </div>
                                    <div class="d-sm-flex justify-content-between">
                                        <div class="field-wrapper toggle-pass d-flex align-items-center">
                                            <p class="d-inline-block">Mostrar contraseña</p>
                                            <label class="switch s-primary mx-2">
                                                <input @click="set_pwd_type" type="checkbox" class="custom-control-input" checked="" />
                                                <span class="slider round"></span>
                                            </label>
                                        </div>
                                        <div class="field-wrapper">
                                            <button type="submit" class="btn btn-primary" :disabled="isLoading">
                                                {{ isLoading ? 'Verificando…' : 'Iniciar sesión' }}
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                            <p class="terms-conditions">
                                © 2020 Todos los derechos reservados. Es un producto de Techmedia Solutiones tecnologicas.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-image">
                <div class="l-image"></div>
            </div>
        </div>
        <loading
        v-model:active="isLoading"
        :can-cancel="false"
        :is-full-page="true"/>
    </div>
</template>

<script setup>
    import "../../assets/sass/authentication/auth.scss";
    import { ref, onMounted } from "vue";
    import * as AuthRepository from "@/repositories/AuthRepository";
    import { usePermissions } from '@/composables/use-permissions';
    import { useMeta } from "../../composables/use-meta";
    import Loading from 'vue-loading-overlay';
    import 'vue-loading-overlay/dist/css/index.css';
    useMeta({ title: "Iniciar sesión" });

    const passwordField = ref("password");
    const form = ref({
        email: '',
        password: '',
    });
    const formComponent = ref(null);
    const submitted = ref(false);
    const errors = ref({});
    const isLoading = ref(false);
    const sessionNotice = ref('');
    const loginAlert = ref('');

    const set_pwd_type = () => {
        passwordField.value = passwordField.value === "password" ? "text" : "password";
    };

    function fieldClass(field) {
        if (!submitted.value) return '';
        return errors.value[field]?.length ? 'is-invalid' : '';
    }

    function clearFieldError(field) {
        if (errors.value[field]) {
            errors.value = { ...errors.value, [field]: null };
        }
        if (loginAlert.value) loginAlert.value = '';
    }

    function forceLogoutLocal() {
        localStorage.removeItem('token');
    }

    const login = async () => {
        submitted.value = true;
        loginAlert.value = '';
        errors.value = {};

        const email = String(form.value.email || '').trim();
        const password = String(form.value.password || '');

        if (!email || !password) {
            if (!email) errors.value.email = ['Ingresa tu correo electrónico.'];
            if (!password) errors.value.password = ['Ingresa tu contraseña.'];
            loginAlert.value = 'Debes indicar correo y contraseña.';
            return;
        }

        // No reutilizar sesión previa: solo entrar con credenciales nuevas válidas.
        forceLogoutLocal();

        isLoading.value = true;
        try {
            const response = await AuthRepository.createTokens({ email, password });
            if (!response.success || !response.token) {
                errors.value = response.error || {};
                loginAlert.value =
                    response.error?.password?.[0]
                    || response.error?.email?.[0]
                    || 'Correo o contraseña incorrectos.';
                forceLogoutLocal();
                return;
            }

            localStorage.setItem('token', response.token);
            usePermissions().resetPermissions();
            window.location.href = '/?nocache=' + Date.now();
        } catch (error) {
            forceLogoutLocal();
            loginAlert.value = 'No se pudo iniciar sesión. Revisa correo y contraseña.';
            console.error(error);
        } finally {
            isLoading.value = false;
        }
    };

    onMounted(() => {
        const params = new URLSearchParams(window.location.search);
        const session = params.get('session');
        if (session === 'expired') {
            forceLogoutLocal();
            sessionNotice.value = 'Tu sesión expiró o el token no es válido. Vuelve a iniciar sesión.';
        } else if (session === 'noperms') {
            forceLogoutLocal();
            sessionNotice.value = 'Tu cuenta no tiene permisos. Contacta al administrador o inicia con otra cuenta.';
        } else if (session === 'auth') {
            forceLogoutLocal();
            sessionNotice.value = 'Debes iniciar sesión con correo y contraseña válidos.';
        }
        // No prellenar contraseña; solo sugerir correo de admin en local vacío
        if (!form.value.email) {
            form.value.email = 'admin@gmail.com';
        }
    });
</script>
