import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-login-page',
  standalone: false,
  templateUrl: './login-page.component.html',
  styleUrls: ['./login-page.component.css'],
})
export class LoginPageComponent implements OnInit {
  @Input() brandName = 'Contoso';
  @Input() subtitle = 'to your account';
  @Input() mode = '';
  @Output() signedIn = new EventEmitter<any>();

  faCoffee = faCoffee;
  loginForm!: FormGroup;
  busy = false;
  message = '';

  constructor(
   private router: Router
  ) {}

  ngOnInit(): void {
    this.setupFormControl();
  }

  setupFormControl(): void {
    this.loginForm = new FormGroup({
      username: new FormControl('',[Validators.required, Validators.maxLength(100)]),
      password: new FormControl( '', [Validators.required, Validators.maxLength(50)]),
      remember: new FormControl(false)
    });
  }

  signIn(): void {
    if (this.loginForm.invalid) return;
    this.signedIn.emit(this.loginForm.value);
  }

  async useBiometric(): Promise<void> {
    this.message = '';
    if (!('credentials' in navigator) || !('get' in (navigator as any).credentials)) {
      this.message = 'Biometric authentication is not available on this device/browser.';
      return;
    }

    try {
      this.busy = true;
      // Example WebAuthn / PublicKeyCredential call. In a real application,
      // you must obtain the challenge and allowedCredentials from your server.
      const publicKeyCredentialRequestOptions = {
        // challenge must be provided by server as ArrayBuffer
        challenge: Uint8Array.from('server-provided-challenge', c => c.charCodeAt(0)).buffer,
        timeout: 60000,
        userVerification: 'preferred',
      } as any;

      const credential: any = await (navigator as any).credentials.get({
        publicKey: publicKeyCredentialRequestOptions,
      });

      // Send credential to server for verification (not implemented here).
      // Example: await this.authService.verifyWebAuthn(credential);

      // On success:
      this.signedIn.emit({ email: '', remember: true });
    } catch (err: any) {
      this.message = err?.message || 'Biometric sign-in cancelled or failed.';
    } finally {
      this.busy = false;
    }
  }

  forgotPassword(): void {
    // emit or navigate
    this.router.navigate(['/login/forgot-password']);
  }

  createAccount(): void {
    this.message = 'Create account flow not implemented.';
  }

  privacy(): void {
    this.router.navigate(['/license']);
  }
}
