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

const emit = defineEmits(['toggle'])

const email = ref('')
const password = ref('')
const keepSession = ref(false)
const isLoading = ref(false)
const errorMessage = ref('')
const showPassword = ref(false)
const router = useRouter()
const authStore = useAuthStore()
const handleLogin = async () => {
  isLoading.value = true
  errorMessage.value = ''
  console.log('Iniciando Login con correo...')

  try {
    const response = await authService.login({
      email: email.value.trim().toLowerCase(),
      password: password.value,
      keep_session: keepSession.value
    })
    console.log('Backend login exitoso:', response)

    authStore.login(response.access_token, response.role, response.full_name)

    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) {
    console.error('Error Login detallado:', error)
    if (!error.response) {
      errorMessage.value = 'Error de conexión. Verifica tu internet o el estado del servidor.'
    } else if (error.response.status === 401) {
      errorMessage.value = 'Correo o contraseña incorrectos.'
    } else {
      errorMessage.value = `Error (${error.response.status}): ${error.response?.data?.detail || 'Error en el servidor.'}`
    }
  } finally {
    isLoading.value = false
  }
}

const handleGoogleLogin = async () => {
  isLoading.value = true
  errorMessage.value = ''
  console.log('Iniciando Google Login...')

  try {
    const { token } = await signInWithGoogle()
    console.log('Firebase token obtenido:', token ? 'SI' : 'NO (Redirecting...)')
    
    if (token) {
      const response = await authService.googleLogin(token)
      console.log('Backend Google login exitoso:', response)
      authStore.login(response.access_token, response.role, response.full_name)
      router.push('/map')
    }
  } catch (error: any) {
    console.error('Error Google Login:', error)
    errorMessage.value = `Error con Google: ${error.message || 'Error desconocido'}`
  } finally {
    isLoading.value = false
  }
}
</script>

<template>
  <div class="login-form">
    <!-- Google -->
    <button
      type="button"
      class="google-btn"
      :disabled="isLoading"
      @click="handleGoogleLogin"
    >
      <img src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg" width="20" height="20" alt="Google" />
      <span>Continuar con Google</span>
    </button>

    <div class="divider">
      <span class="divider-line"></span>
      <span class="divider-text">o con correo</span>
      <span class="divider-line"></span>
    </div>

    <!-- Formulario -->
    <form @submit.prevent="handleLogin">
      <!-- Email -->
      <div class="field">
        <label class="field-label" for="login-email">Correo electrónico</label>
        <div class="input-wrap">
          <span class="material-icons input-icon">alternate_email</span>
          <input
            id="login-email"
            type="email"
            v-model="email"
            placeholder="tu@correo.com"
            required
            autocomplete="email"
            class="field-input"
          />
        </div>
      </div>

      <!-- Contraseña -->
      <div class="field">
        <label class="field-label" for="login-password">Contraseña</label>
        <div class="input-wrap">
          <span class="material-icons input-icon">lock</span>
          <input
            id="login-password"
            :type="showPassword ? 'text' : 'password'"
            v-model="password"
            placeholder="••••••••"
            required
            autocomplete="current-password"
            class="field-input"
          />
          <button
            type="button"
            class="toggle-pw"
            @click="showPassword = !showPassword"
            tabindex="-1"
          >
            <span class="material-icons">{{ showPassword ? 'visibility_off' : 'visibility' }}</span>
          </button>
        </div>
      </div>

      <!-- Mantener sesión -->
      <label class="keep-session">
        <input type="checkbox" v-model="keepSession" class="keep-checkbox" />
        <span class="keep-box" :class="{ 'keep-box--on': keepSession }">
          <span v-if="keepSession" class="material-icons keep-check">check</span>
        </span>
        <span class="keep-label">Mantener sesión iniciada</span>
      </label>

      <!-- Error -->
      <p v-if="errorMessage" class="error-msg">
        <span class="material-icons error-icon">error_outline</span>
        {{ errorMessage }}
      </p>

      <!-- Botón enviar -->
      <button type="submit" class="submit-btn" :disabled="isLoading">
        <span v-if="isLoading" class="btn-spinner"></span>
        <span>{{ isLoading ? 'Ingresando...' : 'Iniciar Sesión' }}</span>
      </button>
    </form>

    <!-- Switch a registro -->
    <p class="switch-text">
      ¿No tienes cuenta?
      <button type="button" class="switch-link" @click="emit('toggle')">Regístrate aquí</button>
    </p>
  </div>
