<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { authService } from '@/services/authService'
import { useAuthStore } from '@/stores/auth'

defineProps<{
  onToggle: () => void
}>()

const email = ref('')
const password = ref('')
const keepSession = ref(false)
const isLoading = ref(false)
const errorMessage = ref('')
const router = useRouter()
const authStore = useAuthStore()

const handleLogin = async () => {
  isLoading.value = true
  errorMessage.value = ''
  
  try {
    const response = await authService.login({
      email: email.value,
      password: password.value,
      keep_session: keepSession.value
    })
    
    authStore.login(response.access_token, response.role, response.full_name)
    
    // Redirect based on role or home
    const role = response.role.toUpperCase()
    if (role === 'ADMIN') {
      router.push('/admin')
    } else if (role === 'DRIVER') {
      router.push('/driver')
    } else if (role === 'PROMOTER') {
      router.push('/promoter')
    } else {
      router.push('/map')
    }
  } catch (error: any) {
    if (!error.response) {
      errorMessage.value = `Error de conexión: No se pudo contactar con el servidor en ${authService.getApiUrl()}. Revisa si el backend está encendido y accesible desde este dispositivo.`
    } else if (error.response.status === 401) {
      errorMessage.value = 'Correo o contraseña incorrectos.'
    } else {
      errorMessage.value = error.response?.data?.detail || 'Error interno del servidor. Inténtalo más tarde.'
    }
  } finally {
    isLoading.value = false
  }
}
</script>

<template>
  <div class="login-form">
    <h2 class="auth-title">Iniciar Sesión</h2>
    
    <form @submit.prevent="handleLogin" class="form-container">
      <div class="form-group">
        <label for="email">Correo Electrónico</label>
        <input 
          type="email" 
          id="email" 
          v-model="email" 
          placeholder="ejemplo@correo.com" 
          required 
        />
      </div>
      
      <div class="form-group">
        <label for="password">Contraseña</label>
        <input 
          type="password" 
          id="password" 
          v-model="password" 
          placeholder="********" 
          required 
        />
      </div>
      
      <div class="form-options">
        <label class="checkbox-container">
          <input type="checkbox" v-model="keepSession" />
          <span class="checkmark"></span>
          Mantener sesión
        </label>
      </div>
      
      <p v-if="errorMessage" class="error-text">{{ errorMessage }}</p>
      
      <button type="submit" class="auth-button" :disabled="isLoading">
        <span v-if="isLoading">Cargando...</span>
        <span v-else>Entrar</span>
      </button>
    </form>
    
    <div class="auth-footer">
      <p>¿No tienes cuenta? <a @click.prevent="onToggle" href="#">Regístrate aquí</a></p>
    </div>
  </div>
</template>

<style scoped>
.login-form {
  width: 100%;
}

.auth-title {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 24px;
  color: var(--text-primary);
  text-align: center;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
}

input[type="email"],
input[type="password"] {
  padding: 12px;
  border-radius: 8px;
  border: 1px solid var(--border-color);
  background: var(--bg-secondary);
  color: var(--text-primary);
  font-size: 16px;
  transition: border-color 0.2s;
}

input:focus {
  outline: none;
  border-color: var(--accent-color);
}

.form-options {
  margin-top: 4px;
}

.checkbox-container {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
}

.auth-button {
  margin-top: 12px;
  padding: 14px;
  background: var(--accent-color);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s, background 0.2s;
}

.auth-button:hover:not(:disabled) {
  background: var(--accent-hover);
  transform: translateY(-2px);
}

.auth-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.error-text {
  color: #ef5350;
  font-size: 14px;
  margin: 0;
}

.auth-footer {
  margin-top: 24px;
  text-align: center;
  font-size: 14px;
  color: var(--text-secondary);
}

.auth-footer a {
  color: var(--accent-color);
  text-decoration: none;
  font-weight: 600;
  cursor: pointer;
}
</style>
