<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="form-section">
        <div class="logo-top">
          <img 
            src="/icons/logo2.png"
            alt="Company Logo" 
            class="logo-image" 
          />
        </div>

        <!-- Login Form -->
        <div class="login-card">
          <div class="form-container">
            <h3 class="login-title">Bem-vindo</h3> 
            <p class="login-sub-title">Faça login para continuar</p>
            <form @submit.prevent="handleLogin" class="login-form">

              <!-- Email Input -->
              <div class="form-group">
                <label for="email">Email</label>
                <input 
                  id="email"
                  v-model="email" 
                  type="text" 
                  placeholder="Entrar com seu e-mail ou usuário"
                  :class="{'input-error': emailError}"
                  @blur="validateEmail"
                />
                <span v-if="emailError" class="error-message">
                  {{ emailError }}
                </span>
              </div>

              <!-- Password Input -->
              <div class="form-group">
                <label for="password">Senha</label>
                <input 
                  id="password"
                  v-model="password" 
                  type="password" 
                  placeholder="Insira sua senha"
                  :class="{'input-error': passwordError}"
                  @blur="validatePassword"
                />
                <span v-if="passwordError" class="error-message">
                  {{ passwordError }}
                </span>
              </div>

              <!-- Login Button -->
              <div class="button-group">
                <button 
                  type="submit" 
                  class="btn btn-primary"
                  :disabled="!isLoginFormValid"
                >
                  Login
                </button>

                <!-- SSO Button -->
                <button 
                  type="button" 
                  class="btn btn-secondary"
                  @click="handleSSO"
                  :disabled="!isLoginFormValid"
                >
                  SSO Login
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'

// Router and Store
const router = useRouter()
const authStore = useAuthStore()

// Login Form Fields
const email = ref('')
const password = ref('')
const emailError = ref('')
const passwordError = ref('')

// Validation Methods - Login
const validateEmail = () => {
  const emailRegex = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$|^[a-zA-Z0-9_.-]+$/
  
  if (!email.value) {
    emailError.value = 'Please enter your email or username'
    return false
  } else if (!emailRegex.test(email.value)) {
    emailError.value = 'Invalid email or username format'
    return false
  } else {
    emailError.value = ''
    return true
  }
}

const validatePassword = () => {
  if (!password.value) {
    passwordError.value = 'Please enter your password'
    return false
  } else {
    passwordError.value = ''
    return true
  }
}

// Watch for changes to validate in real-time
watch(email, () => { if (email.value) validateEmail() })
watch(password, () => { if (password.value) validatePassword() })

// Form Validation
const isLoginFormValid = computed(() => {
  return email.value && password.value && !emailError.value && !passwordError.value
})

// Login Handlers
const handleLogin = async () => {
  if (isLoginFormValid.value) {
    try {
      await authStore.login(email.value, password.value)
      router.push('/dashboard/home')
    } catch (error) {
      alert('Login failed. Please check your credentials.')
    }
  }
}

const handleSSO = async () => {
  if (isLoginFormValid.value) {
    try {
      await authStore.sso(email.value, password.value)
      router.push('/dashboard/chat')
    } catch (error) {
      alert('SSO login failed. Please check your credentials.')
    }
  }
}
</script>

<style scoped>
/* Mantendo os estilos do login */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-image: url('/icons/fundo2.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-wrapper {
  width: 70%;
  max-width: 600px;
  background-color: white;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 20px;
  overflow: hidden;
  padding: 2em;
}

.form-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.logo-top {
  display: flex;
  justify-content: center;
  margin-bottom: 0px;
}

.logo-image {
  max-width: 250px;
  height: auto;
}

.login-card {
  width: 100%;
}

.login-title {
  text-align: flex;
  color: #2eaacf;
  font-size: 23px;
}

.login-sub-title {
  text-align: flex;
  color: #2eaacf;
  font-size: 15px;
  margin-bottom: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 25px;
}

.input-error {
  border-color: red;
}

.error-message {
  color: red;
  font-size: 0.8rem;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 0rem;
}

.btn-primary {
  padding: 3px;
  background-color: #4cc9f0;
  color: white;
  border-radius: 10px;
}

.btn-secondary {
  padding: 3px;
  background-color: #f8f9fa;
  color: #4cc9f0;
  border-radius: 10px;
  border: 1px solid #4cc9f0;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>