import {Component, Output, EventEmitter, Input, ViewChild, ElementRef, OnDestroy} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {FontAwesomeModule} from '@fortawesome/angular-fontawesome';
import {faPaperclip, faTimes} from '@fortawesome/free-solid-svg-icons';
import {SafeHtml} from '@angular/platform-browser';
import {AttachedFile} from '../../models/data.model';
import {FileHandlerService} from '../../services/file-handler.service';


@Component({
  selector: 'app-chat-input',
  standalone: true,
  imports: [CommonModule, FormsModule, FontAwesomeModule],
  templateUrl: './chat-input.html',
  styleUrls: ['./chat-input.scss']
})
export class ChatInput implements OnDestroy {
  @Input() disabled = false;

  @Output() messageSent = new EventEmitter<{ message: string; files: AttachedFile[] }>();
  @Output() fileAttached = new EventEmitter<File[]>();
  @Output() voiceActivated = new EventEmitter<void>();
  @ViewChild('messageInput') messageInput!: ElementRef<HTMLTextAreaElement>;
  @ViewChild('fileInput') fileInput!: ElementRef<HTMLInputElement>;

  message = '';
  attachedFiles: AttachedFile[] = [];
  faPaperclip = faPaperclip;
  faTimes = faTimes;

  constructor(
    private fileHandlerService: FileHandlerService
  ) {
  }

  ngOnDestroy(): void {
    this.fileHandlerService.cleanupFiles(this.attachedFiles);
  }

  onSend(): void {
    if ((this.message.trim() || this.attachedFiles.length > 0) && !this.disabled) {
      const filesClone = this.fileHandlerService.cloneAttachedFiles(this.attachedFiles);

      this.messageSent.emit({
        message: this.message.trim(),
        files: filesClone
      });
      this.message = '';
      this.attachedFiles = [];
      this.adjustTextareaHeight();
    }
  }

  onInputChange(): void {
    const textarea = this.messageInput.nativeElement;
    textarea.style.height = 'auto';
    textarea.style.height = textarea.scrollHeight + 'px';
  }

  onAttach(): void {
    this.fileInput.nativeElement.click();
  }

  onFileSelected(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files.length > 0) {
      this.handleFiles(Array.from(input.files));
      input.value = '';
    }
  }

  onFileDrop(event: DragEvent): void {
    event.preventDefault();
    event.stopPropagation();

    if (event.dataTransfer?.files && event.dataTransfer.files.length > 0) {
      this.handleFiles(Array.from(event.dataTransfer.files));
    }
  }

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

  private async handleFiles(files: File[]): Promise<void> {
    const validationResult = this.fileHandlerService.validateFiles(
      files,
      this.attachedFiles.length
    );
    if (!validationResult.isValid) {
      alert(validationResult.error);
      return;
    }
    try {
      const processedFiles = await this.fileHandlerService.processFiles(files);
      this.attachedFiles.push(...processedFiles);
      this.fileAttached.emit(files);
    } catch (error) {
      console.error('Erreur lors du traitement des fichiers:', error);
      alert('Erreur lors du traitement des fichiers');
    }
  }

  removeFile(id: string): void {
    const file = this.attachedFiles.find(f => f.id === id);
    if (file) {
      this.fileHandlerService.cleanupFile(file);
    }
    this.attachedFiles = this.attachedFiles.filter(f => f.id !== id);
  }

  getFileIcon(file: File): SafeHtml {
    return this.fileHandlerService.getFileIcon(file);
  }

  formatFileSize(bytes: number): string {
    return this.fileHandlerService.formatFileSize(bytes);
  }

  onVoice(): void {
    this.voiceActivated.emit();
  }

  private adjustTextareaHeight(): void {
    if (this.messageInput) {
      const textarea = this.messageInput.nativeElement;
      textarea.style.height = 'auto';
      textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
    }
  }

  protected getAcceptedTypes() {
    return this.fileHandlerService.getAcceptedTypes;

  }
}
