import {Component, OnDestroy, ViewContainerRef} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component';
import {TableModule} from 'primeng/table';
import {AuthorService} from '../../services/author.service';
import {Subscription} from 'rxjs';
import {Post} from '../../models/post';
import {Author} from '../../models/author';
import {MessageService} from 'primeng/api';
import {DatePipe} from '@angular/common';
import {Button} from 'primeng/button';
import {DialogModule} from 'primeng/dialog';
import {InputTextModule} from 'primeng/inputtext';
import {PostHomeComponent} from '../../components/post-home/post-home.component';
import {PostService} from '../../services/post.service';
import {PostFormComponent} from "../../components/post-form/post-form.component";
import {AuthService} from '../../auth.service';
import {PreviewModalComponent} from '../../components/modal/preview-modal/preview-modal.component';
import {UpdateModalComponent} from '../../components/modal/update-modal/update-modal.component';

@Component({
  selector: 'app-my-posts',
  standalone: true,
  imports: [
    HeaderComponent,
    TableModule,
    Button,
    DatePipe,
    DialogModule,
    InputTextModule,
    PostHomeComponent,
    PostFormComponent,
  ],
  templateUrl: './my-posts.component.html',
  styleUrl: './my-posts.component.css'
})
export class MyPostsComponent implements OnDestroy {
  subs: Subscription[] = [];
  updateDialogVisibility: boolean[] = [];
  deleteDialogVisibility: boolean[] = [];
  posts: Post[] = [];
  actualAuthor: Author | undefined;


  constructor(private authService: AuthService,
              private postService: PostService,
              private viewContainer: ViewContainerRef,
              private authorService: AuthorService,
              private messageService: MessageService) {
    const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
    if (authenticatedAuthor) {
      this.actualAuthor = authenticatedAuthor;
      this.authorService.getAuthorAvatar(this.actualAuthor.id).subscribe(avatar => this.actualAuthor!.profilePicture = avatar);
    }
    this.updatePosts();
  }

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

  updatePosts(): void {
    const authorToken = this.authService.getAuthenticatedAuthorToken()
    if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated() && authorToken) {
      this.authorService.getAuthorsPosts(this.actualAuthor?.id, authorToken).subscribe({
          next: posts => this.posts = posts,
          error: error => this.failureMessage("Erreur", error.error.message),
        }
      )
    } else {
      this.authService.checkSessionExpiration();
    }
  }

  deletePost(id: bigint, rowIndex: number) {
    const authorToken = this.authService.getAuthenticatedAuthorToken()
    if (authorToken) {
      this.postService.deletePost(id, authorToken).subscribe({
        next: (_) => {
          this.updatePosts()
          this.successMessage("Post supprimé", "Ce post a été supprimé avec succès")
        },
        error: error => this.failureMessage("Erreur", error.error.message),
      });
    }
    this.closeDialog(this.deleteDialogVisibility, rowIndex)
  }

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

  openDialogPreview(post: Post): void {
    const modalInstance = this.viewContainer.createComponent(PreviewModalComponent);
    modalInstance.setInput("post", post)
    modalInstance.setInput("username", this.actualAuthor?.name)
    modalInstance.setInput("profilePicture", this.actualAuthor?.profilePicture)
  }

  openDialogUpdate(post: Post): void {
    const modalInstance = this.viewContainer.createComponent(UpdateModalComponent);
    modalInstance.setInput("post", post)
    modalInstance.instance.updatedPost.subscribe(post => {
      console.log(this.posts.map(a => a.id).indexOf(post.id))
      this.posts[this.posts.map(a => a.id).indexOf(post.id)] = post
      this.posts = [... this.posts]
      modalInstance.destroy();
    });
  }

  openDialog(dialogBooleanTab: boolean[], index: number) {
    dialogBooleanTab[index] = true;
  }

  closeDialog(dialogBooleanTab: boolean[], index: number) {
    dialogBooleanTab[index] = false;
  }

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