import type { InputHTMLAttributes, ReactNode } from 'react';
import { useId } from 'react';
import './switch.css';

export type SwitchSize = 'sm' | 'md' | 'lg';
export type SwitchControlPosition = 'start' | 'end';

export type SwitchProps = {
  label?: ReactNode;
  size?: SwitchSize;
  /** Position of the switch control relative to the label. */
  controlPosition?: SwitchControlPosition;
} & Omit<InputHTMLAttributes<HTMLInputElement>, 'type' | 'role' | 'size'>;

export function Switch({
  label,
  size = 'sm',
  controlPosition = 'start',
  id: idProp,
  className,
  disabled,
  required,
  ...rest
}: SwitchProps) {
  const uid = useId();
  const id = idProp ?? `ccl-switch-${uid.replace(/:/g, '')}`;

  return (
    <label
      className={[
        'ccl-switch',
        `ccl-switch--${size}`,
        controlPosition === 'end' ? 'ccl-switch--end' : 'ccl-switch--start',
        disabled ? 'ccl-switch--disabled' : '',
        className ?? '',
      ]
        .filter(Boolean)
        .join(' ')}
      htmlFor={id}
    >
      <input
        id={id}
        type="checkbox"
        role="switch"
        disabled={disabled}
        required={required}
        className="ccl-switch__control"
        aria-required={required ? true : undefined}
        {...rest}
      />
      {label != null ? (
        <span className="ccl-switch__label">
          {label}
          {required ? (
            <span className="ccl-switch__required" aria-label="required">
              *
            </span>
          ) : null}
        </span>
      ) : null}
    </label>
  );
}

