import React from "react";
import { useNavigate } from "react-router-dom";

import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
import {
  AppBar,
  AppBarProps,
  Breadcrumbs,
  IconButton,
  Link,
  Stack,
  Toolbar,
  Typography,
} from "@mui/material";

import { useI18n } from "../../contexts/I18nContext";
import { RouteInfo, useRouter } from "../../contexts/RouterContext";
import { useUser } from "../../contexts/UserContext";
import { hasAccess } from "../../util/has_access";
import ActionMenu from "../ActionMenu";
import { usePage } from "../Page";

export interface TitleBarProps extends React.PropsWithChildren<Omit<AppBarProps, "title">> {
  back?: boolean | number | string | RouteInfo;
  title?: React.ReactNode;
}

export const TitleBar: React.FC<TitleBarProps> = ({ back = false, title, children, ...props }) => {
  const { t } = useI18n();
  const { navigate, getCurrent, routes } = useRouter();
  const routerNavigate = useNavigate();
  const page = usePage();
  const { user } = useUser();

  if (typeof back === "boolean" && back) back = -1;

  const { route: currentRoute } = getCurrent()!;
  const breadcrumbRoutes = routes.filter(
    (route) =>
      route.id !== currentRoute.id &&
      route.action === "list" &&
      currentRoute.path.startsWith(route.path),
  );

  return (
    <AppBar elevation={0} position="static" sx={{ flexGrow: 1, bgcolor: "transparent" }} {...props}>
      <Toolbar
        sx={{
          display: "flex",
          width: "100%",
          gap: { xs: 2, sm: 1 },
          flexDirection: { xs: "column", sm: "row" },
          "> *": { width: "100%" },
        }}
        variant="dense"
      >
        <Stack alignItems="center" direction="row" flexGrow={1}>
          {back ? (
            <IconButton
              aria-label="back"
              color="default"
              edge="start"
              size="large"
              sx={{ mr: 1.5, backgroundColor: "background.paper" }}
              onClick={() => navigate(back as string | number | RouteInfo)}
            >
              <ArrowBackIcon />
            </IconButton>
          ) : null}

          <Stack>
            {title ? (
              <Typography color="text.primary" sx={{ fontWeight: 700 }} variant="h6">
                {title}
              </Typography>
            ) : null}

            <Breadcrumbs
              aria-label="breadcrumbs"
              separator={<NavigateNextIcon fontSize="inherit" />}
              sx={{
                fontSize: "0.8rem",
                ".MuiBreadcrumbs-separator": { mx: 0.5 },
                a: { cursor: "pointer" },
              }}
            >
              <Link
                key="home"
                color="inherit"
                underline="hover"
                onClick={() => routerNavigate("/", { replace: true })}
              >
                {t("Home")}
              </Link>

              {breadcrumbRoutes.map((route) => (
                <Link
                  key={route.id}
                  color="inherit"
                  underline="hover"
                  onClick={() => navigate(route)}
                >
                  {route.title}
                </Link>
              ))}
            </Breadcrumbs>
          </Stack>
        </Stack>
        {children}
        {page?.contrib.filter(
          (operation) =>
            operation.component?.variant === "action" &&
            hasAccess(user, operation.component.permission, operation.component.group),
        ).length > 0 && (
          <Stack width="fit-content">
            <ActionMenu />
          </Stack>
        )}
      </Toolbar>
    </AppBar>
  );
};
