import { Component, ElementRef, ViewChild, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router'; // <-- Router imported for navigation

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './login.html',
  styleUrls: ['./login.css']
})
export class LoginComponent {
  loginForm: FormGroup;
  focusedField: 'email' | 'password' | null = null;

  @ViewChild('emailInput') emailInputRef!: ElementRef<HTMLInputElement>;
  @ViewChild('passwordInput') passwordInputRef!: ElementRef<HTMLInputElement>;

  constructor(
    private fb: FormBuilder,
    private cdRef: ChangeDetectorRef,
    private router: Router // <-- injected Router for navigation
  ) {
    this.loginForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }

  setFocus(field: 'email' | 'password'): void {
    this.focusedField = field;
  }

  onNumpadClick(value: string): void {
    if (!this.focusedField) return;

    const control = this.loginForm.get(this.focusedField);
    const current = control?.value || '';
    const newValue = current + value;

    control?.setValue(newValue);

    const inputRef = this.focusedField === 'email' ? this.emailInputRef : this.passwordInputRef;
    inputRef.nativeElement.value = newValue;

    setTimeout(() => {
      const el = inputRef.nativeElement;
      el.focus();
      el.setSelectionRange(newValue.length, newValue.length);
    }, 0);

    this.cdRef.detectChanges();
  }

  onBackspace(): void {
    if (!this.focusedField) return;

    const control = this.loginForm.get(this.focusedField);
    const current = control?.value || '';
    const newValue = current.slice(0, -1);

    control?.setValue(newValue);

    const inputRef = this.focusedField === 'email' ? this.emailInputRef : this.passwordInputRef;
    inputRef.nativeElement.value = newValue;

    setTimeout(() => {
      const el = inputRef.nativeElement;
      el.focus();
      el.setSelectionRange(newValue.length, newValue.length);
    }, 0);

    this.cdRef.detectChanges();
  }

  onSubmit(): void {
    if (this.loginForm.invalid) {
      this.loginForm.markAllAsTouched(); // Show all validation errors
      return;
    }

    console.log('Login successful:', this.loginForm.value);

    // Navigate to landing page
    this.router.navigate(['/landing']);
  }
}
