import styles from './Toggle.module.css'
import { forwardRef, type InputHTMLAttributes } from 'react'

interface ToggleProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'type'> {
  label?: string
  id?: string
}

export const Toggle = forwardRef<HTMLInputElement, ToggleProps>(
  ({ label, id, className, ...rest }, ref) => {
    const inputId = id ?? `toggle-${Math.random().toString(36).slice(2)}`
    return (
      <label className={`${styles.wrapper} ${className ?? ''}`} htmlFor={inputId}>
        <input
          ref={ref}
          id={inputId}
          type="checkbox"
          className={styles.input}
          {...rest}
        />
        <span className={styles.track} aria-hidden="true">
          <span className={styles.thumb} />
        </span>
        {label && <span className={styles.label}>{label}</span>}
      </label>
    )
  },
)

Toggle.displayName = 'Toggle'
