import {
  INumberPredictionItemOption,
  IWidgetOptionItem,
  WidgetKind,
} from '@livelike/javascript';
import { useMemo } from 'react';
import { useIsWidgetDisabled } from './useIsWidgetDisabled';
import { useWidget } from './useWidget';
import { useWidgetInteractions } from './useWidgetInteractions';
import { useWidgetOptions } from './useWidgetOptions';

export type UseNumberPredictionWidgetOptionArg = {
  widgetId: string;
  optionIndex: number;
  numberOption: INumberPredictionItemOption;
};

export type NumberPredictionWidgetOptionDetails = {
  widgetOption: IWidgetOptionItem;
  interactedNumberOption: INumberPredictionItemOption;
  showWidgetResult: boolean;
  isCorrect: boolean;
  isWidgetOptionDisabled: boolean;
};

const NUMBER_PREDICTION_FOLLOW_UP_WIDGET_KIND = [
  WidgetKind.IMAGE_NUMBER_PREDICTION_FOLLOW_UP,
  WidgetKind.TEXT_NUMBER_PREDICTION_FOLLOW_UP,
];

export function useNumberPredictionWidgetOption({
  widgetId,
  optionIndex,
  numberOption,
}: UseNumberPredictionWidgetOptionArg): NumberPredictionWidgetOptionDetails {
  const widgetOptions = useWidgetOptions({ widgetId });
  const isWidgetOptionDisabled = useIsWidgetDisabled({ widgetId });
  const widgetInteractions = useWidgetInteractions({ widgetId });
  const widget = useWidget({ widgetId });
  const widgetOption = widgetOptions?.[optionIndex];
  const widgetOptionId = widgetOption?.id;

  const interactedNumberOption = useMemo(() => {
    if (!widgetInteractions?.length || !widgetInteractions[0]?.votes?.length) {
      return numberOption;
    }
    const widgetInteraction = widgetInteractions[0];
    const currentVote = widgetInteraction.votes.find(
      (option) => option.option_id === widgetOptionId
    );
    if (!currentVote) {
      return numberOption;
    }
    return { optionId: currentVote.id, number: currentVote.number };
  }, [widgetInteractions, optionIndex, numberOption, widgetOptionId]);

  const widgetKind = widget.kind;

  const showWidgetResult =
    NUMBER_PREDICTION_FOLLOW_UP_WIDGET_KIND.includes(widgetKind);

  if (!widgetOptions || !widgetOption) {
    return undefined;
  }

  const isCorrect =
    widgetOption.correct_number === interactedNumberOption?.number;

  return {
    isCorrect,
    widgetOption,
    showWidgetResult,
    interactedNumberOption,
    isWidgetOptionDisabled,
  };
}
