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

interface DocumentProps extends BackstoryElementProps {
  filepath?: string;
}

const Document = (props: DocumentProps) => {
  const { filepath } = props;

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

  // Get the markdown
  useEffect(() => {
    if (!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 Docs content information:', error);
        setDocument(`${filepath} not found.`);
      };
    };

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

  return (<>
    <StyledMarkdown content={document} />
  </>);
};

export {
  Document
};