// components/layout/BackstoryLayout.tsx
import React, { ReactElement, useEffect, useState } from "react";
import { Outlet, useLocation, Routes, Route } from "react-router-dom";
import { Box, Container, Paper } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { SxProps, Theme } from "@mui/material";
import { darken } from "@mui/material/styles";
import { Header } from "components/layout/Header";
import { Scrollable } from "components/Scrollable";
import { Footer } from "components/layout/Footer";
import { Snack, SetSnackType } from "components/Snack";
import { User } from "types/types";
import { LoadingComponent } from "components/LoadingComponent";
import { AuthProvider, useAuth, ProtectedRoute } from "hooks/AuthContext";
import { useAppState, useSelectedCandidate } from "hooks/GlobalContext";
import { getMainNavigationItems, getAllRoutes } from "config/navigationConfig";
import { NavigationItem } from "types/navigation";

// Legacy type for backward compatibility
export type NavigationLinkType = {
  label: ReactElement<any> | string;
  path: string;
  icon?: ReactElement<any>;
};

interface BackstoryPageContainerProps {
  children?: React.ReactNode;
  sx?: SxProps<Theme>;
}

const BackstoryPageContainer = (props: BackstoryPageContainerProps) => {
  const { children, sx } = props;
  return (
    <Container
      className="BackstoryPageContainer"
      sx={{
        display: "flex",
        flexDirection: "row",
        flexGrow: 1,
        p: "0 !important",
        m: "0 auto !important",
        maxWidth: "1024px",
        height: "100%",
        minHeight: 0,
        ...sx,
      }}
    >
      <Box
        sx={{
          display: "flex",
          p: { xs: 0, sm: 0.5 },
          flexGrow: 1,
          minHeight: "min-content",
        }}
      >
        <Paper
          elevation={2}
          sx={{
            display: "flex",
            flexGrow: 1,
            m: 0,
            p: 0.5,
            minHeight: "min-content",
            backgroundColor: "background.paper",
            borderRadius: 0.5,
            maxWidth: "100%",
            flexDirection: "column",
          }}
        >
          {children}
        </Paper>
      </Box>
    </Container>
  );
};

interface BackstoryLayoutProps {
  page: string;
  chatRef: React.Ref<any>;
}

const BackstoryLayout: React.FC<BackstoryLayoutProps> = (
  props: BackstoryLayoutProps
) => {
  const { page, chatRef } = props;
  const { setSnack } = useAppState();
  const navigate = useNavigate();
  const location = useLocation();
  const { guest, user } = useAuth();
  const [navigationItems, setNavigationItems] = useState<NavigationItem[]>([]);

  useEffect(() => {
    const userType = user?.userType || null;
    setNavigationItems(
      getMainNavigationItems(userType, user?.isAdmin ? true : false)
    );
  }, [user]);

  // Generate dynamic routes from navigation config
  const generateRoutes = () => {
    if (!guest && !user) return null;

    const userType = user?.userType || null;
    const isAdmin = user?.isAdmin ? true : false;
    const routes = getAllRoutes(userType, isAdmin);

    return routes
      .map((route, index) => {
        if (!route.path || !route.component) return null;

        // Clone the component and pass necessary props if it's a page component
        const componentWithProps = React.cloneElement(
          route.component as ReactElement,
          {
            ...(route.id === "chat" && { ref: chatRef }),
            ...(route.component.props || {}),
          }
        );

        return (
          <Route
            key={`${route.id}-${index}`}
            path={route.path}
            element={componentWithProps}
          />
        );
      })
      .filter(Boolean);
  };

  return (
    <Box
      sx={{
        height: "100%",
        maxHeight: "100%",
        minHeight: "100%",
        flexDirection: "column",
      }}
    >
      <Header
        currentPath={page}
        navigate={navigate}
        navigationItems={navigationItems}
      />
      <Box
        sx={{
          display: "flex",
          width: "100%",
          maxHeight: "100%",
          minHeight: "100%",
          flex: 1,
          m: 0,
          p: 0,
          flexDirection: "column",
          backgroundColor: "#D3CDBF" /* Warm Gray */,
        }}
      >
        <Scrollable
          className="BackstoryPageScrollable"
          sx={{
            m: 0,
            p: 0,
            mt: "72px" /* Needs to be kept in sync with the height of Header */,
            display: "flex",
            flexDirection: "column",
            backgroundColor: (theme) =>
              darken(theme.palette.background.default, 0.4),
            height: "100%",
            maxHeight: "100%",
            minHeight: "100%",
            minWidth: "min-content",
          }}
        >
          <BackstoryPageContainer>
            {!guest && !user && (
              <Box>
                <LoadingComponent
                  loadingText="Creating session..."
                  loaderType="linear"
                  withFade={true}
                  fadeDuration={1200}
                />
              </Box>
            )}
            {(guest || user) && (
              <>
                <Outlet />
                <Routes>{generateRoutes()}</Routes>
              </>
            )}
            {location.pathname === "/" && <Footer />}
          </BackstoryPageContainer>
        </Scrollable>
      </Box>
    </Box>
  );
};

export { BackstoryLayout };
