import {Component, OnInit, inject} from '@angular/core';
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormControl, UntypedFormGroup, Validators} from '@angular/forms';
import {UserService} from '../../../services/user/user.service';
import {faUserPlus} from '@fortawesome/free-solid-svg-icons';
import {CardComponent} from '../../../widget-modules/components/card/card.component';
import {MatFormField, MatLabel} from '@angular/material/form-field';
import {MatInput} from '@angular/material/input';
import {ButtonRowComponent} from '../../../widget-modules/components/button-row/button-row.component';
import {ButtonComponent} from '../../../widget-modules/components/button/button.component';

@Component({
  selector: 'app-new',
  templateUrl: './new.component.html',
  styleUrls: ['./new.component.less'],
  imports: [CardComponent, ReactiveFormsModule, MatFormField, MatLabel, MatInput, ButtonRowComponent, ButtonComponent],
})
export class NewComponent implements OnInit {
  private fb = inject(UntypedFormBuilder);
  private userService = inject(UserService);

  public form: UntypedFormGroup = this.fb.group({
    email: new UntypedFormControl(null, [Validators.required, Validators.email]),
    name: new UntypedFormControl(null, [Validators.required]),
    password: new UntypedFormControl(null, [Validators.required, Validators.minLength(6)]),
  });
  public faNewUser = faUserPlus;

  public ngOnInit(): void {
    this.form.reset();
  }

  public async onCreate(): Promise<void> {
    this.form.updateValueAndValidity();
    if (this.form.valid) {
      try {
        const value = this.form.value as {
          email: string;
          name: string;
          password: string;
        };
        await this.userService.createNewUser(value.email, value.name, value.password);
      } catch (ex) {
        console.error(ex);
      }
    }
  }
}
