import React, { useState } from 'react';
import { UNCardMenuAction, UNComponentsError, UNComponentsOnLoadResponse } from '../../types/shared';
import { withReduxStore } from '../../helpers/store/helpers';
import type { WebViewMessage } from '../../messages/webMessages';
import { HeightEvent, PageMessage } from '../../messages/webMessages/pageMessage';
import { UnitComponentsMessage } from '../../messages/webMessages/unitComponentsMessages';
import { UNBaseView } from '../../nativeComponents/UNBaseView';
import { RESPONSE_KEYS, UnitOnLoadResponseEvent } from '../../messages/webMessages/onLoadMessage';
import { WebComponent } from '../../webComponent/WebComponent';
import { PresentationMode, WebComponentType } from '../../types/internal/webComponent.types';
import { getCardActionParams, getCardActionScript } from './UNCardActionComponent.utils';
import { Dimensions } from 'react-native';

export interface UNCardActionComponentProps {
  // inputs
  cardId: string;
  action: UNCardMenuAction;

  // ui
  theme?: string;
  language?: string;

  // callbacks
  onLoad?: (response: UNComponentsOnLoadResponse<undefined>) => void
  onCloseFlow?: () => void
}

const DEFAULT_HEIGHT = Dimensions.get('window').height * 0.5;
const UNCardActionComponent = (props: UNCardActionComponentProps) => {
  const [defaultHeight, setDefaultHeight] = useState<number>();

  const handleUnitOnLoad = (response: UnitOnLoadResponseEvent) => {
    if (!props.onLoad) {
      return;
    }

    if (RESPONSE_KEYS.errors in response) {
      props.onLoad(response as UNComponentsError);
      return;
    }

    props.onLoad({ data: undefined });
  };

  const handleMessage = (message: WebViewMessage) => {
    if (!message) return;

    switch (message.type) {
      case PageMessage.PAGE_HEIGHT: {
        const currentHeight = (message.details as HeightEvent).height;
        currentHeight === 0 && setDefaultHeight(DEFAULT_HEIGHT);
        break;
      }
      case UnitComponentsMessage.UNIT_ON_LOAD:
        handleUnitOnLoad(message.details as UnitOnLoadResponseEvent);
        break;
      case UnitComponentsMessage.UNIT_REQUEST_CLOSE_FLOW:
        props.onCloseFlow && props.onCloseFlow();
        break;
    }
  };

  const style = defaultHeight ? { height: defaultHeight } : { flex: 1 };
  return (
    <UNBaseView style={style} onLoadError={ handleUnitOnLoad } fallback={<></>}>
      <WebComponent
        type={WebComponentType.cardAction}
        presentationMode={PresentationMode.Inherit}
        params={getCardActionParams(props)}
        theme={props.theme}
        language={props.language}
        script={getCardActionScript()}
        onMessage={message => handleMessage(message)}
        isScrollable={true}
      />
    </UNBaseView>
  );
};

export default withReduxStore<UNCardActionComponentProps>(UNCardActionComponent);
