import React, { useEffect, useState, Fragment, ReactElement } from 'react';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { Platform, StyleSheet } from 'react-native';
import { PortalService } from './portal-service';
import { fp as _ } from '../fp';
import { StreamFactory } from '../stream-factory';

export const portalHack = new StreamFactory();

// @ts-ignore
export const PortalGate: () => ReactElement[] | null = () => {
  const [disbled, toggleDisable] = useState(true);
  const [portals, setPortal] = useState([]);
  const isAndroid = Platform.OS === 'android';

  useEffect(() => {
    const addSubscription = PortalService.addSubject$.subscribe(
      (payload: unknown) => {
        const updated = PortalService.update(payload as {
          id: string;
          children: React.ReactElement;
        });
        setPortal(updated);
      }
    );
    const removeSubscription = PortalService.removeSubject$.subscribe(
      (payload: unknown) => {
        const updated = PortalService.destroy(payload as string);
        setPortal(updated);
      }
    );

    portalHack.get().subscribe(value => {
      toggleDisable(value);
    });

    return () => {
      addSubscription.unsubscribe();
      removeSubscription.unsubscribe();
    };
  }, []);

  if (!_.length(portals)) {
    return null;
  }

  if (disbled && isAndroid) {
    return null;
  }

  const allPortals = portals.map(({ children, id }) => {
    return (
      <Fragment key={id}>
        {/*{React.Children.map(children, (child, i) => cloneElement(child))}*/}
        {children}
      </Fragment>
    );
  });

  if (!isAndroid) {
    return allPortals;
  }

  return (
    <GestureHandlerRootView
      style={[
        StyleSheet.absoluteFill,
        {
          flex: 1,
          height: '100%',
        },
      ]}
    >
      {allPortals}
    </GestureHandlerRootView>
  );
};
