import React from 'react';
import { LLWidgetHeader } from '../LLWidgetHeader';
import { LLWidgetFooter } from '../LLWidgetFooter';
import {
  useWidgetInteractiveTimeout,
  useWidgetExpiryEffect,
  usePredictionWidgetEffect,
} from '../../hooks';
import { LLCoreWidget } from '../LLCoreWidget';
import { LLVoteWidgetBody, LLVoteWidgetBodyProps } from '../LLVoteWidgetBody';
import { LLPredictionFollowUpWidget } from './LLPredictionFollowUpWidget';
import { LLBaseWidgetProps } from '../LLBaseWidgetProps';
import { LLPredictionWidgetActionInfo } from './LLPredictionWidgetActionInfo';

export type LLPredictionWidgetProps = LLBaseWidgetProps & {
  inlineFollowUp?: boolean;
  BodyComponent?: typeof LLVoteWidgetBody;
  BodyComponentStyles?: LLVoteWidgetBodyProps['styles'];
};

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

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

  if (followUpWidget && inlineFollowUp) {
    return (
      <LLPredictionFollowUpWidget
        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={LLPredictionWidgetActionInfo}
          />
        </>
      )}
    </WidgetComponent>
  );
}
