import React from "react";
import type { ReactNode } from "react";
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";
import type { ToggleGroupSingleProps } from "@radix-ui/react-toggle-group";

import { twMerge } from "../../../tailwind.config";
import MultipleButtonToggleItem from "./MultipleButtonToggleItem";

export interface MultipleButtonToggleProps
  extends Omit<ToggleGroupSingleProps, "type" | "className"> {
  children: ReactNode;
  value?: string;
  onValueChange?: (newValue: string) => void;
  size?: "small" | "large";
  ESCAPE_className?: string;
}

export const MultipleButtonToggle = ({
  value,
  children,
  onValueChange,
  size = "large",
  ESCAPE_className,
  ...restProps
}: MultipleButtonToggleProps) => (
  <ToggleGroupPrimitive.Root
    className={twMerge(
      "grid auto-cols-fr grid-flow-col gap-4 rounded-6 bg-N20A p-4",
      ESCAPE_className
    )}
    type="single"
    value={value}
    onValueChange={(value) => value !== "" && onValueChange?.(value)}
    {...restProps}
  >
    {React.Children.map(children, (child) => {
      if (React.isValidElement(child)) {
        return React.cloneElement(child, {
          ...child.props,
          size,
        });
      }

      return child;
    })}
  </ToggleGroupPrimitive.Root>
);

MultipleButtonToggle.Item = MultipleButtonToggleItem;
