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)
    // console.log("listing chats?")
    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(() => {
    setChats([]);
    setLoaded(false);
    setLoading(false);
    setTotalMessages(0);
  }, [objectKey]);

  useEffect(() => {
    if (chats.length === 0 && !loaded) {
      loadChats();
    }
  }, [objectKey, chats, loaded]);

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

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