import { Box, CircularProgress, Divider, Theme } from "@mui/material";
import { useGlobalState, useNoteAPI } from "providers";
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import ChatInput from "./ChatInput";
import ChatOutput from "./ChatOutput";
import { Note } from "models";
import { pond } from "protobuf-ts/pond";
import { makeStyles } from "@mui/styles";

const useStyles = makeStyles((_theme: Theme) => {
  return ({
    chatContainer: {
      height: "100%", 
      display: "flex", 
      flexDirection: "column", 
      justifyContent: "space-between",
    }
  })
})

interface Props {
  objectKey: string;
  type?: pond.NoteType;
}

export default function Chat(props: Props) {
  const [chats, setChats] = useState<pond.Chat[]>([]);
  const { objectKey, type } = props;
  const noteAPI = useNoteAPI();
  const [loaded, setLoaded] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [totalMessages, setTotalMessages] = useState(0);
  const [{ user }] = useGlobalState();
  const classes = useStyles()

  const loadChats = () => {
    setLoading(true)
    noteAPI.listChats(10, chats.length, "desc", "timestamp", objectKey).then(resp => {
      setChats(resp.data.chats ? resp.data.chats.reverse().concat(chats) : [])
      setTotalMessages(resp.data.total)
    }).finally(() => {
      setLoading(false)
      setLoaded(true)
    })
  }

  const removeNote = (index: number) => {
    let c = chats
    setTotalMessages(totalMessages - 1);
    c.splice(index, 1);
    setChats([...c])
  };

  const showNewNotes = (newNote: Note) => {
    let note = pond.Note.create({
      settings: newNote.settings,
      status: newNote.status,
    })
    let profile = pond.UserProfile.create({
      name: user.name(),
      avatar: user.settings.avatar,
    })
    let permissions = [
      pond.Permission.PERMISSION_READ, 
      pond.Permission.PERMISSION_WRITE,
    ]
    let c = chats;
    c.push({
      note: note,
      profile: profile,
      permissions: permissions
    } as any)
    setChats([...c])
  };

  useEffect(() => {
    loadChats()
  }, []);

  const loadMore = () => {
    loadChats();
  };

  return (
    <React.Fragment>
      { loading && !loaded ? (
        <Box width="100%" height="100%" alignContent={"center"} textAlign={"center"} >
          <CircularProgress />
        </Box>
      ) : (
        <Box className={classes.chatContainer}>
          <ChatOutput
            totalMessages={totalMessages}
            messages={chats}
            removeNoteMethod={removeNote}
            loadMore={loadMore}
          />
          <Box style={{bottom: 0}}>
            <Divider/>
            <ChatInput newNoteMethod={showNewNotes} objectKey={objectKey} type={type} />
          </Box>
        </Box>
      )}
    </React.Fragment>
  );
}
