import { Component, effect, inject, Input, OnInit, output, signal } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { User } from '@app/domain/users/user.model';
import { UntilDestroy } from '@ngneat/until-destroy';
import { ToastrService } from 'ngx-toastr';
import { UserFacade } from '@app/ui/users/user.facade';
import { ActionType } from '@app/domain/action-type.util';
import { LoadingComponent } from '@app/shared/components/loading/loading.component';
import { NgTemplateOutlet } from '@angular/common';

@Component({
  selector: 'app-user-form',
  standalone: true,
  imports: [ReactiveFormsModule, LoadingComponent, NgTemplateOutlet],
  templateUrl: './user-form.component.html',
  styleUrl: './user-form.component.scss',
})
@UntilDestroy()
export class UserFormComponent implements OnInit {
  private readonly toastrService = inject(ToastrService);
  private readonly facade = inject(UserFacade);
  protected readonly ActionType = ActionType;

  @Input({ required: true }) user: User | undefined = undefined;
  onFormSubmitted = output<any>();

  private fb = inject(FormBuilder);
  protected userForm!: FormGroup;

  protected readonly loading = this.facade.loading;
  protected readonly error = this.facade.error;
  protected onSubmitted = signal<boolean>(false);

  constructor() {
    let message = '';

    effect(() => {
      if (!this.loading().isLoading && this.onSubmitted()) {
        switch (this.loading().action) {
          case ActionType.UPDATE:
            message = `Vos informations personnelles ont bien été modifier !`;
            this.customToast(ActionType.UPDATE, message);
            this.onSubmitted.set(false);
            break;
        }
      }
    });
  }
  ngOnInit(): void {
    this.userForm = this.fb.group({
      firstname: new FormControl(this.user?.name?.split(' ').slice(0, -1).join(' ') ?? '', [
        Validators.required,
      ]),
      name: new FormControl(this.user?.name?.split(' ').slice(-1)[0] ?? '', [Validators.required]),
    });
  }

  onUserFormSubmit() {
    if (this.userForm.invalid) {
      return;
    }

    const data = {
      username:
        this.userForm.getRawValue()!.firstname!.split(' ')[0] + this.userForm.getRawValue()!.name!,
      name: this.userForm.getRawValue()!.firstname! + ' ' + this.userForm.getRawValue()!.name!,
    } as User;

    this.facade.update(this.user?.id!, data);

    this.onFormSubmitted.emit(data);
    this.onSubmitted.set(true);
  }

  private customToast(action: ActionType, message: string): void {
    if (this.error().hasError) {
      this.toastrService.error(
        `Une erreur s'est produite, veuillez réessayer ulterieurement`,
        `Erreur`,
        {
          closeButton: true,
          progressAnimation: 'decreasing',
          progressBar: true,
        }
      );
      return;
    }

    this.toastrService.success(
      `${message}`,
      `${action === ActionType.UPDATE ? 'Mise à jour' : ''}`,
      {
        closeButton: true,
        progressAnimation: 'decreasing',
        progressBar: true,
      }
    );
  }
}
