import React, { useState, useEffect } from 'react';
import { Message } from './Message';
import { BackstoryElementProps } from './BackstoryTab';

interface DocumentProps extends BackstoryElementProps {
  title: string;
  expanded?: boolean;
  filepath: string;
  content?: string;
  disableCopy?: boolean;
  onExpand?: (open: boolean) => void;
}

const Document = (props: DocumentProps) => {
  const { sessionId, setSnack, submitQuery, filepath, content, title, expanded, disableCopy, onExpand } = props;
  const backstoryProps = {
    submitQuery,
    setSnack,
    sessionId
  }

  const [document, setDocument] = useState<string>("");

  // Get the markdown
  useEffect(() => {
    if (document !== "" || !filepath) {
      return;
    }
    const fetchDocument = async () => {
      try {
        const response = await fetch(filepath, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
        });
        if (!response.ok) {
          throw Error(`${filepath} not found.`);
        } 
        const data = await response.text();
        setDocument(data);
      } catch (error: any) {
        console.error('Error obtaining About content information:', error);
        setDocument(`${filepath} not found.`);
      };
    };

    fetchDocument();
  }, [document, setDocument, filepath])

  return (
    <Message
      {...{
        sx: {
          display: 'flex',
          flexDirection: 'column',
          p: 1,
          m: 0,
          flexGrow: 0,
        },
        message: { role: 'content', title: title, content: document || content || "" },
        expanded,
        disableCopy,
        onExpand,
      }}
      {...backstoryProps} />
  );
};

export {
  Document
};