import React, { useState } from 'react';
import { WebComponent } from '../../webComponent/WebComponent';
import { UNAccount, UNComponentsError, UNComponentsOnLoadResponse, UNComponentsOnLoadResponseData } from '../../types/shared';
import { PresentationMode, WebComponentType } from '../../types/internal/webComponent.types';
import { WebViewMessage } from '../../messages/webMessages';
import { getProgramDetailsParams } from './UNProgramDetailsComponent.utils';
import { withReduxStore } from '../../helpers/store/helpers';
import { RESPONSE_KEYS, UnitOnLoadResponseEvent } from '../../messages/webMessages/onLoadMessage';
import { UnitComponentsMessage } from '../../messages/webMessages/unitComponentsMessages';
import { HeightEvent, PageMessage } from '../../messages/webMessages/pageMessage';
import { UNBaseView } from '../../nativeComponents/UNBaseView';

export interface UNProgramDetailsComponentProps {
  // inputs
  accountId: string;

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

  // events
  onLoad?: (response: UNComponentsOnLoadResponse<[UNAccount]>) => void;
}

const UNProgramDetailsComponent =  (props: UNProgramDetailsComponentProps) => {
  const [height, setHeight] = useState(0);

  const handleUnitOnLoad = (response: UnitOnLoadResponseEvent) => {
    console.log('handleUnitOnLoad', response);

    if (!props.onLoad) {
      return;
    }

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

    if (RESPONSE_KEYS.account in response) {
      props.onLoad(response[RESPONSE_KEYS.account] as UNComponentsOnLoadResponseData<[UNAccount]>);
      return;
    }

    console.error('On Load Error: unexpected response type.');
    return;
  };

  const handleMessage = (message: WebViewMessage) => {
    switch (message.type) {
      case UnitComponentsMessage.UNIT_ON_LOAD:
        handleUnitOnLoad(message.details as UnitOnLoadResponseEvent);
        break;

      case PageMessage.PAGE_HEIGHT:
        setHeight((message.details as HeightEvent).height);
        break;
    }
  };

  return (
    <UNBaseView style={{ height, width: '100%' }} onLoadError={ handleUnitOnLoad } fallback={<></>}>
      <WebComponent
        type={WebComponentType.programDetails}
        presentationMode={PresentationMode.Default}
        params={getProgramDetailsParams(props)}
        theme={props.theme}
        language={props.language}
        onMessage={handleMessage}
      />
    </UNBaseView>
  );
};

export default withReduxStore<UNProgramDetailsComponentProps>(UNProgramDetailsComponent);
