import React from 'react';
import { clsx } from 'clsx';
import * as BaseCheckbox from '@radix-ui/react-checkbox';

import { forwardRef } from '../utils/react';
import { Box } from '../box';
import { CheckIcon } from '../icons';
import * as css from './checkbox.css';

export interface CheckboxProps extends css.ContainerVariants {
  className?: string;
  checked?: BaseCheckbox.CheckedState;
  defaultChecked?: BaseCheckbox.CheckedState;
  onChange?(checked: BaseCheckbox.CheckedState): void;
  children: React.ReactNode;
  required?: boolean;
  name?: string;
  value?: string;
}

export const Checkbox = forwardRef<'label', CheckboxProps>(function Checkbox(
  {
    as = 'label',
    className,
    children,
    defaultChecked,
    name,
    value,
    checked,
    disabled,
    required,
    onChange,
    ...rest
  },
  ref,
) {
  const containerClass = clsx(className, css.container({ disabled }));

  return (
    <Box {...rest} as={as} className={containerClass} ref={ref}>
      <BaseCheckbox.Root
        className={css.checkbox}
        defaultChecked={defaultChecked}
        required={required}
        value={value}
        name={name}
        disabled={disabled}
        checked={checked}
        onCheckedChange={onChange}
      >
        <BaseCheckbox.Indicator asChild>
          <CheckIcon className={css.icon} />
        </BaseCheckbox.Indicator>
      </BaseCheckbox.Root>
      <span>{children}</span>
    </Box>
  );
});

export type { CheckedState } from '@radix-ui/react-checkbox';
