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

import TabContext from "@mui/lab/TabContext";

import { ApiOperation } from "../api";
import { useApi } from "../contexts/ApiContext";
import { useRouter } from "../contexts/RouterContext";

export interface PageContextProps {
  changeTab: (tab: string) => void;
  contrib: ApiOperation[];
}

const PageContext = React.createContext<PageContextProps>(undefined as unknown as PageContextProps);
export const usePage = () => React.useContext(PageContext);

export interface PageProps {
  defaultTab?: string;
  tabSearchParam?: boolean | string;
}

export const Page: React.FC<React.PropsWithChildren<PageProps>> = ({
  defaultTab = "default",
  tabSearchParam,
  children,
}) => {
  const [searchParams, setSearchParams] = useSearchParams();

  const tabSearchParamName = (tabSearchParam === true ? "tab" : tabSearchParam) ?? undefined;
  const initialTab = tabSearchParamName
    ? (searchParams.get(tabSearchParamName) ?? defaultTab)
    : location.hash
      ? location.hash.slice(1)
      : defaultTab;
  const [selectedTab, setTab] = React.useState(initialTab);

  const handleTabChange = (tab: string) => {
    if (tabSearchParamName) {
      // Set current tab as URL query param
      if (tab != defaultTab) {
        searchParams.set(tabSearchParamName, tab);
      } else {
        searchParams.delete(tabSearchParamName);
      }
      setSearchParams(searchParams);
    } else {
      // Set current tab as URL hash
      const url = new URL(location.toString());
      const hash = tab != defaultTab ? tab : "";
      url.hash = `#${hash}`;
      history.pushState({}, "", url);
    }
    setTab(tab);
  };

  const { getCurrent } = useRouter();
  const { route: currentRoute } = getCurrent()!;
  const api = useApi();
  // TODO: Skip replacing once bcom contrib tabs are adjusted
  const contrib = api.findContrib(currentRoute.id.replace(".", ":"));

  const context = {
    changeTab: handleTabChange,
    contrib: contrib,
  };

  return (
    <PageContext.Provider value={context}>
      <TabContext value={selectedTab}>{children}</TabContext>
    </PageContext.Provider>
  );
};
