import { Component, signal, inject } from '@angular/core';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  private router = inject(Router);

  email = signal('');
  password = signal('');
  errorMsg = signal<string>('');
  loading = signal(false);

  getVal(event: Event): string {
    return (event.target as HTMLInputElement).value;
  }

  onSubmit(event: Event) {
    event.preventDefault();
    this.loginLocal();
  }

  loginLocal() {
    const em = this.email();
    const pw = this.password();

    if (!em || !pw) {
      this.errorMsg.set('Por favor ingresa tu correo y contraseña corporativos.');
      return;
    }

    this.loading.set(true);

    // Simulate authentication delay
    setTimeout(() => {
      if (em.includes('admin') || em.includes('App') || em.includes('@')) {
        const userName = em.split('@')[0];
        const displayName = userName.charAt(0).toUpperCase() + userName.slice(1);

        localStorage.setItem('App_token', 'local-mock-jwt-token-998822');
        localStorage.setItem('App_user', JSON.stringify({
          name: displayName,
          email: em,
          role: 'Consortium Manager',
          avatar: displayName.substring(0, 2).toUpperCase()
        }));

        this.router.navigate(['/dashboard']);
      } else {
        this.errorMsg.set('Credenciales no válidas. Prueba con Active Directory SSO.');
        this.loading.set(false);
      }
    }, 600);
  }

  loginSSO() {
    this.loading.set(true);

    setTimeout(() => {
      localStorage.setItem('App_token', 'ad-jwt-token-microsoft-entra-id-2026');
      localStorage.setItem('App_user', JSON.stringify({
        name: 'Jess Miller',
        email: 'jess.miller@App-consortium.com',
        role: 'Chief Architect & Director',
        avatar: 'JM'
      }));
      this.router.navigate(['/dashboard']);
    }, 500);
  }
}
