import React, { Children, ReactNode, forwardRef } from "react";
import classNames from "classnames";
import { Box, BoxProps } from "../Box";
import { AppbarTabMarker } from "./AppbarTabMarker";
import { cn } from "./config";

type AppbarTabProps = {
  children: ReactNode;
  as?: any;
  active?: boolean;
};

export const AppbarTabs = (props: BoxProps) => {
  return (
    <Box as="nav" className={cn({ e: "tabs" })} role="navigation" {...props} />
  );
};

export const AppbarTab = forwardRef<AppbarTabProps, any>(
  ({ children, renderAs: Component = "a", active, ...rest }, ref) => {
    if (Children.count(children) > 1) {
      throw new Error(
        `Only one child node may be passed to Appbar.Tab, but ${Children.count(
          children,
        )} were passed.`,
      );
    }

    return (
      <Component
        {...rest}
        ref={ref}
        tabIndex={0}
        className={classNames(
          cn({ e: "tab" }),
          "hasTabMarker",
          active && cn({ e: "tab", m: "active" }),
        )}
      >
        {children}

        <AppbarTabMarker />
      </Component>
    );
  },
);
