import { ThemeProvider } from '@mui/material';
import { Attributes, FC, cloneElement, createContext, useContext, useRef, useState } from 'react';
import { useTheme } from '../contexts/ThemeContext';
import ListPage from '../pages/ListPage/ListPage';
import PDFPage from '../pages/PDFPage/PDFPage';

interface IRouterContext {
  navigate?: (route: string, props: (Partial<Record<string, unknown>> & Attributes) | undefined) => void;
  goBack?: (props: (Partial<Record<string, unknown>> & Attributes) | undefined) => void;
  getProps?: () => (Partial<Record<string, unknown>> & Attributes) | undefined;
}

export const RouterContext = createContext<IRouterContext>({});

export const useRouter = () => {
  const { navigate, goBack, getProps } = useContext(RouterContext);

  if (navigate && goBack && getProps) return { navigate, goBack, getProps };
  else throw new Error("Couldn't find context. Is your component inside a Router?");
};

interface IRouterProps {
  globals: (Partial<Record<string, unknown>> & Attributes) | undefined;
}

const routes = [
  {
    path: '/',
    element: <ListPage key={'/-0'} />,
  },
  {
    path: '/file',
    element: <PDFPage />,
  },
];

const Router: FC<IRouterProps> = ({ globals }) => {
  const { theme } = useTheme();

  const history = useRef([{ page: routes[0].element, props: globals }]).current;

  const [currentPage, setCurrentPage] = useState(0);

  const navigate = (route: string, _props: (Partial<Record<string, unknown>> & Attributes) | undefined) => {
    const page = routes.find((_page) => _page.path === route);
    if (page) {
      history.push({
        page: cloneElement(page.element, { key: `${page.path}-${history.length}` }),
        props: { ..._props, ...globals },
      });
      setCurrentPage((prev) => prev + 1);
      window.dispatchEvent(new Event('resize'));
    } else console.warn('No route registered for', route);
  };
  const goBack = (_props: (Partial<Record<string, unknown>> & Attributes) | undefined) => {
    if (history.length > 1) {
      history.pop();
      history[history.length - 1].props = _props;
      setCurrentPage((prev) => prev - 1);
      window.dispatchEvent(new Event('resize'));
    } else console.warn('Already on root page');
  };

  const getProps = () => history[currentPage].props;

  return (
    <ThemeProvider theme={theme}>
      <RouterContext.Provider value={{ navigate, goBack, getProps }}>
        {history[currentPage].page}
      </RouterContext.Provider>
    </ThemeProvider>
  );
};

export default Router;
