import React, { useEffect, useMemo, useState } from 'react'
import {
  DeviceEventEmitter,
  NativeEventEmitter,
  NativeModules,
  Platform,
  StyleSheet,
  View,
  ViewProps,
} from 'react-native'
import { requireNativeComponent } from 'react-native'

// On the New Architecture (bridgeless + Fabric) the legacy
// `UIManagerModule.updateNodeSize` path used by the native Android view is
// unavailable, so the native side reports its measured size via a device event
// instead and JS sizes the container, mirroring the iOS behaviour.
const isFabricEnabled =
  (globalThis as unknown as { nativeFabricUIManager?: unknown })
    ?.nativeFabricUIManager != null

interface ApxorViewManagerProps extends ViewProps {
  storiesID?: number
}

export const ApxorStoryViewManager =
  requireNativeComponent<ApxorViewManagerProps>('ApxorStoryViewManager')

interface ApxorStoryWidgetProps extends ViewProps {
  storiesID?: number
}
const StoryView = requireNativeComponent<ApxorStoryWidgetProps>('APXRNStory')

const ApxorStoryWidget: React.FC<ApxorStoryWidgetProps> = ({ storiesID }) => {
  const [storyDimensions, setstoryDimensions] = useState({
    height: 0,
    width: 0,
  })
  const eventEmitter = useMemo(
    () => new NativeEventEmitter(NativeModules.APXRNEventEmitter),
    [],
  )

  useEffect(() => {
    if (Platform.OS === 'android') {
      // Legacy Architecture sizes the view natively, no JS handling required.
      if (!isFabricEnabled) {
        return
      }
      const subscription = DeviceEventEmitter.addListener(
        'canShow',
        (dimensions) => {
          if (dimensions.id === storiesID) {
            setstoryDimensions(dimensions)
          }
        },
      )

      return () => {
        subscription.remove()
      }
    }
    const subscription = eventEmitter.addListener('canShow', (dimensions) => {
      if (dimensions.id === storiesID) {
        setstoryDimensions(dimensions)
      }
    })

    const subscription2 = eventEmitter.addListener(
      'removeStoryPlaceHolder',
      (dimensions) => {
        if (dimensions.activeCards) {
          if (!dimensions.activeCards.includes(storiesID?.toString())) {
            setstoryDimensions(dimensions)
          }
        }
      },
    )

    return () => {
      subscription.remove()
      subscription2.remove()
    }
  }, [storiesID, eventEmitter])

  if (Platform.OS === 'android') {
    if (!isFabricEnabled) {
      return (
        <View style={styles.viewManager}>
          <ApxorStoryViewManager storiesID={storiesID} />
        </View>
      )
    }
    return (
      <View
        style={[
          styles.container,
          { height: storyDimensions.height, width: `100%` },
        ]}
        testID={storiesID?.toString()}
        nativeID={storiesID?.toString()}
      >
        <ApxorStoryViewManager
          storiesID={storiesID}
          style={styles.fabricChild}
        />
      </View>
    )
  }

  return (
    <View
      style={[
        styles.container,
        { height: storyDimensions.height, width: `100%` },
      ]}
      testID={storiesID?.toString()}
      nativeID={storiesID?.toString()}
      pointerEvents="box-none"
    >
      <StoryView storiesID={storiesID}
        style={{ width: '100%', height: storyDimensions.height }}
        pointerEvents="auto" />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    overflow: 'hidden', // Ensure that contents are clipped if they exceed the specified dimensions
  },
  fabricChild: {
    flex: 1,
  },
  viewManager: {
    width: '100%',
  },
})

export default ApxorStoryWidget
