import baseUrl from "@/services/api/api.config";
import { useTheme } from "@mui/material";
import Grid from "@mui/material/Unstable_Grid2";
import { useEffect, useState } from "react";
import ChatInterface from "../chatInterface";
import ChunkInteface from "../chunkInterface";
import ContextHeader from "../contextHeader";
import ModelSelection from "../modelSelection";
import PreviewChunks from "../previewChunks";
import PreviewDocuments from "../previewDocuments";
import PreviewHeader from "../previewHeader";
import SendMessage from "../sendMessage";
import UploadFile from "../uploadFile";

export default function Body() {
  const theme = useTheme();

  const [messages, setMessages] = useState([]);
  const [documents, setDocuments] = useState([]);
  const [chunks, setChunks] = useState([]);
  const [previewedChunk, setPreviewedChunk] = useState(null);

  const onSelectedChunk = (chunk) => {
    if (chunk.documentNumber === previewedChunk) {
      setPreviewedChunk(null);
      return;
    }
    setPreviewedChunk(chunk.documentNumber);
  };

  const fetchMessages = async () => {
    const url = `${baseUrl}/query/get_messages`;

    const response = await fetch(url);
    const messagesResponse = await response.json();
    setMessages(messagesResponse.data);
  };

  const fetchChunks = async () => {
    const url = `${baseUrl}/document/get_chunks`;
    const response = await fetch(url);
    const chunksResponse = await response.json();

    if (Object.keys(chunksResponse.data).length === 0) {
      return;
    }

    const documentNames = [];

    const transformedData = Object.keys(chunksResponse.data).flatMap(
      (documentKey, index) => {
        documentNames.push({
          id: index + 1,
          filename: documentKey,
        });

        const documentData = chunksResponse.data[documentKey];
        return documentData.map((chunk) => {
          return {
            chunkId: chunk.index,
            documentId: documentKey,
            text: chunk.text,
          };
        });
      }
    );

    setDocuments(documentNames);
    setChunks(transformedData);
  };

  useEffect(() => {
    fetchMessages();
    fetchChunks();
  }, []);

  return (
    <>
      <Grid container mt={1} style={{ height: "97vh" }}>
        <Grid
          item
          xs={12}
          sm={5}
          p={1}
          style={{ display: "flex", flexDirection: "column", height: "100%" }}
        >
          <ModelSelection
            fetchChunks={fetchChunks}
            fetchMessages={fetchMessages}
          ></ModelSelection>
          <ChatInterface messages={messages}></ChatInterface>
          <SendMessage fetchMessages={fetchMessages}></SendMessage>
        </Grid>
        <Grid
          item
          xs={12}
          sm={2}
          p={1}
          style={{ display: "flex", flexDirection: "column", height: "100%" }}
        >
          <ContextHeader chunks={2} documents={1} />
          <PreviewChunks chunks={chunks} onSelectedChunk={onSelectedChunk} />
          <PreviewDocuments documents={documents} fetchChunks={fetchChunks} />
          <UploadFile fetchChunks={fetchChunks} />
        </Grid>
        <Grid
          item
          xs={12}
          sm={5}
          p={1}
          style={{ display: "flex", flexDirection: "column", height: "100%" }}
        >
          <PreviewHeader></PreviewHeader>
          <ChunkInteface chunkTest={chunks[previewedChunk]}></ChunkInteface>
        </Grid>
      </Grid>
    </>
  );
}
