<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 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. Verifica tu internet.'
    } else if (error.response.status === 401) {
      errorMessage.value = 'Credenciales inválidas.'
    } else {
      errorMessage.value = error.response?.data?.detail || 'Error en el servidor.'
    }
  } finally {
    isLoading.value = false
  }
}

const handleGoogleLogin = async () => {
  isLoading.value = true
  errorMessage.value = ''
  
  try {
    const { token } = await signInWithGoogle()
    const response = await authService.googleLogin(token)
    
    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) {
    errorMessage.value = 'Error al iniciar sesión con Google.'
    console.error(error)
  } finally {
    isLoading.value = false
  }
}
</script>

<template>
  <div class="login-hud">
    <!-- Google Login Button (Featured) -->
    <button 
      @click="handleGoogleLogin"
      class="w-full mb-8 h-14 bg-white dark:bg-zinc-800 rounded-2xl flex items-center justify-center gap-3 border border-slate-200 dark:border-white/10 shadow-sm active:scale-95 transition-all group"
    >
      <img src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg" class="size-6" alt="Google">
      <span class="text-sm font-black text-slate-700 dark:text-gray-200 uppercase tracking-tight">Continuar con Google</span>
      <div class="absolute inset-0 rounded-2xl border-2 border-primary opacity-0 group-hover:opacity-100 transition-opacity"></div>
    </button>

    <div class="flex items-center gap-4 mb-8">
      <div class="h-px flex-1 bg-white/5"></div>
      <span class="text-[10px] font-black text-slate-500 uppercase tracking-widest">O entrar con email</span>
      <div class="h-px flex-1 bg-white/5"></div>
    </div>

    <form @submit.prevent="handleLogin" class="space-y-4">
      <div class="space-y-1.5">
        <label class="text-[10px] font-black text-primary uppercase tracking-widest ml-1">Terminal de Correo</label>
        <div class="relative group">
          <span class="material-icons absolute left-4 top-1/2 -translate-y-1/2 text-primary/40 text-sm">alternate_email</span>
          <input 
            type="email" 
            v-model="email" 
            placeholder="ACCESS_ID@SIBU.COM" 
            required 
            class="w-full pl-12 pr-4 h-14 bg-white/5 border border-white/10 rounded-2xl text-white font-bold placeholder:text-slate-600 focus:border-primary focus:ring-0 transition-all uppercase text-sm"
          />
        </div>
      </div>
      
      <div class="space-y-1.5">
        <label class="text-[10px] font-black text-primary uppercase tracking-widest ml-1">Código de Acceso</label>
        <div class="relative group">
          <span class="material-icons absolute left-4 top-1/2 -translate-y-1/2 text-primary/40 text-sm">lock_open</span>
          <input 
            type="password" 
            v-model="password" 
            placeholder="••••••••" 
            required 
            class="w-full pl-12 pr-4 h-14 bg-white/5 border border-white/10 rounded-2xl text-white font-bold focus:border-primary focus:ring-0 transition-all text-sm"
          />
        </div>
      </div>
      
      <div class="flex items-center justify-between pt-2">
        <label class="flex items-center gap-2 cursor-pointer group">
          <input type="checkbox" v-model="keepSession" class="hidden" />
          <div class="size-5 rounded-lg border-2 border-white/10 flex items-center justify-center transition-colors" :class="keepSession ? 'bg-primary border-primary' : ''">
            <span class="material-icons text-slate-900 text-xs" v-if="keepSession">check</span>
          </div>
          <span class="text-[10px] font-bold text-slate-500 uppercase">Mantener sesión</span>
        </label>
      </div>
      
      <p v-if="errorMessage" class="text-xs font-bold text-red-500 uppercase tracking-tight text-center">{{ errorMessage }}</p>
      
      <button 
        type="submit" 
        class="w-full h-14 bg-primary text-slate-900 rounded-2xl font-black uppercase tracking-[0.2em] text-xs shadow-xl shadow-primary/20 active:scale-95 transition-all mt-4"
        :disabled="isLoading"
      >
        {{ isLoading ? 'Validando...' : 'Acceder al Sistema' }}
      </button>
    </form>
    
    <div class="mt-8 text-center">
      <p class="text-[11px] font-bold text-slate-500 uppercase">
        ¿Nuevo en la red? 
        <button @click="emit('toggle')" class="text-primary hover:underline ml-1">Crear Registro</button>
      </p>
    </div>
  </div>
</template>

<style scoped>
input::placeholder {
  letter-spacing: 0.1em;
}
</style>
