"use client";

import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";

import { cn } from "@/lib/utils";
import { useHiddenInputSync } from "@/components/ui/use-hidden-input-sync";

type CheckboxProps = React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root> & {
  name?: string;
  checkedValue?: string;
  uncheckedValue?: string;
};

const Checkbox = React.forwardRef<
  React.ElementRef<typeof CheckboxPrimitive.Root>,
  CheckboxProps
>(({ className, name, checked, defaultChecked, onCheckedChange, checkedValue = "on", uncheckedValue = "false", ...props }, ref) => {
  const [internalChecked, setInternalChecked] = React.useState(defaultChecked === true);
  const isControlled = checked !== undefined;
  const currentChecked = isControlled ? checked === true : internalChecked;
  const hiddenValue = currentChecked ? checkedValue : uncheckedValue;
  const hiddenInputRef = useHiddenInputSync(hiddenValue);

  return (
    <>
      {name ? <input ref={hiddenInputRef} type="hidden" name={name} value={hiddenValue} /> : null}
      <CheckboxPrimitive.Root
        ref={ref}
        checked={checked}
        defaultChecked={defaultChecked}
        onCheckedChange={(nextChecked) => {
          if (!isControlled) {
            setInternalChecked(nextChecked === true);
          }
          onCheckedChange?.(nextChecked);
        }}
        className={cn(
          "peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
          className,
        )}
        {...props}
      >
        <CheckboxPrimitive.Indicator className="flex items-center justify-center text-current">
          <Check className="h-3.5 w-3.5" />
        </CheckboxPrimitive.Indicator>
      </CheckboxPrimitive.Root>
    </>
  );
});

Checkbox.displayName = CheckboxPrimitive.Root.displayName;

export { Checkbox };
