import { Component, ElementRef, ViewChild, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@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
  ) {
    this.loginForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }

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

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

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

    // Set the form control value
    control?.setValue(newValue);

    // Set the input element value directly
    const inputRef = this.focusedField === 'email' ? this.emailInputRef : this.passwordInputRef;
    inputRef.nativeElement.value = newValue;

    // Refocus to fix cursor position
    setTimeout(() => inputRef.nativeElement.focus(), 0);

    // Trigger change detection
    this.cdRef.detectChanges();
  }

  onBackspace() {
    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(() => inputRef.nativeElement.focus(), 0);
    this.cdRef.detectChanges();
  }

  onSubmit() {
    console.log(this.loginForm.value);
  }
}
