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, AttachedFile, 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);
  }
  onMessageSentFromWelcome(data: { message: string; files: AttachedFile[] }): void {
    const defaultAgentId = this.agents.length > 0 ? this.agents[0].id : 'default';

    this.animatingInput = true;

    setTimeout(() => {
      this.dataService.createNewConversation(defaultAgentId);
      this.animatingInput = false;
      setTimeout(() => {
        if (this.chatView) {
          this.chatView.onMessageSent(data);
        }
      }, 100);
    }, 600);
  }

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


  /*private async sendMessage(message: string, files: File[] = []): Promise<void> {
    if (!this.currentConversation) return;

    const attachedFiles: AttachedFile[] = await this.processFiles(files);

    let messageContent = message;
    if (!messageContent && attachedFiles.length > 0) {
      messageContent = `${attachedFiles.length} fichier(s) joint(s)`;
    }

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

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

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

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


  private async processFiles(files: File[]): Promise<AttachedFile[]> {
    const attachedFiles: AttachedFile[] = [];

    for (const file of files) {
      const attachedFile: AttachedFile = {
        file:file,
        id:
        url: URL.createObjectURL(file)
      };

      if (file.type.startsWith('image/')) {
        try {
          attachedFile.preview = await this.generateImagePreview(file);
        } catch (error) {
          console.error('Erreur lors de la génération de la preview:', error);
        }
      }

      attachedFiles.push(attachedFile);
    }

    return attachedFiles;
  }

  private generateImagePreview(file: File): Promise<string> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();

      reader.onload = (e: ProgressEvent<FileReader>) => {
        if (e.target?.result) {
          resolve(e.target.result as string);
        } else {
          reject(new Error('Impossible de lire le fichier'));
        }
      };

      reader.onerror = () => reject(new Error('Erreur de lecture du fichier'));
      reader.readAsDataURL(file);
    });
  }*/


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