import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { ApiFitService } from 'src/app/shared/services/api-fit/api-fit.service';
import { AuthService } from 'src/app/core/services/auth/auth.service';
import { AuthLogin } from 'src/app/shared/interfaces/services/api-fit/request/auth.interface';

import { InputType } from 'src/app/shared/components/input/input.component';
import { StoreService } from 'src/app/core/services/store/store.service';

interface InputFieldData {
  id: string;
  label: string;
  value: string;
  type: InputType;
  regex?: RegExp[];
  placeholder: string;
  isNullish: boolean;
  isValid: boolean;
  error?: string;
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent {
  readonly emailRegex = /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/;
  readonly usernameRegex = /^[a-z0-9._]+$/i;

  formData: InputFieldData[] = [
    {
      id: 'email',
      label: 'E-mail ou nome de usuário:',
      value: '',
      regex: [this.emailRegex, this.usernameRegex],
      type: 'text',
      placeholder: 'Digite seu e-mail ou nome de usuário...',
      isNullish: false,
      isValid: false,
      error: '',
    },
    {
      id: 'password',
      label: 'Senha:',
      value: '',
      type: 'password',
      placeholder: 'Digite sua senha...',
      isNullish: false,
      isValid: false,
      error: '',
    },
  ];

  constructor(
    private apiFitService: ApiFitService,
    private authService: AuthService,
    private storeService: StoreService,
    private router: Router
  ) {}

  ngOnInit(): void {
    const token = this.authService.getAuthorizationToken();

    if (token) {
      this.router.navigate(['/app/home']);
      return;
    }
  }

  isFormValid() {
    const passwordField = this.formData[1];
    if (passwordField?.value?.trim().length < 8) return false;

    return this.formData.every((d) => d.isValid || (d.isNullish && !d.value));
  }

  submitForm() {
    if (!this.isFormValid || !this.formData[0].value || !this.formData[1].value)
      return;

    const userIdentificator = this.formData[0].value.trim();
    const userPassword = this.formData[1].value.trim();

    const isEmail = this.emailRegex.test(userIdentificator);

    const loginData: AuthLogin = {
      password: userPassword,
    };

    isEmail
      ? (loginData.email = userIdentificator)
      : (loginData.username = userIdentificator);

    this.apiFitService.login(loginData).subscribe({
      next: (res) => {
        this.formData[1] = {
          ...this.formData[1],
          error: '',
        };

        this.authService.setAuthorizationToken(res.data.accessToken);
        this.storeService.setStore();
        this.router.navigate(['/app']);
      },
      error: () => {
        this.formData[1] = {
          ...this.formData[1],
          error: 'E-mail ou senha incorreto',
        };
      },
    });
  }
}
