import type React from 'react';
import { forwardRef, useImperativeHandle, useRef } from 'react';
import {
  findNodeHandle,
  NativeModules,
  requireNativeComponent,
  type ViewProps,
} from 'react-native';
import type { DimensionsChangeEvent } from '../types/internal';
import type { InternalFlowConfig } from './FlowNativeComponent';

interface FlowProps extends ViewProps {
  config: InternalFlowConfig;
  onDimensionsChanged?: (event: DimensionsChangeEvent) => void;
}

export interface FlowPaperRef {
  submit: () => void;
  tokenize: () => void;
  update: (amount: number, currency?: string) => void;
}

const FlowPaperNative = requireNativeComponent<FlowProps>('FlowPaper');

const FlowPaper = forwardRef<FlowPaperRef, FlowProps>((props, ref) => {
  const nativeRef = useRef<React.ElementRef<typeof FlowPaperNative>>(null);

  useImperativeHandle(ref, () => ({
    submit: () => {
      const reactTag = findNodeHandle(nativeRef.current);
      if (reactTag && NativeModules.FlowPaper) {
        NativeModules.FlowPaper.submit(reactTag);
      }
    },
    tokenize: () => {
      const reactTag = findNodeHandle(nativeRef.current);
      if (reactTag && NativeModules.FlowPaper) {
        NativeModules.FlowPaper.tokenize(reactTag);
      }
    },
    update: (amount: number, currency?: string) => {
      const reactTag = findNodeHandle(nativeRef.current);
      if (reactTag && NativeModules.FlowPaper) {
        NativeModules.FlowPaper.update(reactTag, amount, currency);
      }
    },
  }));

  return <FlowPaperNative {...props} ref={nativeRef} />;
});

export default FlowPaper;
