import { useEffect, useState } from "react"

interface Message {
    role: string
    content:string
}

interface ChatMessages {
    name: string
    messages: Message[]
    timestamp: number
    
}

interface GlobalChatHistory {
    chats: ChatMessages[]
    selectedIndex: number
}

let globalChatHistory: GlobalChatHistory = {
    chats: [
        { name: "Chat 1", messages: [{role:"system",content:"you are a helpful assistant"},{role:"assistant",content:"how can i help you"}], timestamp: 4 },
        { name: "Chat 2", messages: [{role:"system",content:"you are a helpful assistant"},{role:"assistant",content:"how can i help you"}], timestamp: 4 },
    ],
    selectedIndex:0
}
let listeners: ((state: GlobalChatHistory) => void)[] = []

const setGlobalState = (newState: GlobalChatHistory): void => {
    globalChatHistory = newState;
    listeners.forEach((listener) => listener(globalChatHistory))
}

export const useChatHistory = (): [GlobalChatHistory, (index:number)=>void,  (newState:GlobalChatHistory) => void,(messageIndex: number, newContent:string)=> void] => {
    const [state, setState] = useState<GlobalChatHistory>(globalChatHistory)

    useEffect(() => {
        console.log("help", globalChatHistory);
        
        const listener = (newState: GlobalChatHistory) => {
            setState(newState)
        }

        listeners.push(listener)

        return () => {
            listeners = listeners.filter((l) => l!== listener)
        }
    }, [])

    const setSelectedIndex = (index: number) => {
        setGlobalState({...state,selectedIndex:index})
    }

    const updateMessage = (messageIndex: number, newContent: string) => {
        const updatedChats = [...state.chats]
        const chatIndex = globalChatHistory.selectedIndex
        if (chatIndex >= 0 && chatIndex < updatedChats.length) {
            const updatedMessages = [...updatedChats[chatIndex].messages]
            if (messageIndex >= 0 && messageIndex < updatedMessages.length) {
                updatedMessages[messageIndex] = { ...updatedMessages[messageIndex], content: newContent }
                updatedChats[chatIndex] = { ...updatedChats[chatIndex], messages: updatedMessages }
                setGlobalState({...state, chats: updatedChats})
            }
        }
    }

    return [state, setSelectedIndex, setGlobalState, updateMessage]
}