import React, { useState } from 'react';
import { UNBaseView } from '../../nativeComponents/UNBaseView';
import { WebComponent } from '../../webComponent/WebComponent';
import { PresentationMode, WebComponentType } from '../../types/internal/webComponent.types';
import { withReduxStore } from '../../helpers/store/helpers';
import { getCreateCardParams } from './UNCreateCardComponent.utils';
import type { WebViewMessage } from '../../messages/webMessages';
import { HeightEvent, PageMessage } from '../../messages/webMessages/pageMessage';
import { UnitComponentsMessage } from '../../messages/webMessages/unitComponentsMessages';
import { UNCard, UNComponentsError, UNComponentsOnLoadResponse, UNComponentsOnLoadResponseData } from '../../types/shared';
import { RESPONSE_KEYS, UnitOnLoadResponseEvent } from '../../messages/webMessages/onLoadMessage';
import { UNCreateCardComponentResources, UNCreateCardType } from '../../types/shared/createCard.types';
import { CardCreatedEvent, CardMessage } from '../../messages/webMessages/cardMessage';
import { eventBus } from '../../utils/eventBus';

export interface UNCreateCardComponentProps {
  // inputs
  accountId?: string;
  cardTypes: UNCreateCardType[];
  virtualCardFee?: number;
  physicalCardFee?: number;

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

  // callbacks
  onLoad?: (response: UNComponentsOnLoadResponse<UNCreateCardComponentResources>) => void
  onCardCreated?: (cardData: UNCard) => void
}

const UNCreateCardComponent = (props: UNCreateCardComponentProps) => {
  const [height, setHeight] = useState<number>(0);
  const [presentationMode, setPresentationMode] = useState<PresentationMode>(PresentationMode.Inherit);

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

    if (RESPONSE_KEYS.errors in response) {
      props.onLoad(response as UNComponentsError);
      return;
    }
    if (RESPONSE_KEYS.createCardResult in response) {
      const createCardResponse = response[RESPONSE_KEYS.createCardResult] as UNComponentsOnLoadResponseData<UNCreateCardComponentResources>;
      props.onLoad(createCardResponse);
      return;
    }
    // Ignore cardResult - card creation handled by onCardCreated
    if (RESPONSE_KEYS.card in response) {
      return;
    }
    console.error('On Load Error: unexpected response type.');
    return;
  };

  const handleWebViewMessage = (message: WebViewMessage) => {
    if (!message || !message.details) return;

    switch (message.type) {
      case UnitComponentsMessage.UNIT_ON_LOAD:
        handleUnitOnLoad(message.details as UnitOnLoadResponseEvent);
        break;
      case PageMessage.PAGE_HEIGHT: {
        const currentHeight = (message.details as HeightEvent).height;
        setHeight(currentHeight);
        if (presentationMode === PresentationMode.Inherit && currentHeight === 0) {
          setPresentationMode(PresentationMode.Default);
        }
        break;
      }
      case CardMessage.CARD_CREATED:
        eventBus.emit(
          CardMessage.CARD_CREATED,
          (message.details as CardCreatedEvent)
        );
        props.onCardCreated && props.onCardCreated(message.details as UNCard);
        break;
    }
  };

  const style = presentationMode === PresentationMode.Inherit ? { flex: 1 } : { height: height };
  return <UNBaseView style={style} onLoadError={handleUnitOnLoad} fallback={<></>}>
    <WebComponent
      type={WebComponentType.createCard}
      presentationMode={PresentationMode.Inherit}
      params={getCreateCardParams(props)}
      onMessage={(message: WebViewMessage) => handleWebViewMessage(message)}
      theme={props.theme}
      language={props.language}
    />
  </UNBaseView>;
};

export default withReduxStore<UNCreateCardComponentProps>(UNCreateCardComponent);
