import {Component, Input, OnDestroy} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {InputTextareaModule} from 'primeng/inputtextarea';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
import {mergeMap, Subscription} from 'rxjs';
import {PostService} from '../../services/post.service';
import {CookieService} from 'ngx-cookie-service';
import {MessageService} from 'primeng/api';
import {EditorModule} from 'primeng/editor';
import {Router} from '@angular/router';
import {Author} from '../../models/author';
import {AuthorService} from '../../services/author.service';

@Component({
  selector: 'app-post-form',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    InputTextModule,
    InputTextareaModule,
    FileUploadModule,
    EditorModule
  ],
  templateUrl: './post-form.component.html',
  styleUrls: ['./post-form.component.css']
})
export class PostFormComponent implements OnDestroy {
  @Input() postId: bigint | undefined;
  @Input() isUpdateMode: boolean = false;
  @Input() actualAuthor: Author | undefined;
  @Input() title: string = '';
  @Input() category: string = '';
  @Input() description: string = '';
  @Input() body: string = '';
  subs: Subscription[] = [];
  form: FormGroup;
  uploadedFile: File | undefined;
  editorModules = {
    toolbar: [
      ['bold', 'italic', 'underline', 'code'], // Styles de texte
      [{header: [2, false]}], // Permet d'ajouter un `<h2>`
      [{list: 'ordered'}, {list: 'bullet'}], // Listes
      ['link', 'image', 'video'], // Ajout de liens et images
    ],
  };

  constructor(
    private formBuilder: FormBuilder,
    private postService: PostService,
    private authorService: AuthorService,
    private cookieService: CookieService,
    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.isUpdateMode && this.postId) {
      this.loadPostData();
    }
  }

  loadPostData(): void {
    if (this.postId) {
      this.subs.push(
        this.postService.getPost(this.postId).subscribe({
          next: (post) => {
            this.form.patchValue({
              title: post.title,
              description: post.description,
              body: post.body,
              category: post.category
            });
          },
          error: (err) => {
            this.failureMessage('Erreur', `Impossible de charger le post : ${err.message}`);
          }
        })
      );
    }
  }

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

  onSubmit(): void {
    if (this.form.valid && this.uploadedFile) {
      const formData = this.form.value;
      // this.transformParagraphs()
      const postData: any = {
        title: formData.title,
        description: formData.description,
        body: formData.body,
        category: formData.category
      };

      if (this.isUpdateMode && this.postId) {
        this.subs.push(
          this.postService.updatePost(this.postId, postData, this.cookieService.get('token')).pipe(
            mergeMap((_) => {
              return this.postService.changeIllustration(this.postId, this.uploadedFile, this.cookieService.get('token'));
            })
          ).subscribe({
            next: (_) => this.successMessage('Succès', 'Post créé avec succès'),
            error: (err) => this.failureMessage('Erreur', err.message)
          })
        );
      } else {
        this.subs.push(
          this.postService.createPost(postData, 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)
          })
        );
      }
    }
  }

  choose(callback: Function) {
    callback();
  }

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

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

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