import React, { useCallback } from 'react';
import {
  LLWidgetSubmitButtonComponent,
  LLWidgetSubmitButtonProps,
} from '../LLWidgetFooter';
import {
  useIsEndWidgetUIPhase,
  useIsWidgetDisabled,
  useUserNumberOptions,
  useWidgetSubmitAction,
} from '../../hooks';
import { INumberPredictionItemOption } from '@livelike/javascript';

export type LLNumberPredictionWidgetSubmitButtonProps =
  LLWidgetSubmitButtonProps & {
    onPress?: (arg: { numberOptions: INumberPredictionItemOption[] }) => void;
  };

export function LLNumberPredictionWidgetSubmitButton({
  widgetId,
  styles,
  onPress,
}: LLNumberPredictionWidgetSubmitButtonProps) {
  const numberOptions = useUserNumberOptions({ widgetId });
  const widgetDisabled = useIsWidgetDisabled({ widgetId });
  const isEndWidgetUIPhase = useIsEndWidgetUIPhase({ widgetId });
  const { onInteractionSubmit } = useWidgetSubmitAction({ widgetId });

  const onSubmit = useCallback(() => {
    onPress?.({ numberOptions });
    const interactionItem = { options: numberOptions };
    onInteractionSubmit({ interactionItem });
  }, [numberOptions]);

  if (isEndWidgetUIPhase) {
    return undefined;
  }

  const disabled = widgetDisabled || isInvalidNumberOptions(numberOptions);

  return (
    <LLWidgetSubmitButtonComponent
      disabled={disabled}
      onPress={onSubmit}
      styles={styles}
    />
  );
}

function isInvalidNumberOptions(numberOptions?: INumberPredictionItemOption[]) {
  if (!numberOptions?.length) {
    return true;
  }
  for (let i = 0; i < 2; i++) {
    if (!numberOptions[i] || numberOptions[i].number === undefined) {
      return true;
    }
  }
  return false;
}
