import { Component, Input, Output, EventEmitter, ViewChild, ElementRef, AfterViewChecked } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { faCopy, faThumbsUp, faThumbsDown, faRotateRight } from '@fortawesome/free-solid-svg-icons';
import { Conversation } from '../../models/data.model';
import {ChatInput} from '../../components/chat-input/chat-input';

@Component({
  selector: 'app-chat-view',
  standalone: true,
  imports: [CommonModule, FontAwesomeModule, ChatInput],
  templateUrl: './chat-view.html',
  styleUrls: ['./chat-view.scss']
})
export class ChatView implements AfterViewChecked {
  @ViewChild('messagesContainer') messagesContainer!: ElementRef;

  @Input() conversation: Conversation | null = null;
  @Input() isTyping = false;
  @Input() agentName = 'Assistant';

  @Output() messageSent = new EventEmitter<string>();
  @Output() attach = new EventEmitter<void>();
  @Output() voice = new EventEmitter<void>();
  @Output() copyMessage = new EventEmitter<string>();
  @Output() regenerateMessage = new EventEmitter<void>();

  // Icons
  faCopy = faCopy;


  private shouldScrollToBottom = false;

  ngAfterViewChecked(): void {
    if (this.shouldScrollToBottom) {
      this.scrollToBottom();
      this.shouldScrollToBottom = false;
    }
  }

  onMessageSent(message: string): void {
    this.messageSent.emit(message);
    this.shouldScrollToBottom = true;
  }

  onAttach(): void {
    this.attach.emit();
  }

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

  onCopyMessage(content: string): void {
    navigator.clipboard.writeText(content);
    this.copyMessage.emit(content);
  }

  onRegenerateMessage(): void {
    this.regenerateMessage.emit();
  }

  private scrollToBottom(): void {
    try {
      const messagesElement = this.messagesContainer?.nativeElement;
      if (messagesElement) {
        setTimeout(() => {
          messagesElement.scrollTop = messagesElement.scrollHeight;
        }, 100);
      }
    } catch (err) {
      console.error('Error scrolling to bottom:', err);
    }
  }

  markScrollNeeded(): void {
    this.shouldScrollToBottom = true;
  }
}
