import { forwardRef } from 'react';
import { Switch as RNSwitch, type SwitchProps as RNSwitchProps } from 'react-native';
import { mergeDataAttributes, type IUseSwitchReturn } from '@cdx-ui/primitives';
import { cn, composeEventHandlers } from '@cdx-ui/utils';
import {
  switchIosBgVariants,
  switchThumbColorVariants,
  switchTrackOffVariants,
  switchTrackOnVariants,
} from './styles';

export interface BaseSwitchProps extends Omit<
  RNSwitchProps,
  | 'value'
  | 'disabled'
  | 'onValueChange'
  | 'thumbColor'
  | 'trackColor'
  | 'ios_backgroundColor'
  | 'className'
> {
  switchState: IUseSwitchReturn;
  className?: string;
  size?: string | null;
}

/**
 * Native host for `Switch`. Renders `RNSwitch` with Uniwind className passthrough
 * derived from the resolved interaction state in `switchState`.
 *
 * All state/a11y/interaction machinery lives in the `useSwitch` hook; this file
 * is pure rendering (Standard 3: primitives must not carry styling machinery).
 */
export const BaseSwitch = forwardRef<RNSwitch, BaseSwitchProps>(
  ({ switchState, className, size: _size, onFocus, onBlur, ...props }, ref) => {
    const uniwindProps: Record<string, string | undefined> = {
      className,
      thumbColorClassName: cn(switchThumbColorVariants({ isDisabled: switchState.isDisabled })),
      trackColorOnClassName: cn(switchTrackOnVariants({ isInvalid: switchState.isInvalid })),
      trackColorOffClassName: cn(switchTrackOffVariants({ isInvalid: switchState.isInvalid })),
      ios_backgroundColorClassName: cn(switchIosBgVariants({ isInvalid: switchState.isInvalid })),
    };

    return (
      <RNSwitch
        ref={ref}
        value={switchState.checked}
        disabled={switchState.isDisabled}
        onValueChange={switchState.setChecked}
        onFocus={composeEventHandlers(onFocus, switchState.focusProps.onFocus)}
        onBlur={composeEventHandlers(onBlur, switchState.focusProps.onBlur)}
        {...uniwindProps}
        {...props}
        {...mergeDataAttributes(props, switchState.dataAttrs)}
      />
    );
  },
);

BaseSwitch.displayName = 'BaseSwitch';
