import {Component, EventEmitter, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {mergeMap, Subscription} from 'rxjs';
import {PostService} from '../../services/post.service';
import {MessageService} from 'primeng/api';
import {EditorModule} from 'primeng/editor';
import {AuthorService} from '../../services/author.service';
import {Author} from '../../models/author';
import {Router} from '@angular/router';
import {PostFormComponent} from '../../components/post-form/post-form.component';
import {AuthService} from '../../auth.service';

@Component({
  selector: 'app-new-post',
  standalone: true,
  imports: [
    HeaderComponent,
    ReactiveFormsModule,
    InputTextModule,
    FileUploadModule,
    EditorModule,
    PostFormComponent,
  ],
  templateUrl: './new-post.component.html',
  styleUrl: './new-post.component.css'
})
export class NewPostComponent implements OnDestroy {
  subs: Subscription[] = []
  actualAuthor: Author | undefined;
  uploadedFile: File | undefined;
  form: FormGroup;

  constructor(private formBuilder: FormBuilder,
              private postService: PostService,
              private authorService: AuthorService,
              private messageService: MessageService,
              private authService: AuthService,
              private router: Router) {
    this.form = this.formBuilder.group({
      description: ['', [Validators.required, Validators.maxLength(512)]],
      title: ['', [Validators.required, Validators.maxLength(50)]],
      body: ['', [Validators.required]],
      category: ['', [Validators.required, Validators.maxLength(50)]],
    });
    if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
      const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
      if (authenticatedAuthor) {
        this.actualAuthor = authenticatedAuthor;
      }
    } else {
      this.authService.checkSessionExpiration();
    }
  }

  onSelected(event: FileSelectEvent) {
    if (event.currentFiles && event.currentFiles.length > 0) {
      this.uploadedFile = event.currentFiles[0];
    }
  }

  onSubmit() {
    const formData = this.form.value;

    if (this.uploadedFile && this.form.status === 'VALID') {
      const postToPost: any = { // LOL
        body: formData.body as string,
        description: formData.description as string,
        title: formData.title as string,
        category: formData.category as string
      };

      const authenticatedAuthor = this.authService.getAuthenticatedAuthorToken();
      if (authenticatedAuthor) {
        this.subs.push(
          this.postService.createPost(postToPost, authenticatedAuthor).pipe(
            mergeMap(post =>
              this.authorService.attributePost(this.actualAuthor?.id, post.id, authenticatedAuthor).pipe(
                mergeMap((_) =>
                  this.postService.changeIllustration(post.id, this.uploadedFile, authenticatedAuthor),
                )
              )
            )
          ).subscribe({
            next: () => {
              this.router.navigate(['/']).then(() => {
                this.successMessage('Succès', 'Post créé avec succès')
              });
            },
            error: (err) => {
              this.failureMessage('Erreur', err.error.message);
            }
          })
        );
      } else {
        console.error("Profil mal chargé")
      }
    }
  }

  successMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'success',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }

  failureMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'error',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }

  ngOnDestroy(): void {
    this.subs.forEach(sub => sub.unsubscribe());
  }

}
