import { splitProps, mergeProps, createSignal, JSX } from 'solid-js';
import clsx from 'clsx';

export interface ToggleProps {
  checked?: boolean;
  defaultChecked?: boolean;
  onChange?: (checked: boolean) => void;
  size?: 'sm' | 'md' | 'lg';
  disabled?: boolean;
  label?: string;
  class?: string;
}

/**
 * Toggle -- WAI-ARIA switch with glow transition and angular track/thumb.
 *
 * Supports controlled (checked prop) and uncontrolled (defaultChecked) modes.
 * Uses role="switch" with aria-checked for accessibility.
 * Space and Enter toggle via native button behavior.
 */
export function Toggle(rawProps: ToggleProps) {
  const merged = mergeProps({ size: 'md' as const }, rawProps);
  const [local, rest] = splitProps(merged, [
    'checked', 'defaultChecked', 'onChange', 'size', 'disabled', 'label', 'class',
  ]);

  // Internal state for uncontrolled mode
  const [internalChecked, setInternalChecked] = createSignal(local.defaultChecked ?? false);

  // Resolve checked state: controlled vs uncontrolled
  const isChecked = () => {
    if (local.checked !== undefined) {
      return local.checked;
    }
    return internalChecked();
  };

  const handleClick = () => {
    if (local.disabled) return;

    const next = !isChecked();

    // Update internal state (uncontrolled mode)
    if (local.checked === undefined) {
      setInternalChecked(next);
    }

    local.onChange?.(next);
  };

  return (
    <button
      type="button"
      role="switch"
      aria-checked={isChecked()}
      aria-label={local.label}
      disabled={local.disabled}
      class={clsx(
        'hh-toggle',
        isChecked() && 'hh-toggle--on',
        `hh-size-${local.size}`,
        'hh-disabled',
        local.class,
      )}
      onClick={handleClick}
      {...(rest as JSX.ButtonHTMLAttributes<HTMLButtonElement>)}
    >
      <div class="hh-toggle__track">
        <div class="hh-toggle__thumb" />
      </div>
      {local.label && (
        <span class="hh-toggle__label">{local.label}</span>
      )}
    </button>
  );
}
