"use client";

import * as React from "react";
import { Check } from "lucide-react";

import { cn } from "@/lib/utils";

type CheckboxProps = Omit<React.InputHTMLAttributes<HTMLInputElement>, "type" | "onChange"> & {
  onCheckedChange?: (checked: boolean) => void;
};

const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
  ({ className, checked, defaultChecked, onCheckedChange, onBlur, onFocus, onClick, disabled, ...props }, ref) => {
    const isChecked = typeof checked === "boolean" ? checked : undefined;
    const dataState =
      typeof checked === "boolean" ? (checked ? "checked" : "unchecked") : defaultChecked ? "checked" : "unchecked";

    return (
      <span className="relative inline-flex items-center">
        <input
          ref={ref}
          type="checkbox"
          checked={isChecked}
          defaultChecked={defaultChecked}
          disabled={disabled}
          onChange={(event) => {
            onCheckedChange?.(event.target.checked);
          }}
          onBlur={onBlur}
          onFocus={onFocus}
          onClick={onClick}
          data-state={dataState}
          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 appearance-none",
            "data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
            className
          )}
          {...props}
        />
        <Check
          className={cn(
            "pointer-events-none absolute h-4 w-4 text-primary-foreground opacity-0 peer-data-[state=checked]:opacity-100"
          )}
        />
      </span>
    );
  }
);

Checkbox.displayName = "Checkbox";

export { Checkbox };
