import { forwardRef } from 'react';
import type { Switch as RNSwitch, View } from 'react-native';
import {
  dataAttributes,
  mergeDataAttributes,
  useSwitch,
  type ISwitchProps,
} from '@cdx-ui/primitives';
import { BaseSwitch } from './BaseSwitch';

export interface SwitchProps extends ISwitchProps {
  /**
   * Track and thumb size.
   * @default 'md'
   */
  size?: 'sm' | 'md' | 'lg';
  /** Additional Uniwind/Tailwind classes, merged after the switch's own styles. */
  className?: string;
  /** Accessible label announced by screen readers. */
  accessibilityLabel?: string;
  /** Called when the switch receives focus. */
  onFocus?: () => void;
  /** Called when the switch loses focus. */
  onBlur?: () => void;
}

export const Switch = forwardRef<RNSwitch | View, SwitchProps>(
  (
    {
      className,
      size,
      value,
      isChecked,
      defaultValue,
      disabled,
      isDisabled,
      isInvalid,
      onValueChange,
      ...props
    },
    ref,
  ) => {
    const switchState = useSwitch({
      value,
      isChecked,
      defaultValue,
      disabled,
      isDisabled,
      isInvalid,
      onValueChange,
    });

    return (
      <BaseSwitch
        ref={ref as never}
        switchState={switchState}
        className={className}
        size={size}
        {...props}
        {...mergeDataAttributes(props, dataAttributes({ slot: 'switch' }))}
      />
    );
  },
);

Switch.displayName = 'Switch';
