import React from 'react';
import { LLWidgetHeader } from '../LLWidgetHeader';
import { LLWidgetFooter } from '../LLWidgetFooter';
import {
  useWidgetInteractiveTimeout,
  useWidgetExpiryEffect,
  usePredictionWidgetEffect,
} from '../../hooks';
import { LLCoreWidget } from '../LLCoreWidget';
import { LLNumberPredictionFollowUpWidget } from './LLNumberPredictionFollowUpWidget';
import { LLBaseWidgetProps } from '../LLBaseWidgetProps';
import {
  LLNumberPredictionWidgetBody,
  LLNumberPredictionWidgetBodyProps,
} from './LLNumberPredictionWidgetBody';
import { LLNumberPredictionWidgetActionInfo } from './LLNumberPredictionWidgetActionInfo';

export type LLNumberPredictionWidgetProps = LLBaseWidgetProps & {
  inlineFollowUp?: boolean;
  BodyComponent?: typeof LLNumberPredictionWidgetBody;
  BodyComponentStyles?: LLNumberPredictionWidgetBodyProps['styles'];
};

export function LLNumberPredictionWidget({
  programId,
  widgetId,
  widgetKind,
  inlineFollowUp,
  onDismiss: onDismissProp,
  interactiveTimeout: interactiveTimeoutProp,
  onInteractiveTimeout: onInteractiveTimeoutProp,
  WidgetComponent = LLCoreWidget,
  HeaderComponent = LLWidgetHeader,
  BodyComponent = LLNumberPredictionWidgetBody,
  FooterComponent = LLWidgetFooter,
  WidgetComponentStyles,
  HeaderComponentStyles,
  BodyComponentStyles,
  FooterComponentStyles,
}: LLNumberPredictionWidgetProps) {
  const { interactiveTimeout, onInteractiveTimeout } =
    useWidgetInteractiveTimeout({
      widgetId,
      interactiveTimeout: interactiveTimeoutProp,
      onInteractiveTimeout: onInteractiveTimeoutProp,
    });
  useWidgetExpiryEffect({ widgetId });

  const { followUpWidget } = usePredictionWidgetEffect({
    widgetId,
    programId,
    inlineFollowUp,
  });

  if (followUpWidget && inlineFollowUp) {
    return (
      <LLNumberPredictionFollowUpWidget
        widgetId={followUpWidget.id}
        widgetKind={followUpWidget.kind}
        programId={programId}
      />
    );
  }

  return (
    <WidgetComponent
      widgetId={widgetId}
      widgetKind={widgetKind}
      programId={programId}
      onDismiss={onDismissProp}
      styles={WidgetComponentStyles}
    >
      {({ widget, onDismiss }) => (
        <>
          <HeaderComponent
            title={widget.question}
            interactiveTimeout={interactiveTimeout}
            onInteractiveTimeout={onInteractiveTimeout}
            onDismiss={onDismiss}
            dismissable={!!onDismissProp}
            styles={HeaderComponentStyles}
          />
          <BodyComponent widgetId={widgetId} styles={BodyComponentStyles} />
          <FooterComponent
            styles={FooterComponentStyles}
            widgetId={widgetId}
            ActionInfoComponent={LLNumberPredictionWidgetActionInfo}
          />
        </>
      )}
    </WidgetComponent>
  );
}
