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';
import { GroqService, GroqMessage } from './groq.service';

@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);
  private isTyping$ = new BehaviorSubject<boolean>(false);

  constructor(private groqService: GroqService) {}

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

  getIsTyping(): Observable<boolean> {
    return this.isTyping$.asObservable();
  }

  createNewConversation(agentId: string): void {
    const conversation: Conversation = {
      id: this.generateId(),
      title: 'Nouvelle conversation...',
      messages: [],
      createdAt: new Date(),
      updatedAt: 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.updatedAt = 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);
  }


  sendMessageToGroq(agentId: string, userMessage: string): void {
    const current = this.currentConversation$.value;
    if (!current) return;

    if (!this.groqService.isConfigured()) {
      console.error('Groq API key not configured');
      this.addMessage({
        content: 'Erreur : Clé API Groq non configurée. Veuillez configurer votre clé API dans groq.service.ts',
        sender: 'agent',
      });
      return;
    }

    const agent = this.agents$.value.find(a => a.id === agentId);
    const agentName = agent?.name || 'Assistant';
    const agentDescription = agent?.description || 'un assistant IA utile';

    const groqMessages: GroqMessage[] = [
      {
        role: 'system',
        content: `Tu es ${agentName}, ${agentDescription}. Tu réponds en français de manière claire, professionnelle et utile.`
      }
    ];

    const recentMessages = current.messages.slice(-10);
    for (const msg of recentMessages) {
      groqMessages.push({
        role: msg.sender === 'user' ? 'user' : 'assistant',
        content: msg.content
      });
    }

    groqMessages.push({
      role: 'user',
      content: userMessage
    });

    this.isTyping$.next(true);

    let fullResponse = '';
    let messageId = '';

    this.groqService.sendMessageStream(
      groqMessages,
      (chunk: string) => {
        fullResponse += chunk;

        const current = this.currentConversation$.value;
        if (!current) return;

        if (!messageId) {
          messageId = this.generateId();
          const newMessage: Message = {
            id: messageId,
            content: fullResponse,
            sender: 'agent',
            timestamp: new Date()
          };
          current.messages.push(newMessage);
        } else {
          const messageIndex = current.messages.findIndex(m => m.id === messageId);
          if (messageIndex !== -1) {
            current.messages[messageIndex].content = fullResponse;
          }
        }

        current.updatedAt = new Date();
        this.currentConversation$.next({ ...current });
        this.updateConversationsList(current);
      },
      () => {
        this.isTyping$.next(false);
        console.log('Réponse complète reçue de Groq');
      },
      (error: any) => {
        this.isTyping$.next(false);
        console.error('Erreur Groq:', error);

        this.addMessage({
          content: `Désolé, une erreur est survenue lors de la communication avec l'IA : ${error.message || 'Erreur inconnue'}`,
          sender: 'agent',
        });
      }
    );
  }


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