import React from 'react';
import { useReducedMotion } from 'react-native-reanimated';
import { createContext } from '@cdx-ui/utils';
import type {
  GlobalAnimationSettingsContextValue,
  GlobalAnimationSettingsProviderProps,
  AnimationSettingsContextValue,
} from './types';

const [GlobalAnimationSettingsProviderComponent, useGlobalAnimationSettings] =
  createContext<GlobalAnimationSettingsContextValue>('GlobalAnimationSettingsContext', {
    strict: false,
    defaultValue: { globalIsAllAnimationsDisabled: false },
  });

export { useGlobalAnimationSettings };

/**
 * GlobalAnimationSettingsProvider Component
 *
 * @description
 * Provider component that controls global animation settings across the application.
 * When animation is set to 'disable-all', all animations will be disabled globally.
 * Additionally, if the user has enabled reduce motion in accessibility settings,
 * all animations will be disabled automatically.
 *
 * The global setting is read directly via `useGlobalAnimationSettings`; the
 * separate `AnimationSettingsProvider` handles per-subtree cascading. Both
 * contexts are non-strict, so components can read them without a provider
 * mounted (falling back to "animations enabled").
 *
 * @param {GlobalAnimationSettingsProviderProps} props - Provider props
 * @param {AnimationRootDisableAll} [props.animation] - Global animation setting
 * @param {ReactNode} props.children - Child components to wrap
 */
export const GlobalAnimationSettingsProvider: React.FC<GlobalAnimationSettingsProviderProps> = ({
  animation,
  children,
}) => {
  const reducedMotion = useReducedMotion();
  const globalIsAllAnimationsDisabled = animation === 'disable-all' || reducedMotion;

  return (
    <GlobalAnimationSettingsProviderComponent value={{ globalIsAllAnimationsDisabled }}>
      {children}
    </GlobalAnimationSettingsProviderComponent>
  );
};

export const [AnimationSettingsProvider, useAnimationSettings] =
  createContext<AnimationSettingsContextValue>('AnimationSettingsContext', {
    strict: false,
    defaultValue: { isAllAnimationsDisabled: false },
  });
