// src/app/login/login.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {
  signInForm: FormGroup;
  passwordVisible: boolean = false;
  isLoading: boolean = false;
  showAlert: boolean = false;
  alert = { type: '', message: '' };

  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
    private router: Router
  ) {
    this.signInForm = this.fb.group({
      machineId: ['', Validators.required],
      password: ['', Validators.required],
      rememberMe: [false]
    });
  }

  togglePasswordVisibility() {
    this.passwordVisible = !this.passwordVisible;
  }

  signIn() {
    if (this.signInForm.invalid) {
      return;
    }

    this.isLoading = true;
    this.showAlert = false;

    const { machineId, password } = this.signInForm.value;

    this.authService.login(machineId, password).subscribe(
      (response: any) => {
        this.isLoading = false;
        if (response.message === 'Login successful') {
          this.authService.setLoggedInMachine(response.machine_id, response.id);
          this.router.navigate(['/machine-slots', response.machine_id]); // Redirect to dashboard on success
        }
      },
      (error) => {
        this.isLoading = false;
        this.showAlert = true;
        this.alert = {
          type: 'error',
          message: error.error.error || 'Login failed. Please try again.'
        };
      }
    );
  }
}