import React, { useMemo } from "react";

import TabList, { TabListProps } from "@mui/lab/TabList";

import { useUser } from "../contexts/UserContext";
import { hasAccess } from "../util/has_access";

import { usePage } from "./Page";
import { Tab } from "./Tab";

export interface TabsProps extends Omit<TabListProps, "onChange"> {
  onChange?: (tab: string) => void;
  searchParam?: boolean | string;
  data?: unknown;
}

export const Tabs: React.FC<React.PropsWithChildren<TabsProps>> = ({
  onChange,
  data,
  children,
  scrollButtons = "auto",
  variant = "scrollable",
  sx: passedSx,
  ...props
}) => {
  const page = usePage();
  const { user } = useUser();

  const sx = useMemo(
    () => ({
      display: "flex",
      pl: 3,
      transform: "translateY(1px)",
      ".MuiTabs-flexContainer": {
        gap: 3,
        height: "100%",
      },
      ...passedSx,
    }),
    [passedSx],
  );

  const handleTabChange = (_: React.SyntheticEvent, newTab: string) => {
    page.changeTab(newTab);
    if (onChange != null) {
      onChange(newTab);
    }
  };

  return (
    <TabList
      scrollButtons={scrollButtons}
      sx={sx}
      variant={variant}
      onChange={handleTabChange}
      {...props}
    >
      {children}
      {page.contrib
        .filter((operation) => operation.method === "GET" && operation.component?.variant === "tab")
        .map((operation) => {
          if (operation.component?.predicate && data && !operation.component?.predicate(data)) {
            return null;
          }

          if (!hasAccess(user, operation.component?.permission, operation.component?.group)) {
            return null;
          }

          const value = operation.id.match(/\w+\.contrib:(?<name>.+)/)?.groups?.name;
          const Icon = operation.component?.icon as React.ComponentType;

          return (
            value && (
              <Tab
                key={operation.id}
                icon={Icon && <Icon />}
                label={operation.component?.title ?? value}
                value={value}
              />
            )
          );
        })}
    </TabList>
  );
};
