import { clsx } from "clsx";
import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui";
import * as React from "react";
import { useGetKey, useGetSet } from "../../hooks";

export const ToggleGroup = React.forwardRef<
  React.ElementRef<typeof ToggleGroupPrimitive.Root>,
  React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> & {
    ensureValue?: boolean;
  }
>(
  (
    {
      className,
      type,
      children,
      defaultValue,
      ensureValue,
      onValueChange,
      ...props
    },
    ref,
  ) => {
    const key = useGetKey(props as any);
    const initialValue = React.useMemo(
      () => ({ value: defaultValue as string | string[] | undefined }),
      [defaultValue],
    );
    const [{ value }, setState] = useGetSet<{
      value: string | string[] | undefined;
    }>(key, initialValue);
    return (
      <ToggleGroupPrimitive.Root
        ref={ref}
        className={clsx("__toggle_group", className)}
        {...props}
        type={type || "single"}
        value={value as any}
        onValueChange={(value: string | string[] | undefined) => {
          if (ensureValue && !value) {
            return;
          }
          setState(
            { value },
            process.env.PREVIEW ? `onValueChange` : undefined,
          );
          onValueChange?.(value as any);
        }}
      >
        {children}
      </ToggleGroupPrimitive.Root>
    );
  },
);

(ToggleGroup as any).ToggleGroupItem = React.forwardRef<
  React.ElementRef<typeof ToggleGroupPrimitive.Item>,
  React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
  return (
    <ToggleGroupPrimitive.Item
      ref={ref}
      className={clsx("__toggle_group-item", className)}
      {...props}
    />
  );
});
(ToggleGroup as any).ToggleGroupItem.displayName =
  ToggleGroupPrimitive.Item.displayName;
