import {
  Children,
  cloneElement,
  type ComponentProps,
  isValidElement,
  type ReactNode,
} from "react";

import { ButtonProps } from "../button/Button";
import { twMerge } from "../../../tailwind.config";
import { twJoin } from "tailwind-merge";

export interface ButtonGroupProps extends ComponentProps<"div"> {
  /** @default "primary" */
  variant?: ButtonProps["variant"];
  /** @default "32" */
  size?: ButtonProps["size"];
  children: ReactNode;
}

export const ButtonGroup = ({
  variant = "primary",
  children,
  size = "32",
  ...restProps
}: ButtonGroupProps) => {
  let backgroundColor = "bg-N0";
  let dividerColor = "after:bg-N50";

  if (variant === "primary") {
    backgroundColor = "bg-B400";
    dividerColor = "after:bg-B300";
  } else if (variant === "danger") {
    backgroundColor = "bg-R400";
    dividerColor = "after:bg-R300";
  }

  const dividerClasses = twJoin(
    "after:h-16 after:w-[1px] after:rounded-full after:content-['']",
    "after:absolute after:right-0 after:top-1/2 after:z-10 after:-translate-y-1/2 after:translate-x-1/2",
    dividerColor
  );

  return (
    <div
      role="group"
      className={twJoin("group flex rounded-6", backgroundColor)}
      {...restProps}
    >
      {Children.toArray(children)
        .filter(Boolean)
        .map((child, index, children) => {
          if (isValidElement(child)) {
            const isFirst = index === 0;
            const isLast = index === children.length - 1;

            return (
              <div
                key={index}
                className={twJoin(
                  "relative flex",
                  isFirst && "group/first",
                  isLast && "group/last",
                  !isLast && variant !== "outlined" && dividerClasses
                )}
              >
                {cloneElement(child, {
                  size,
                  variant,
                  ...child.props,
                  ESCAPE_className: twMerge(
                    "rounded-l-0 rounded-r-0",
                    "group-[]/first:rounded-l-6 group-[]/last:rounded-r-6",
                    variant === "outlined" && "-ml-[1px] group-[]/first:ml-0",
                    child.props.ESCAPE_className
                  ),
                })}
              </div>
            );
          }

          return child;
        })}
    </div>
  );
};
