import * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group';
import { type VariantProps, cva } from 'class-variance-authority';
import * as React from 'react';

import { cn } from '../..';
import { baseToggleVariants } from '../Toggle/BaseToggle';

import styles from './BaseToggleGroup.module.css';

const baseToggleGroupVariants = cva(styles.BaseToggleGroup);

const ToggleGroupContext = React.createContext<
  VariantProps<typeof baseToggleVariants>
>({
  size: 'default',
  variant: 'default',
});

type BaseToggleGroupProps =
  | ToggleGroupPrimitive.ToggleGroupSingleProps
  | ToggleGroupPrimitive.ToggleGroupMultipleProps;

const BaseToggleGroup = React.forwardRef<
  React.ElementRef<typeof ToggleGroupPrimitive.Root>,
  React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &
    VariantProps<typeof baseToggleVariants>
>(({ className, variant, size, children, ...props }, ref) => (
  <ToggleGroupPrimitive.Root
    ref={ref}
    className={cn(styles.BaseToggleGroup, className)}
    {...props}
  >
    <ToggleGroupContext.Provider value={{ variant, size }}>
      {children}
    </ToggleGroupContext.Provider>
  </ToggleGroupPrimitive.Root>
));

BaseToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName;

type BaseToggleGroupItemProps = ToggleGroupPrimitive.ToggleGroupItemProps;

const BaseToggleGroupItem = React.forwardRef<
  React.ElementRef<typeof ToggleGroupPrimitive.Item>,
  React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &
    VariantProps<typeof baseToggleVariants>
>(({ className, children, variant, size, ...props }, ref) => {
  const context = React.useContext(ToggleGroupContext);

  return (
    <ToggleGroupPrimitive.Item
      ref={ref}
      className={cn(
        styles.BaseToggleGroupItem,
        baseToggleVariants({
          variant: context.variant || variant,
          size: context.size || size,
        }),
        className,
      )}
      {...props}
    >
      {children}
    </ToggleGroupPrimitive.Item>
  );
});

BaseToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName;

export {
  BaseToggleGroup,
  BaseToggleGroupItem,
  baseToggleGroupVariants,
  type BaseToggleGroupProps,
  type BaseToggleGroupItemProps,
};
