import { CommonModule } from '@angular/common';
import { Component, Input } from '@angular/core';
import * as L from 'leaflet';
import { Pin } from '../../model/Pin';
import { ModalService } from '../../services/modal/modal.service';
import { PinService } from '../../services/pin/pin.service';
import { ConfirmModalComponent } from '../confirm-modal/confirm-modal.component';
import { EditPinPopupComponent } from '../edit-pin-popup/edit-pin-popup.component';
import { ImageService } from '../../services/image/image.service';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

@Component({
  selector: 'app-pin-marker',
  templateUrl: './pin-marker.component.html',
  imports: [CommonModule, EditPinPopupComponent, ConfirmModalComponent],
  standalone: true
})
export class PinMarkerComponent {
  @Input() pin!: Pin;
  @Input() marker!: L.Marker;

  currentIndex: number = 0;
  imageUrls: SafeUrl[] = [];
  imageLoaded = false;

  constructor(
    private pinService: PinService,
    private modalService: ModalService,
    private imageService: ImageService,
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit() {
    this.loadImages();
  }

  loadImages() {
    this.pin.files.forEach(imageId => {
      this.imageService.getImage(imageId).subscribe(blob => {
        const objectUrl = URL.createObjectURL(blob);
        const safeUrl = this.sanitizer.bypassSecurityTrustUrl(objectUrl);
        this.imageUrls.push(safeUrl);
        if (this.imageUrls.length === this.pin.files.length) {
          this.imageLoaded = true;
        }
      });
    });
  }

  onClosePopup() {
    this.marker.closePopup();
  }

  onImageLoad() {
    this.imageLoaded = true;
  }

  onDelete() {
    this.modalService.openModal('confirm-modal');
  }

  handleConfirm() {
    this.pinService.deletePin(this.pin.id).subscribe(() => {
      this.marker.remove();
      this.modalService.closeModal('confirm-modal');
    });
  }

  handleCancel() {
    this.modalService.closeModal('confirm-modal');
  }

  get formattedDescription(): string {
    return this.formatDescription(this.pin.description);
  }

  formatDescription(description: string): string {
    const regex = /@(\w+(-\w+)*(\.\w+(-\w+)*)*)/g;
    return description.replace(
      regex,
      `<a href="/profile/$1" class="text-blue-500 hover:underline">@$1</a>`
    );
  }

  prevSlide(): void {
    this.currentIndex =
      (this.currentIndex - 1 + this.imageUrls.length) % this.imageUrls.length;
  }

  nextSlide(): void {
    this.currentIndex = (this.currentIndex + 1) % this.imageUrls.length;
  }

  ngOnDestroy() {
    // Clean up object URLs to prevent memory leaks
    this.imageUrls.forEach(url => {
      URL.revokeObjectURL(url.toString());
    });
  }
}
