import { CommonModule } from '@angular/common';
import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-drag-drop',
  imports: [CommonModule],
  templateUrl: './drag-drop.component.html',
})
export class DragDropComponent {
  fileNames: string[] = [];
  @Output() filesSelected = new EventEmitter<FileList>();

  onFilesSelected(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input.files) {
      this.updateFileNames(input.files);
      this.filesSelected.emit(input.files);
    }
  }

  onDrop(event: DragEvent): void {
    event.preventDefault();
    event.stopPropagation();
    if (event.dataTransfer && event.dataTransfer.files) {
      this.updateFileNames(event.dataTransfer.files);
      this.filesSelected.emit(event.dataTransfer.files);
    }
  }

  onDragOver(event: DragEvent): void {
    event.preventDefault();
  }

  onDragLeave(event: DragEvent): void {
    event.preventDefault();
  }

  private updateFileNames(files: FileList): void {
    for (let i = 0; i < files.length; i++) {
      this.fileNames.push(files[i].name);
    }
  }

  removeFile(fileName: string): void {
    const index = this.fileNames.indexOf(fileName);
    this.fileNames.splice(index, 1);
  }
}
