import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { forwardRef, type ComponentPropsWithoutRef, type ElementRef } from "react";

import {
  radioGroupIndicatorVariants,
  radioGroupItemVariants,
  radioGroupVariants
} from "./radio-group.variants";
import { cn } from "../lib/cn";
import type { VariantProps } from "../lib/cva";
import { createDataAttributes, createSlot } from "../lib/contracts";

export type RadioGroupProps = ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root> &
  VariantProps<typeof radioGroupVariants>;

export function RadioGroup({
  className,
  orientation = "vertical",
  ...props
}: RadioGroupProps) {
  return (
    <RadioGroupPrimitive.Root
      {...props}
      {...createSlot("root")}
      {...createDataAttributes({ orientation })}
      className={cn(radioGroupVariants({ orientation }), className)}
      orientation={orientation}
    />
  );
}

export type RadioGroupItemProps =
  ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item> & {
    invalid?: boolean;
  };

export const RadioGroupItem = forwardRef<
  ElementRef<typeof RadioGroupPrimitive.Item>,
  RadioGroupItemProps
>(function RadioGroupItem({ className, disabled, invalid, ...props }, ref) {
  return (
    <RadioGroupPrimitive.Item
      {...props}
      {...createSlot("control")}
      {...createDataAttributes({
        disabled,
        invalid
      })}
      aria-invalid={invalid || undefined}
      className={cn(radioGroupItemVariants(), className)}
      disabled={disabled}
      ref={ref}
    >
      <RadioGroupPrimitive.Indicator
        {...createSlot("icon")}
        className={radioGroupIndicatorVariants()}
      />
    </RadioGroupPrimitive.Item>
  );
});
