import { Component, effect, inject, Input, OnInit, 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/adapters/users/user.facade';
import { ActionType } from '@app/domain/action-type.util';
import { LoadingComponent } from '@app/shared/components/loading/loading.component';
import { NgClass, NgTemplateOutlet } from '@angular/common';

@Component({
  selector: 'app-user-form',
  standalone: true,
  imports: [ReactiveFormsModule, LoadingComponent, NgTemplateOutlet, NgClass],
  providers: [UserFacade],
  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 }) userId: string | undefined = undefined;

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

  protected readonly user = this.facade.user;
  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) {
        switch (this.loading().action) {
          case ActionType.UPDATE:
            message = `Vos informations personnelles ont bien été modifier !`;
            if (this.onSubmitted()) {
              this.customToast(ActionType.UPDATE, message);
            }
            break;
          case ActionType.READ:
            this.userForm.setValue({
              firstname: this.user().name.split(' ').slice(0, -1).join(' ') ?? '',
              name: this.user().name.split(' ').slice(-1)[0] ?? '',
            });
            break;
        }
      }
    });
  }
  ngOnInit(): void {
    if (this.userId !== undefined) {
      this.facade.loadOne(this.userId!);
    }

    this.userForm = this.fb.group({
      firstname: new FormControl('', [Validators.required]),
      name: new FormControl('', [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.userId!, 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,
      }
    );
  }
}
