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

export interface UNNextRepaymentComponentProps {
  // inputs
  accountId: string;

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

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

const UNNextRepaymentComponent = (props: UNNextRepaymentComponentProps) => {

  const [height, setHeight] = useState(0);

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

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

    if (RESPONSE_KEYS.repayment in response) {
      props.onLoad(response[RESPONSE_KEYS.repayment] as UNComponentsOnLoadResponseData<[UNCreditAccountRepaymentInformation]>);
      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.nextRepayment}
        presentationMode={PresentationMode.Default}
        params={getNextRepaymentParams(props)}
        theme={props.theme}
        language={props.language}
        onMessage={message => handleMessage(message)}
        isScrollable={false}
      />
    </UNBaseView>
  );
};

export default withReduxStore<UNNextRepaymentComponentProps>(UNNextRepaymentComponent);
