import React, { useState, useEffect } from 'react';

import { Scrollable } from '../Components/Scrollable';
import { BackstoryPageProps } from '../Components/BackstoryTab';
import { Document } from '../Components/Document';

const AboutPage = (props: BackstoryPageProps) => {
  const { sessionId, submitQuery, setSnack, route, setRoute } = props;
  const [subRoute, setSubRoute] = useState<string>("");
  const [page, setPage] = useState<string>("");

  useEffect(() => {
    if (route === undefined) { return; }
    const parts = route.split("/");
    setPage(parts[0]);
    parts.shift();
    setSubRoute(parts.join("/"));
  }, [route]);

  useEffect(() => {
    console.log(`AboutPage: ${page} - sub-route - ${subRoute}`);
  }, [page, subRoute]);

  useEffect(() => {
    if (route) {
      const parts = route.split("/");
      if (parts[0] !== page) {
        parts.shift();
        const incomingSubRoute = parts.join("/");
        if (incomingSubRoute !== subRoute) {
          setSubRoute(incomingSubRoute);
        }
      }
    } else if (subRoute) {
      setRoute && setRoute(subRoute);
    }
  }, [page, route, setRoute, subRoute]);

  useEffect(() => {
    let newRoute = page;
    if (subRoute) {
      newRoute += '/' + subRoute;
    }
    if (route !== newRoute && setRoute) {
      setRoute(newRoute);
    }
  }, [route, page, subRoute, setRoute]);

  const onDocumentExpand = (document: string, open: boolean) => {
    console.log("Document expanded:", document, open);
    if (open) {
      setSubRoute("");
      setPage(document);
    } else {
      setSubRoute("");
      setPage("");
    }
  }

  return <Scrollable
    autoscroll={false}
    sx={{
      maxWidth: "1024px",
      height: "calc(100vh - 72px)",
      flexDirection: "column",
      margin: "0 auto",
      p: 1,
    }}
  >
    <Document {...{
      title: "About",
      filepath: "/docs/about.md",
      onExpand: (open: boolean) => { onDocumentExpand('about', open); },
      expanded: page === 'about',
      sessionId,
      submitQuery: submitQuery,
      setSnack,
    }} />
    <Document {...{
      title: "BETA",
      filepath: "/docs/beta.md",
      onExpand: (open: boolean) => { onDocumentExpand('beta', open); },
      expanded: page === 'beta',
      sessionId,
      submitQuery: submitQuery,
      setSnack,
    }} />
    <Document {...{
      title: "Resume Generation Architecture",
      filepath: "/docs/resume-generation.md",
      onExpand: (open: boolean) => { onDocumentExpand('resume-generation', open); },
      expanded: page === 'resume-generation',
      sessionId,
      submitQuery: submitQuery,
      setSnack,
    }} />
    <Document {...{
      title: "Application Architecture",
      filepath: "/docs/about-app.md",
      onExpand: (open: boolean) => { onDocumentExpand('about-app', open); },
      expanded: page === 'about-app',
      sessionId,
      submitQuery: submitQuery,
      setSnack,
    }} />
  </Scrollable>;
};

export {
  AboutPage
};