import { Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
  FormControl,
  Validators,
  FormsModule,
  ReactiveFormsModule,
  NgForm,
} from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { merge } from 'rxjs';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { CommonModule } from '@angular/common';
import { UserService } from 'src/app/services/user.service';
import { User } from 'src/app/models/user.model';

@Component({
  selector: 'app-auth',
  templateUrl: './login.component.html',
  styleUrl: './login.component.css',
  standalone: true,
  imports: [
    MatFormFieldModule,
    MatInputModule,
    FormsModule,
    ReactiveFormsModule,
    MatButtonModule,
    MatIconModule,
    CommonModule,
  ],
})
export class LoginComponent {
  hide = true;

  email = new FormControl('', [Validators.required, Validators.email]);

  login = new FormControl('', [Validators.required]);

  password = new FormControl('', [Validators.required]);

  errorMessage = '';

  successLogin = '';
  errorLogin = '';

  constructor(private userService: UserService) {
    merge(this.email.statusChanges, this.email.valueChanges).pipe(
      takeUntilDestroyed()
    );
  }

  loginAction() {
    console.log('login user :', this.login.value);

    const form: any = {
      value: {
        login: this.login.value,
        password: this.password.value,
      },
    };
    this.userService.loginUser(form).subscribe((response) => {
      console.log('response :', response);
      if ((response as any).success) {
        this.successLogin = 'Vous êtes connecté.';
        this.errorLogin = '';
      } else {
        this.errorLogin = "L'authentification a échoué.";
        this.successLogin = '';
      }
    });
  }
}
