import React, { createContext, useContext, useState } from 'react';

interface Message {
  id: number;
  text: string;
  translatedText?: string;
  isArabic?: boolean;
  isFrench?: boolean;
  timestamp: Date;
}

interface ChatContextType {
  messages: Message[];
  addMessage: (message: Message) => void;
}

const ChatContext = createContext<ChatContextType | undefined>(undefined);

export function ChatProvider({ children }: { children: React.ReactNode }) {
  const [messages, setMessages] = useState<Message[]>([]);

  const translateText = async (text: string, from: string, to: string) => {
    try {
      // Utilisation de l'API Google Translate via RapidAPI
      const response = await fetch('https://translate.googleapis.com/translate_a/single?client=gtx&sl=' + from + '&tl=' + to + '&dt=t&q=' + encodeURI(text));
      
      if (!response.ok) {
        throw new Error('Translation failed');
      }

      const data = await response.json();
      // La traduction se trouve dans le premier élément du premier tableau
      const translatedText = data[0][0][0];
      
      return translatedText;
    } catch (error) {
      console.error('Translation error:', error);
      return text;
    }
  };

  const addMessage = async (message: Message) => {
    const from = message.isArabic ? 'ar' : 'fr';
    const to = message.isArabic ? 'fr' : 'ar';
    
    try {
      const translatedText = await translateText(message.text, from, to);
      
      const messageWithTranslation = {
        ...message,
        translatedText,
      };
      
      setMessages(prev => [...prev, messageWithTranslation]);
    } catch (error) {
      console.error('Error in message translation:', error);
      setMessages(prev => [...prev, message]);
    }
  };

  return (
    <ChatContext.Provider value={{ messages, addMessage }}>
      {children}
    </ChatContext.Provider>
  );
}

export function useChat() {
  const context = useContext(ChatContext);
  if (context === undefined) {
    throw new Error('useChat must be used within a ChatProvider');
  }
  return context;
}