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 { InternalCardConfig } from './CardNativeComponent';

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

export interface CardPaperRef {
  submit: () => void;
  tokenize: () => void;
}

const CardPaperNative = requireNativeComponent<CardProps>('CardPaper');

const CardPaper = forwardRef<CardPaperRef, CardProps>((props, ref) => {
  const nativeRef = useRef<React.ElementRef<typeof CardPaperNative>>(null);

  useImperativeHandle(ref, () => ({
    submit: () => {
      const reactTag = findNodeHandle(nativeRef.current);
      if (reactTag && NativeModules.CardPaper) {
        NativeModules.CardPaper.submit(reactTag);
      }
    },
    tokenize: () => {
      const reactTag = findNodeHandle(nativeRef.current);
      if (reactTag && NativeModules.CardPaper) {
        NativeModules.CardPaper.tokenize(reactTag);
      }
    },
  }));

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

export default CardPaper;
