<template>
  <div class="login-container" :style="{ backgroundImage: 'url(' + backgroundImage + ')' }">
    <div class="login-box">
      <div class="login-form">
        <h1>SIGN IN</h1>
        <form @submit.prevent="login_user">
          <div class="input-group">
            <div class="input-wrapper">
              <span class="input-icon">
                <img :src="mailIcon" alt="Mail icon" />
              </span>
              <input
                v-model="email"
                type="email"
                placeholder="Email"
                required
                autocomplete="off"
                :class="{'input-error': (emailError && (emailTouched || triedSubmit))}"
                @blur="emailTouched = true; validateEmail()"
              />
            </div>
            <div v-if="(emailTouched || triedSubmit) && emailError" class="error-message">Introduce un email válido.</div>
          </div>
          <div class="input-group">
            <div class="input-wrapper">
              <span class="input-icon">
                <img :src="lockIcon" alt="Lock icon" />
              </span>
              <input
                v-model="password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="Contraseña"
                required
                autocomplete="current-password"
                :class="{'input-error': (passwordError && (passwordTouched || triedSubmit))}"
                @blur="passwordTouched = true; validatePassword()"
              />
              <span class="toggle-password" @click="toggleShowPassword">
                <i :class="showPassword ? 'bi bi-eye-slash' : 'bi bi-eye'"></i>
              </span>
            </div>
            <div v-if="(passwordTouched || triedSubmit) && passwordError" class="error-message">La contraseña es requerida.</div>
          </div>
          <button type="submit" class="login-button">Iniciar sesión</button>
        </form>
        <p class="signup-link">
          ¿No tienes una cuenta?
          <router-link to="/signup" class="signup-link-text">Regístrate</router-link>
        </p>
      </div>
      <div class="login-image">
        <img :src="boxImage" alt="Login illustration" />
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import Swal from 'sweetalert2'
import UserServices from '../services/UserServices.js'
import LoginServices from '../services/LoginServices'
import AccountServices from '../services/AccountServices.js'

export default {
  data () {
    return {
      email: '',
      password: '',
      token: null,
      is_authenticated: false,
      boxImage: require('../assets/foto_evento_3colores2.jpg'),
      backgroundImage: require('../assets/fondo_claro.jpg'),
      mailIcon: require('../assets/mail_icon.png'),
      lockIcon: require('../assets/lock_icon.png'),
      showPassword: false,
      // Validación
      emailError: false,
      passwordError: false,
      emailTouched: false,
      passwordTouched: false,
      triedSubmit: false
    }
  },
  methods: {
    validateEmail () {
      this.emailError = !/^\S+@\S+\.\S+$/.test(this.email)
    },
    validatePassword () {
      this.passwordError = !this.password
    },
    toggleShowPassword () {
      this.showPassword = !this.showPassword
    },
    async login_user (event) {
      this.triedSubmit = true
      this.validateEmail()
      this.validatePassword()

      if (this.emailError || this.passwordError) {
        Swal.fire({
          icon: 'error',
          title: 'Error de validación',
          text: 'Por favor, revisa los campos marcados en rojo.'
        })
        return
      }

      const data = `username=${this.email}&password=${this.password}`
      try {
        const res = await LoginServices.login(data)
        this.is_authenticated = true
        this.token = res.data.access_token

        localStorage.setItem('token', this.token)
        axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}`

        const userInfo = await UserServices.getActualUser()
        const accountInfo = await AccountServices.getAccountById(userInfo.id)
        const userFull = {
          ...userInfo,
          account: accountInfo
        }
        console.log('userFull', JSON.stringify(userFull))
        localStorage.setItem('user', JSON.stringify(userFull))

        if (userInfo.role === 'vendor_particular' || userInfo.role === 'vendor_business') {
          Swal.fire({
            icon: 'success',
            title: '¡Bienvenido!',
            text: 'Redirigiendo a la página del proveedor...',
            timer: 2000,
            showConfirmButton: false
          }).then(() => {
            this.$router.push({ path: '/mainPageVendor' })
          })
        } else {
          Swal.fire({
            icon: 'success',
            title: '¡Bienvenido!',
            text: 'Redirigiendo a la página del cliente...',
            timer: 2000,
            showConfirmButton: false
          }).then(() => {
            this.$router.push({ path: '/mainPageClient' })
          })
        }
      } catch (error) {
        console.error(error)
        Swal.fire({
          icon: 'error',
          title: 'Error de inicio de sesión',
          text: 'Email o contraseña incorrectos. Por favor, inténtalo de nuevo.'
        })
      }
    }
  }
}
</script>

<style scoped>
/* Fullscreen container with background */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-color: #f5ece0;
  padding: 0;
  margin: 0;
}

/* Login box style */
.login-box {
  display: flex;
  width: 900px;
  padding: 30px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 10px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  position: relative;
  justify-content: space-between;
}

/* Login form styling */
.login-form {
  width: 45%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  padding-right: 30px;
}

/* Sign In title */
h1 {
  text-align: center;
  font-size: 28px;
  margin-bottom: 20px;
  color: #333;
}

/* Input field styles */
.input-group {
  position: relative;
  margin-bottom: 15px;
  width: 100%;
}

.input-wrapper {
  position: relative;
  width: 100%;
}

.input-group input {
  width: 100%;
  padding: 12px 40px 12px 40px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  box-sizing: border-box;
}

.input-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  color: #777;
  z-index: 1;
}

.input-icon img {
  width: 24px;
  height: 24px;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  font-size: 18px;
  color: #000;
  z-index: 1;
}

.error-message {
  color: #d32f2f;
  font-size: 0.8rem;
  margin-top: 5px;
  margin-bottom: 0;
  display: block;
  width: 100%;
  text-align: left;
}

.input-error {
  border: 2px solid #d32f2f !important;
  background: #fff0f0 !important;
}

/* Login button */
.login-button {
  font-family: 'Roboto', sans-serif;
  font-weight: bold;
  font-size: 16px;
  width: 100%;
  padding: 12px;
  background-color: #007bff;
  border: none;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  margin-bottom: 20px;
}

/* Sign-up link */
.signup-link {
  text-align: center;
  margin-top: 10px;
}

.signup-link-text {
  color: #007bff;
  text-decoration: none;
}

.signup-link-text:hover {
  text-decoration: underline;
}

/* Image styling */
.login-image {
  width: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-image img {
  width: 100%;
  height: auto;
  border-radius: 10px;
}

/* Ensure there's no margin around the body and html */
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  font-family: 'Arial', sans-serif;
}
</style>