</template>

<style scoped>
.login-form {
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* ─── Google ─── */
.google-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  padding: 0.875rem;
  background: var(--bg-primary);
  border: 1.5px solid var(--border-color);
  border-radius: 0.875rem;
  color: var(--text-primary);
  font-size: 0.9375rem;
  font-weight: 700;
  font-family: inherit;
  cursor: pointer;
  transition: border-color 0.2s, background 0.2s;
}

.google-btn:hover:not(:disabled) {
  border-color: var(--active-color);
}

.google-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* ─── Divider ─── */
.divider {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.divider-line {
  flex: 1;
  height: 1px;
  background: var(--border-color);
}

.divider-text {
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--text-secondary);
  white-space: nowrap;
}

/* ─── Campos ─── */
.field {
  display: flex;
  flex-direction: column;
  gap: 0.375rem;
}

.field + .field {
  margin-top: 0.875rem;
}

.field-label {
  font-size: 0.75rem;
  font-weight: 700;
  color: var(--text-secondary);
  padding-left: 0.25rem;
}

.input-wrap {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 0.875rem;
  font-size: 1.125rem;
  color: var(--text-secondary);
  pointer-events: none;
}

.field-input {
  width: 100%;
  padding: 0.875rem 0.875rem 0.875rem 2.75rem;
  background: var(--bg-primary);
  border: 1.5px solid var(--border-color);
  border-radius: 0.875rem;
  color: var(--text-primary);
  font-size: 0.9375rem;
  font-weight: 500;
  font-family: inherit;
  outline: none;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.field-input::placeholder {
  color: var(--text-secondary);
  opacity: 0.5;
}

.field-input:focus {
  border-color: var(--active-color);
}

.toggle-pw {
  position: absolute;
  right: 0.875rem;
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 0;
}

.toggle-pw .material-icons {
  font-size: 1.125rem;
}

/* ─── Mantener sesión ─── */
.keep-session {
  display: flex;
  align-items: center;
  gap: 0.625rem;
  cursor: pointer;
  margin-top: 0.25rem;
}

.keep-checkbox {
  display: none;
}

.keep-box {
  width: 1.125rem;
  height: 1.125rem;
  border: 1.5px solid var(--border-color);
  border-radius: 0.375rem;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: background 0.15s, border-color 0.15s;
}

.keep-box--on {
  background: var(--active-color);
  border-color: var(--active-color);
}

.keep-check {
  font-size: 0.875rem;
  color: #101820;
}

.keep-label {
  font-size: 0.8125rem;
  font-weight: 600;
  color: var(--text-secondary);
}

/* ─── Error ─── */
.error-msg {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: rgba(239, 68, 68, 0.1);
  border: 1px solid rgba(239, 68, 68, 0.2);
  border-radius: 0.75rem;
  padding: 0.75rem 1rem;
  color: #ef4444;
  font-size: 0.875rem;
  font-weight: 600;
  margin: 0;
  margin-top: 0.5rem;
}

.error-icon {
  font-size: 1.125rem;
  flex-shrink: 0;
}

/* ─── Botón enviar ─── */
.submit-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 1rem;
  background: var(--active-color);
  color: #101820;
  border: none;
  border-radius: 0.875rem;
  font-size: 0.9375rem;
  font-weight: 800;
  font-family: inherit;
  cursor: pointer;
  transition: opacity 0.2s, transform 0.15s;
  margin-top: 1rem;
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.submit-btn:not(:disabled):active {
  transform: scale(0.98);
}

.btn-spinner {
  width: 1rem;
  height: 1rem;
  border: 2px solid rgba(16, 24, 32, 0.3);
  border-top-color: #101820;
  border-radius: 50%;
  animation: spin 0.7s linear infinite;
  flex-shrink: 0;
}

@keyframes spin { to { transform: rotate(360deg); } }

/* ─── Switch ─── */
.switch-text {
  text-align: center;
  font-size: 0.8125rem;
  font-weight: 600;
  color: var(--text-secondary);
  margin: 0;
}

.switch-link {
  background: none;
  border: none;
  color: var(--active-color);
  font-size: inherit;
  font-weight: 700;
  font-family: inherit;
  cursor: pointer;
  padding: 0;
  margin-left: 0.25rem;
  text-decoration: underline;
  text-underline-offset: 2px;
}
</style>
