import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Agent, Conversation, Message, Project } from '../models/data.model';
import {MOCK_AGENTS, MOCK_CONVERSATIONS, MOCK_PROJECTS} from '../data/mock-data';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private agents$ = new BehaviorSubject<Agent[]>(MOCK_AGENTS);
  private conversations$ = new BehaviorSubject<Conversation[]>(MOCK_CONVERSATIONS);
  private currentConversation$ = new BehaviorSubject<Conversation | null>(null);
  private projects$ = new BehaviorSubject<Project[]>(MOCK_PROJECTS);

  getAgents(): Observable<Agent[]> {
    return this.agents$.asObservable();
  }

  getConversations(): Observable<Conversation[]> {
    return this.conversations$.asObservable();
  }

  getCurrentConversation(): Observable<Conversation | null> {
    return this.currentConversation$.asObservable();
  }

  getProjects(): Observable<Project[]> {
    return this.projects$.asObservable();
  }

  createNewConversation(agentId: string): void {
    const conversation: Conversation = {
      id: this.generateId(),
      title: 'Nouvelle conversation...',
      messages: [],
      lastUpdate: new Date(),
      agentId
    };

    const conversations = this.conversations$.value;
    conversations.unshift(conversation);
    this.conversations$.next(conversations);
    this.currentConversation$.next(conversation);
  }

  addMessage(message: Omit<Message, 'id' | 'timestamp'>): void {
    const current = this.currentConversation$.value;
    if (!current) return;

    const newMessage: Message = {
      ...message,
      id: this.generateId(),
      timestamp: new Date()
    };

    current.messages.push(newMessage);
    current.lastUpdate = new Date();

    // Update title with first user message
    if (current.messages.length === 1 && message.sender === 'user') {
      current.title = message.content.substring(0, 50) + '...';
    }

    this.currentConversation$.next({ ...current });
    this.updateConversationsList(current);
  }

  selectConversation(conversationId: string): void {
    const conversation = this.conversations$.value.find(c => c.id === conversationId);
    if (conversation) {
      this.currentConversation$.next(conversation);
      return;
    }

    const projects = this.projects$.value;
    for (const project of projects) {
      const projectConv = project.conversations?.find(c => c.id === conversationId);
      if (projectConv) {
        this.currentConversation$.next(projectConv);
        return;
      }
    }
  }

  private updateConversationsList(conversation: Conversation): void {
    const conversations = this.conversations$.value;
    const index = conversations.findIndex(c => c.id === conversation.id);
    if (index !== -1) {
      conversations[index] = conversation;
      this.conversations$.next([...conversations]);
    }
  }
  resetCurrentConversation(): void {
    this.currentConversation$.next(null);
  }
  private generateId(): string {
    return Math.random().toString(36).substr(2, 9);
  }

  simulateAgentResponse(agentId: string, userMessage: string): void {
    setTimeout(() => {
      const agent = this.agents$.value.find(a => a.id === agentId);
      const responses = [
        `Je comprends votre question concernant "${userMessage.substring(0, 30)}...". Laissez-moi vous aider avec cela.`,
        `C'est une excellente question. Voici ce que je peux vous dire à ce sujet...`,
        `Merci pour votre message. En tant qu'agent ${agent?.name}, je vais analyser votre demande.`,
        `Je vais traiter votre demande immédiatement. Voici ma réponse...`
      ];

      this.addMessage({
        content: responses[Math.floor(Math.random() * responses.length)],
        sender: 'agent',
      });
    }, 1000 + Math.random() * 1000);
  }

  toggleProject(projectId: string): void {
    const projects = this.projects$.value;
    const project = projects.find(p => p.id === projectId);
    if (project) {
      project.expanded = !project.expanded;
      this.projects$.next([...projects]);
    }
  }
}
