import * as React from "react"
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox"
import { cn } from "../core/cn"

interface CheckboxProps extends CheckboxPrimitive.Root.Props {
  label?: string
  indeterminate?: boolean
  className?: string
  labelClassName?: string
}

function Checkbox({ className, label, id, indeterminate, ...props }: CheckboxProps) {
  const internalId = React.useId()
  const checkboxId = id ?? internalId

  return (
    <div className="flex items-center gap-2">
      <CheckboxPrimitive.Root
        id={checkboxId}
        data-slot="checkbox"
        className={cn(
          "peer size-4 shrink-0 rounded border border-input bg-transparent transition-colors outline-none",
          "focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",
          "data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground",
          "data-indeterminate:border-primary data-indeterminate:bg-primary data-indeterminate:text-primary-foreground",
          "disabled:pointer-events-none disabled:opacity-50",
          className
        )}
        indeterminate={indeterminate}
        {...props}
      >
        <CheckboxPrimitive.Indicator
          data-slot="checkbox-indicator"
          className="flex items-center justify-center text-current"
        >
          {indeterminate ? (
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="3"
              strokeLinecap="round"
              className="size-3"
            >
              <line x1="5" y1="12" x2="19" y2="12" />
            </svg>
          ) : (
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="3"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="size-3"
            >
              <polyline points="20 6 9 17 4 12" />
            </svg>
          )}
        </CheckboxPrimitive.Indicator>
      </CheckboxPrimitive.Root>
      {label && (
        <label
          htmlFor={checkboxId}
          data-slot="checkbox-label"
          className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-50 cursor-pointer select-none"
        >
          {label}
        </label>
      )}
    </div>
  )
}

export { Checkbox }
export type { CheckboxProps }
