import {
  Component,
  Input,
  ViewChild,
  ElementRef,
  AfterViewChecked,
  OnDestroy, OnInit
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { faCopy } from '@fortawesome/free-solid-svg-icons';
import { ChatInput } from '../../components/chat-input/chat-input';
import {AttachedFile, Conversation} from '../../models/data.model';
import { SafeHtml} from '@angular/platform-browser';
import {Subscription} from 'rxjs';
import {DataService} from '../../services/data.service';
import {FileHandlerService} from '../../services/file-handler.service';

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

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


  faCopy = faCopy;

  isTyping = false;
  private isTypingSubscription?: Subscription;
  private shouldScrollToBottom = false;

  constructor(
    private dataService: DataService,
    private fileHandlerService: FileHandlerService
  ) {}

  ngOnInit(): void {
    this.isTypingSubscription = this.dataService.getIsTyping().subscribe(
      isTyping => {
        this.isTyping = isTyping;
        if (isTyping) {
          this.shouldScrollToBottom = true;
        }
      }
    );
  }
  ngAfterViewChecked(): void {
    if (this.shouldScrollToBottom) {
      this.scrollToBottom();
      this.shouldScrollToBottom = false;
    }
  }
  ngOnDestroy(): void {
    this.isTypingSubscription?.unsubscribe();
    this.conversation?.messages.forEach(message => {
      if (message.files) {
        this.fileHandlerService.cleanupFiles(message.files);
      }
    });
  }
  onMessageSentV1(data: { message: string; files: File[] }): void {
    this.shouldScrollToBottom = true;
  }

  async onMessageSent(data: { message: string; files: AttachedFile[] }): Promise<void> {
    if (!this.conversation) return;
    const processedFiles = data.files.map(attachedFile => ({
      ...attachedFile,
      url: attachedFile.url || URL.createObjectURL(attachedFile.file)
    }));

    this.dataService.addMessage({
      content: data.message,
      sender: 'user',
      files: processedFiles.length > 0 ? processedFiles : undefined
    });

    this.dataService.sendMessageToGroq(this.conversation.agentId, data.message);

    this.shouldScrollToBottom = true;
  }



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

  onRegenerateMessageV1(): void {
    if (!this.conversation || this.conversation.messages.length === 0) {
      return;
    }

    const lastUserMessage = [...this.conversation.messages]
      .reverse()
      .find(msg => msg.sender === 'user');

    if (lastUserMessage) {
      // Supprimer la dernière réponse de l'agent
      const messages = this.conversation.messages;
      if (messages[messages.length - 1].sender === 'agent') {
        messages.pop();
      }

      this.isTyping = true;


      setTimeout(() => {
        this.dataService.simulateAgentResponse(
          this.conversation!.agentId,
          lastUserMessage.content
        );

        this.isTyping = false;
      }, 1500);
    }
  }

  onRegenerateMessage(): void {
    if (!this.conversation || this.conversation.messages.length < 2) return;

    const messages = this.conversation.messages;
    const lastUserMessageIndex = messages.map(m => m.sender).lastIndexOf('user');

    if (lastUserMessageIndex === -1) return;

    const lastUserMessage = messages[lastUserMessageIndex];

    if (messages[messages.length - 1].sender === 'agent') {
      messages.pop();
    }

    this.dataService.sendMessageToGroq(this.conversation.agentId, lastUserMessage.content);

  }

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

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

  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;
  }
}
