import { CommonModule } from '@angular/common';
import {
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnInit,
  Output,
} from '@angular/core';
import { Subscription } from 'rxjs';
import { ModalService } from '../../services/modal/modal.service';

@Component({
  selector: 'app-confirm-modal',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './confirm-modal.component.html',
})
export class ConfirmModalComponent implements OnInit, OnDestroy {
  @Input() modalId: string = 'confirm-modal';
  @Input() message: string = 'Es-tu sûr de vouloir supprimer ?';
  @Output() confirmed = new EventEmitter<void>();
  @Output() cancelled = new EventEmitter<void>();

  isOpen = false;
  private subscription!: Subscription;

  constructor(private modalService: ModalService) {}

  ngOnInit() {
    this.subscription = this.modalService
      .getModalState(this.modalId)
      .subscribe((state) => {
        this.isOpen = state;
        if (state) {
          setTimeout(() => this.moveModalToBody(), 0);
        }
      });
  }

  ngAfterViewInit() {
    // Appel initial pour déplacer le modal
    this.moveModalToBody();
  }

  ngOnDestroy() {
    this.subscription?.unsubscribe();
  }

  confirm() {
    this.confirmed.emit();
    this.modalService.closeModal(this.modalId);
  }

  cancel() {
    this.cancelled.emit();
    this.modalService.closeModal(this.modalId);
  }

  closeModal() {
    this.isOpen = false;
    this.modalService.closeModal(this.modalId);
  }

  private moveModalToBody(): void {
    const modal = document.getElementById('confirm-modal');
    if (modal && modal.parentElement !== document.body) {
      document.body.appendChild(modal);
    }
    const bg = document.getElementById('confirm-modal-background');
    if (bg && bg.parentElement !== document.body) {
      document.body.appendChild(bg);
    }
  }
}
