"use client"

import Head from 'next/head'
import * as timeago from "timeago.js"
import { useSession } from "next-auth/react"
import {
    MainContainer,
    ChatContainer,
    MessageList,
    Message,
    MessageInput,
    ConversationHeader,
    TypingIndicator
  } from "@chatscope/chat-ui-kit-react"
  import styles from "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";
import { useState } from 'react';

const Chat = ({ params } ) => {
    const [error, setError] = useState()
    const [ text, setText ] = useState("")
    const [ botIsTyping, setBotIsTyping] = useState(false)
    const { data: session } = useSession()
    const [ statusMessage, setStatusMessage] = useState("Waiting for query...")
    const [conversation, setConversation] = useState([])
    
    const submit = async () => {
        try {
            setConversation((state) => [
                ... state, {
                  message: text,
                  speaker: "user",
                  date: new Date()
                }
              ])

            setBotIsTyping(true)
            setStatusMessage("Finding matches...")
          
            const response = await fetch("/api/chat", {
                method: 'POST',
                body: JSON.stringify({
                    videoId: params.videoId,
                    userId: session?.id,
                    question: text
                })
            })

            setText("")
            setStatusMessage("")
            if(!response.ok) {
                setError(response.statusText)
            } else {
                const data = await response.json()
                setConversation((state) => [
                    ... state, {
                      message: data.text,
                      speaker: "bot",
                      date: new Date()
                    }
                  ])
            }
            setBotIsTyping(false)
        }catch(e) {
            console.error(e)
            setError(e.message)
        }
    }

    return (
        <>
          {
           error &&
                 <div 
                    className="alert alert-danger" 
                    role="alert"
                    style={{ left: "10%", textAlign: "center",  width: "80%", top: "20px"}}
                   >
                     <p>{error}</p>
                 </div>  
          }
            <Head>
                <title>ChatBot</title>
                <meta name="description" content="Generated by create next app" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <main className={`${styles.main}`}>  
            <div style={{ position: "relative", height: "92vh", overflow: "hidden" }}>
                <MainContainer>
                    <ChatContainer>
                        <ConversationHeader>
                        <ConversationHeader.Actions></ConversationHeader.Actions>
                        <ConversationHeader.Content
                            userName="ChatBot"
                            info={statusMessage}
                        />
                        </ConversationHeader>
                        <MessageList
                        typingIndicator={
                            botIsTyping ? (
                            <TypingIndicator content="Bot is typing" />
                            ) : null
                        }
                        >
                        { 
                        conversation.map((entry, index) => {
                            return (
                            <Message
                                key={index}
                                style={{ width: "90%" }}
                                model={{
                                type: "custom",
                                sender: entry.speaker,
                                position: "single",
                                direction:
                                    entry.speaker === "bot" ? "incoming" : "outgoing"
                                }}
                            >
                                <Message.CustomContent>
                                <span  dangerouslySetInnerHTML={{__html: entry.message}} />
                                </Message.CustomContent>
                                <Message.Footer
                                sentTime={timeago.format(entry.date)}
                                sender={entry.speaker === 'bot' ? "Bot": "You"}
                                />
                            </Message>
                            )
                        })
                        }
                        </MessageList>
                        <MessageInput
                            placeholder='Type message here'
                            onSend={submit}
                            onChange={(e, text) => {
                            setText(text)
                            }}
                            sendButton={true}
                            autoFocus
                            disabled={botIsTyping}
                        />
                    </ChatContainer>
                </MainContainer>
                </div>
            </main>
        </>
       
    )
}

export default Chat