import { Component, OnInit } from '@angular/core';
import { BaseForm } from '../../../core/base/base-form';
import { ComponentBase } from '@core/base/common-base';
import {
  FormGroup,
  UntypedFormControl,
  UntypedFormGroup,
  Validators,
} from '@angular/forms';
import { AuthService } from '@core/services/authentication/auth.service';
import { takeUntil } from 'rxjs';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Store } from '@ngrx/store';
import { Profile, USER } from '../../../core/models/authenticcation.model';
import { ADD_PROFILE } from '../../../core/state/profile/profile.actions';

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.scss'],
})
export class SignInComponent extends ComponentBase implements BaseForm, OnInit {
  hide: boolean = true;
  form!: FormGroup;

  constructor(
    private readonly authService: AuthService,
    private readonly router: Router,
    private readonly toastr: ToastrService,
    private readonly store: Store<{ user: Profile }>
  ) {
    super();
  }

  ngOnInit(): void {
    this.initForm();
  }

  initForm(): void {
    this.form = new UntypedFormGroup({
      email: new UntypedFormControl(null, [
        Validators.email,
        Validators.required,
      ]),
      password: new UntypedFormControl(null, [Validators.required]),
    });
  }

  onSubmit(): void {
    if (super.submitValidity(this.form)) {
      this.loading = true;
      this.authService
        .Login(this.form.value)
        .pipe(takeUntil(this.destroy$))
        .subscribe(
          (response) => {
            localStorage.setItem('token', response.token!);
            localStorage.setItem('id', response.id!);
            this.store.dispatch(ADD_PROFILE({ user: response }));
            this.router.navigate(['/modules']);
            this.loading = false;
          },
          (err) => {
            this.loading = false;
          }
        );
    }
  }
}
