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';

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

  loginError: string | null = null; // <-- 🔴 ADD THIS LINE

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

  constructor(
    private fb: FormBuilder,
    private cdRef: ChangeDetectorRef,
    private router: Router
  ) {
    this.loginForm = this.fb.group({
      email: ['', [Validators.required, Validators.pattern(/^\d{12}$/)]],
      password: ['', [Validators.required, Validators.pattern(/^\d{6}$/)]]
    });
  }

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

  formatUsernameDisplay(rawValue: string): string {
    return rawValue.replace(/(\d{4})(?=\d)/g, '$1-').slice(0, 14);
  }

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

    const control = this.loginForm.get(this.focusedField);
    const currentRaw = control?.value || '';
    const maxLength = this.focusedField === 'email' ? 12 : 6;

    if (currentRaw.length >= maxLength) return;

    const newRawValue = currentRaw + value;
    control?.setValue(newRawValue);

    const inputRef = this.focusedField === 'email' ? this.emailInputRef : this.passwordInputRef;
    const displayValue = this.focusedField === 'email'
      ? this.formatUsernameDisplay(newRawValue)
      : newRawValue;

    inputRef.nativeElement.value = displayValue;

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

    this.cdRef.detectChanges();
  }

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

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

    control?.setValue(newRawValue);

    const inputRef = this.focusedField === 'email' ? this.emailInputRef : this.passwordInputRef;
    const displayValue = this.focusedField === 'email'
      ? this.formatUsernameDisplay(newRawValue)
      : newRawValue;

    inputRef.nativeElement.value = displayValue;

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

    this.cdRef.detectChanges();
  }

  onSubmit(): void {
    if (this.loginForm.invalid) {
      this.loginForm.markAllAsTouched();
      return;
    }

    // const { email, password } = this.loginForm.value;

    // // 🔴 Replace this with real auth logic
    // if (email === '123456789012' && password === '123456') {
    //   this.loginError = null;
      console.log('Login successful:', this.loginForm.value);
      this.router.navigate(['/home']);
    // } else {
    //   this.loginError = 'Invalid username or password'; // 🔴 Show error
    // }
  }
}
