import {Component, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component';
import {FormBuilder, FormControl, FormGroup, ReactiveFormsModule, ValidationErrors, Validators} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {InputTextareaModule} from 'primeng/inputtextarea';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {mergeMap, Subscription, switchMap} from 'rxjs';
import {Post} from '../../models/post';
import {PostService} from '../../services/post.service';
import {CookieService} from 'ngx-cookie-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';

@Component({
  selector: 'app-new-post',
  standalone: true,
  imports: [
    HeaderComponent,
    ReactiveFormsModule,
    InputTextModule,
    InputTextareaModule,
    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 cookieService: CookieService,
              private authorService: AuthorService,
              private messageService: MessageService,
              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.cookieService.get("author")) {
      this.actualAuthor = JSON.parse(this.cookieService.get("author"));
    }
  }

  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
      };

      this.subs.push(
        this.postService.createPost(postToPost, this.cookieService.get("token")).pipe(
          mergeMap(post =>
            this.authorService.attributePost(this.actualAuthor?.id, post.id, this.cookieService.get("token")).pipe(
              mergeMap((_) =>
                this.postService.changeIllustration(post.id, this.uploadedFile, this.cookieService.get("token"))
              )
            )
          )
        ).subscribe({
          next: () => {
            this.router.navigate(['/']).then(() => {
              this.successMessage('Succès', 'Post créé avec succès')
            });
          },
          error: (err) => {
            this.failureMessage('Erreur', err.message);
          }
        })
      );
    }
  }

  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());
  }

}
