import React, { useLayoutEffect, useRef } from 'react';
import cx from 'classnames';
import { Switch, useLocation } from 'react-router-dom';
import { useAppContext } from '../../app/appContext';
import { AccountPage, NotFoundPage } from '../../pages';
import { filterByAccess } from '../../utils';
import { PageRoute } from './pageRoute';
import type { MainContentProps } from './types';

const CLASSNAME = 'MainContent';

export function MainContent<AppData>({ className, routes = [] }: MainContentProps<AppData>) {
    const ref = useRef<HTMLElement | null>(null);
    const { pathname } = useLocation();
    const context = useAppContext<AppData>();

    useLayoutEffect(() => {
        ref?.current?.scrollTo?.(0, 0);
    }, [pathname]);

    const filteredRoutes = filterByAccess(routes, context);

    return (
        <main ref={ref} className={cx(CLASSNAME, className)} data-testid={CLASSNAME}>
            <Switch>
                {filteredRoutes.map((route) => (
                    <PageRoute
                        key={route.path}
                        path={route.path}
                        page={route.page}
                        exact={route.exact ?? true}
                        className={route.className}
                    />
                ))}
                {context.identity.isEmployee && <PageRoute path="/account" page={AccountPage} />}

                <PageRoute path="/*" page={NotFoundPage} />
            </Switch>
        </main>
    );
}
