import { CommonModule } from '@angular/common';
import {
  Component,
  input,
  output
} from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import {
  lucideCopy,
  lucideDownload,
  lucideX
} from '@ng-icons/lucide';
import { Attachment } from '../../../../../attachment';
import { ContextMenuComponent } from '../../../../../../shared';
import { ChatMessageImageContextMenuEvent } from '../../models/chat-messages.model';

@Component({
  selector: 'app-chat-message-overlays',
  standalone: true,
  imports: [
    CommonModule,
    NgIcon,
    ContextMenuComponent
  ],
  viewProviders: [
    provideIcons({
      lucideCopy,
      lucideDownload,
      lucideX
    })
  ],
  templateUrl: './chat-message-overlays.component.html',
  host: {
    style: 'display: contents;'
  }
})
export class ChatMessageOverlaysComponent {
  readonly lightboxAttachment = input<Attachment | null>(null);
  readonly imageContextMenu = input<ChatMessageImageContextMenuEvent | null>(null);

  readonly lightboxClosed = output();
  readonly contextMenuClosed = output();
  readonly downloadRequested = output<Attachment>();
  readonly copyRequested = output<Attachment>();
  readonly imageContextMenuRequested = output<ChatMessageImageContextMenuEvent>();

  closeLightbox(): void {
    this.lightboxClosed.emit();
  }

  closeImageContextMenu(): void {
    this.contextMenuClosed.emit();
  }

  downloadAttachment(attachment: Attachment): void {
    this.downloadRequested.emit(attachment);
  }

  copyImageToClipboard(attachment: Attachment): void {
    this.copyRequested.emit(attachment);
  }

  openImageContextMenu(event: MouseEvent, attachment: Attachment): void {
    event.preventDefault();
    event.stopPropagation();
    this.imageContextMenuRequested.emit({
      positionX: event.clientX,
      positionY: event.clientY,
      attachment
    });
  }

  formatBytes(bytes: number): string {
    const units = [
      'B',
      'KB',
      'MB',
      'GB'
    ];

    let size = bytes;
    let unitIndex = 0;

    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }

    return `${size.toFixed(1)} ${units[unitIndex]}`;
  }
}
