import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import {faArrowLeft, faShare} from '@fortawesome/free-solid-svg-icons';
import { Sidebar } from '../../components/sidebar/sidebar';
import { AgentCard } from '../../components/agent-card/agent-card';
import { ChatInput } from '../../components/chat-input/chat-input';
import { DataService } from '../../services/data.service';
import { Agent, Conversation } from '../../models/data.model';
import {ChatView} from '../chat/chat-view';
import {RouterLink} from '@angular/router';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [
    CommonModule,
    FontAwesomeModule,
    Sidebar,
    AgentCard,
    ChatInput,
    ChatView,
    RouterLink
  ],
  templateUrl: './dashboard.html',
  styleUrls: ['./dashboard.scss']
})
export class Dashboard implements OnInit {
  @ViewChild('contentBody') contentBody!: ElementRef;
  @ViewChild(ChatView) chatView!: ChatView;

  agents: Agent[] = [];
  currentConversation: Conversation | null = null;
  sidebarCollapsed = false;
  isTyping = false;

  // Icons
  faShare = faShare;

  private animatingInput = false;

  constructor(private dataService: DataService) {}

  ngOnInit(): void {
    this.dataService.getAgents().subscribe(agents => {
      this.agents = agents;
    });

    this.dataService.getCurrentConversation().subscribe(conversation => {
      const hadConversation = this.currentConversation !== null;
      this.currentConversation = conversation;

      if (hadConversation && conversation && this.chatView) {
        this.chatView.markScrollNeeded();
      }

      if (conversation !== null) {
        this.isTyping = false;
      }
    });
  }

  onNewChat(): void {
    this.dataService.resetCurrentConversation();
    this.animatingInput = false;

    setTimeout(() => {
      if (this.contentBody?.nativeElement) {
        this.contentBody.nativeElement.scrollTop = 0;
      }
    }, 100);
  }

  onAgentSelected(agent: Agent): void {
    this.animatingInput = true;

    setTimeout(() => {
      this.dataService.createNewConversation(agent.id);
      this.animatingInput = false;
    }, 600);
  }

  onConversationSelected(conversationId: string): void {
    this.dataService.selectConversation(conversationId);
  }

  onMessageSent(message: string): void {
    if (!this.currentConversation) {
      this.dataService.createNewConversation('default');

      setTimeout(() => {
        this.sendMessage(message);
      }, 100);
    } else {
      this.sendMessage(message);
    }
  }

  onToggleSidebar(): void {
    this.sidebarCollapsed = !this.sidebarCollapsed;
  }

  onAttach(): void {
    console.log('Attach file clicked');
  }

  onVoice(): void {
    console.log('Voice input clicked');
  }

  onCopyMessage(content: string): void {
    console.log('Message copied:', content);
  }

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

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

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

      this.isTyping = true;
      if (this.chatView) {
        this.chatView.markScrollNeeded();
      }

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

        this.isTyping = false;
        if (this.chatView) {
          this.chatView.markScrollNeeded();
        }
      }, 1500);
    }
  }

  private sendMessage(message: string): void {
    if (!this.currentConversation) return;

    this.dataService.addMessage({
      content: message,
      sender: 'user',
    });

    this.isTyping = true;
    if (this.chatView) {
      this.chatView.markScrollNeeded();
    }

    setTimeout(() => {
      this.dataService.simulateAgentResponse(
        this.currentConversation!.agentId,
        message
      );

      this.isTyping = false;
      if (this.chatView) {
        this.chatView.markScrollNeeded();
      }
    }, 1500);
  }

  get hasActiveConversation(): boolean {
    return this.currentConversation !== null &&
      this.currentConversation.messages &&
      this.currentConversation.messages.length > 0;
  }

  get currentAgentName(): string {
    if (!this.currentConversation) return '';

    const agent = this.agents.find(a => a.id === this.currentConversation?.agentId);
    return agent?.name || 'Assistant';
  }

  protected readonly faArrowLeft = faArrowLeft;
}
