import React, { useState } from "react";
import { CheckIcon } from "@radix-ui/react-icons";
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { cva, type VariantProps } from "class-variance-authority";
import { MouseEventHandler } from "react";
import { cn } from "../../lib/utils";

const radiogroupVariants = cva(
  "",
  {
    variants: {
      type: {
        sm: "rounded-sm",
        md: "rounded-md",
        lg: "rounded-lg",
        full: "rounded-full",
      },
    },
  }
);

export interface RadioOption {
  id: string;
  label: string;
}

interface RadioGroupProps {
  options: RadioOption[];
  defaultValue?: string;
  onClick?: MouseEventHandler<HTMLDivElement>;
  onSelect?: (label: string) => void; 
}

const RadioGroup: React.FC<RadioGroupProps & VariantProps<typeof radiogroupVariants>> = ({ options, type, defaultValue, onClick, onSelect }) => {
  const handleClick = (id: string) => {
    if (onSelect) {
      onSelect(id); 
    }
  };

  return (
    <RadioGroupPrimitive.Root defaultValue={defaultValue}>
      {options.map((option) => (
        <div key={option.id} className={cn(radiogroupVariants({ type }),"flex items-center space-x-2")} onClick={(e) => handleClick(option.id)}>
          <RadioGroupItem value={option.label} id={option.id} className={cn(radiogroupVariants({ type }))} />
          <label htmlFor={option.id}>{option.label}</label>
        </div>
      ))}
    </RadioGroupPrimitive.Root>
  );
};

const RadioGroupItem = React.forwardRef<
  React.ElementRef<typeof RadioGroupPrimitive.Item>,
  React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item> & VariantProps<typeof radiogroupVariants>
>(({ className, type, ...props }, ref) => {
  return (
    <RadioGroupPrimitive.Item
      ref={ref}
      className={cn(radiogroupVariants({ type }),
        "aspect-square h-4 w-4 border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
        className
      )}
      {...props}
    >
      <RadioGroupPrimitive.Indicator className="flex items-center justify-center">
        <CheckIcon className="h-3.5 w-3.5 fill-primary" />
      </RadioGroupPrimitive.Indicator>
    </RadioGroupPrimitive.Item>
  );
});

RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;

export { RadioGroup, RadioGroupItem };
