import { useEffect, useState, useCallback } from 'react';
import { StyleSheet, View } from 'react-native';
import TBLClassicUnitController from './classic/TBLClassicUnitController';
import TBLRNTPluginViewNativeComponent from './TBLRNTPluginViewNativeComponent';
import type TBLClassicPage from './classic/TBLClassicPage';
import type { OnResizeArgs } from './types';
import { INITIAL_VIEW_HEIGHT } from './consts';

interface TBLClassicUnitProps {
  tblClassicUnitController: TBLClassicUnitController | null;
  tblClassicPage: TBLClassicPage;
}

const TBLClassicUnit: React.FC<TBLClassicUnitProps> = (props) => {
  const { tblClassicUnitController, tblClassicPage } = props;
  const [height, setHeight] = useState(
    tblClassicUnitController?.height ?? INITIAL_VIEW_HEIGHT
  );

  const resizeHandler = useCallback((event: OnResizeArgs) => {
    setHeight(event.height);
  }, []);

  useEffect(() => {
    if (!tblClassicUnitController) return;
    tblClassicUnitController.setResizeListener(resizeHandler);
  }, [tblClassicUnitController, resizeHandler]);

  useEffect(() => {
    return () => {
      if (tblClassicUnitController) {
        tblClassicUnitController.clear();
      }
    };
  }, [tblClassicUnitController]);

  // Render empty view is tblClassicUnitController or tblClassicPage is not available yet on the native side
  if (!tblClassicUnitController?.unitId || !tblClassicPage.pageId) {
    console.log('[TBLClassicUnit] render: TBLClassicUnitController not found');
    return <View style={styles.emptyPlaceHolderView} />;
  }

  return (
    <TBLRNTPluginViewNativeComponent
      initValues={{
        unitId: tblClassicUnitController.unitId,
        pageId: tblClassicPage.pageId!,
      }}
      style={{
        height: height,
        // https://tbla.atlassian.net/browse/MOB-4844
        // Using flex: 1 instead of width: '100%' to fix Android issue
        // where initial visible event didn't fire properly on release mode
        flex: 1,
      }}
    />
  );
};

const styles = StyleSheet.create({
  emptyPlaceHolderView: {
    height: INITIAL_VIEW_HEIGHT,
  },
});

export default TBLClassicUnit;
