import {
  Component,
  effect,
  inject,
  Input,
  OnChanges,
  OnInit,
  output,
  SimpleChanges,
} from '@angular/core';
import { FormBuilder, FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { PaginatorModule } from 'primeng/paginator';
import { ProjectPictureFormComponent } from '@app/shared/components/project-picture-form/project-picture-form.component';
import { ToastrService } from 'ngx-toastr';
import { AuthService } from '@app/core/services/authentication/auth.service';
import { ProjectFacade } from '@app/ui/projects/project.facade';
import { CreateProjectDto } from '@app/domain/projects/dto/create-project.dto';
import { ActionType } from '@app/domain/action-type.util';
import { LoadingComponent } from '@app/shared/components/loading/loading.component';

@Component({
  selector: 'app-my-profile-update-project-form',
  standalone: true,
  imports: [PaginatorModule, ReactiveFormsModule, ProjectPictureFormComponent, LoadingComponent],
  templateUrl: './my-profile-update-project-form.component.html',
  styleUrl: './my-profile-update-project-form.component.scss',
})
export class MyProfileUpdateProjectFormComponent implements OnInit, OnChanges {
  @Input({ required: true }) projectId: string | null = null;

  private readonly toastrService = inject(ToastrService);
  private readonly authService = inject(AuthService);

  private readonly projectFacade = new ProjectFacade();
  protected readonly ActionType = ActionType;
  protected readonly project = this.projectFacade.project;
  protected readonly loading = this.projectFacade.loading;
  protected readonly error = this.projectFacade.error;

  private readonly formBuilder = inject(FormBuilder);

  protected projectForm = this.formBuilder.group({
    nom: new FormControl('', [Validators.required]),
    description: new FormControl('', [Validators.required]),
    lien: new FormControl(''),
  });

  formIsUpdated = output<string | null>();

  constructor() {
    let message = '';
    effect(() => {
      if (!this.loading().isLoading) {
        switch (this.loading().action) {
          case ActionType.CREATE:
            message = `Le projet ${this.projectForm.getRawValue().nom} a bien été créer !`;
            this.customToast(ActionType.CREATE, message);
            break;
          case ActionType.UPDATE:
            message = `Les informations du projet ${this.projectForm.getRawValue().nom} ont bien été modifier !`;
            this.customToast(ActionType.UPDATE, message);
            break;
        }

        if (this.project() !== undefined) {
          this.projectForm.setValue({
            nom: this.project().nom ?? '',
            description: this.project().description ?? '',
            lien: this.project().lien ?? '',
          });
        }
      }
    });
  }

  ngOnInit(): void {
    if (this.projectId == 'add'.toLowerCase()) {
      this.projectForm.setValue({
        nom: '',
        description: '',
        lien: '',
      });
    }

    if (this.projectId != null && this.projectId != 'add'.toLowerCase()) {
      this.projectFacade.loadOne(this.projectId);
    }
  }

  onSubmit() {
    if (this.projectForm.invalid) {
      return;
    }

    if (this.projectId != null && this.projectId != 'add'.toLowerCase()) {
      // Update
      this.projectFacade.update(this.project()!.id, this.projectForm.getRawValue());
    } else {
      // Create
      const projectDto: CreateProjectDto = {
        ...this.projectForm.getRawValue(),
        utilisateur: this.authService.user()!.record!.id,
      } as CreateProjectDto;

      this.projectFacade.create(projectDto);
    }
  }

  ngOnChanges(changes: SimpleChanges): void {
    this.projectId = changes['projectId'].currentValue;
    this.ngOnInit();
  }

  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.formIsUpdated.emit(this.project()!.id);
    this.toastrService.success(
      `${message}`,
      `${action === ActionType.UPDATE ? 'Mise à jour' : 'Nouveau projet'}`,
      {
        closeButton: true,
        progressAnimation: 'decreasing',
        progressBar: true,
      }
    );
  }
}
