"use client"

import * as React from "react"
import * as SwitchPrimitives from "@radix-ui/react-switch"

import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "../../../lib/utils"

const switchVariants = cva(
  "",
    {
    variants:{
      variant:{
        primary:"data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
        secondary:'data-[state=checked]:bg-green-300 data-[state=unchecked]:bg-input',
      },
      size: {
        default: " rounded-full",
        sm: "rounded-sm"
      }
    }
  }
)

const Switch = React.forwardRef<
  React.ElementRef<typeof SwitchPrimitives.Root>,
  React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root> & 
  VariantProps<typeof switchVariants> & {
    onChange?: (isChecked: boolean) => void; 
  }
>(({ className, variant, size, onChange, ...props }, ref) => {
  const [isChecked, setIsChecked] = React.useState(false);

  const handleToggle = () => {
    const newState = !isChecked;
    setIsChecked(newState);
    if (onChange) {
      onChange(newState);
    }
  };
  return (
    <SwitchPrimitives.Root
      className={cn(
        switchVariants({ variant, size }),
        "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center  border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 ",
        className
      )}
      {...props}
      ref={ref}
      // Toggle switch state on click
      onClick={handleToggle}
    >
      <SwitchPrimitives.Thumb
        className={cn(
          switchVariants({ size }),
          "pointer-events-none block h-4 w-4 bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
        )}
      />
    </SwitchPrimitives.Root>
  );
});
Switch.displayName = SwitchPrimitives.Root.displayName;

export { Switch };