import { useState, useCallback } from "react";
import { Message } from "../types";
import { v4 as uuidv4 } from "uuid";

export const useMessages = () => {
  const [messages, setMessages] = useState<Message[]>([]);

  const addMessage = useCallback((message: Partial<Message>) => {
    const newMessage: Message = {
      id: uuidv4(),
      text: message.text || "",
      isUser: message.isUser || false,
      timestamp: new Date(),
      streaming: message.streaming || false,
      metadata: message.metadata || {},
    };

    setMessages((prevMessages) => [...prevMessages, newMessage]);
    console.log(
      `Added message with ID: ${newMessage.id}, streaming: ${newMessage.streaming}`
    );
    return newMessage;
  }, []);

  const addSystemMessage = useCallback(
    (text: string, type: string = "info") => {
      const newMessage: Message = {
        id: uuidv4(),
        text,
        isUser: false,
        timestamp: new Date(),
        streaming: false,
        isSystem: true,
        metadata: { type },
      };

      setMessages((prevMessages) => [...prevMessages, newMessage]);

      // Auto-remove system messages after a delay
      setTimeout(
        () => {
          setMessages((prevMessages) =>
            prevMessages.filter((msg) => msg.id !== newMessage.id)
          );
        },
        type === "error" ? 5000 : 3000
      );

      return newMessage;
    },
    []
  );

  const updateMessage = useCallback((id: string, updates: Partial<Message>) => {
    console.log(`Updating message ${id} with:`, updates);

    setMessages((prevMessages) =>
      prevMessages.map((msg) => {
        if (msg.id === id) {
          const updated = { ...msg, ...updates };
          console.log(`Message ${id} updated:`, updated);
          return updated;
        }
        return msg;
      })
    );
  }, []);

  const removeMessage = useCallback((id: string) => {
    setMessages((prevMessages) => prevMessages.filter((msg) => msg.id !== id));
  }, []);

  const clearMessages = useCallback(() => {
    setMessages([]);
  }, []);

  return {
    messages,
    addMessage,
    addSystemMessage,
    updateMessage,
    removeMessage,
    clearMessages,
    setMessages,
  };
};
