import { CHOICE_WIDGET_KIND } from '@livelike/javascript';
import { useMemo } from 'react';
import { useWidgetChoices } from './useWidgetChoices';
import { useWidgetInteractions } from './useWidgetInteractions';
import { useWidgetOptions } from './useWidgetOptions';

export type UseSelectedWidgetOption = {
  widgetId: string;
};

export function useInteractedWidgetOption({ widgetId }) {
  const widgetInteractions = useWidgetInteractions({ widgetId });
  const widgetOptions = useWidgetOptions({ widgetId });
  const widgetChoices = useWidgetChoices({ widgetId });
  return useMemo(() => {
    if (!widgetInteractions?.length) {
      return undefined;
    }
    if (CHOICE_WIDGET_KIND.includes(widgetInteractions[0].widget_kind)) {
      if (!widgetChoices?.length) {
        return undefined;
      }
      return widgetChoices.find(
        (option) => option.id === widgetInteractions[0].choice_id
      );
    }
    if (!widgetOptions?.length) {
      return undefined;
    }
    return widgetOptions.find((option) =>
      widgetInteractions.find(({ option_id }) => option.id === option_id)
    );
  }, [widgetInteractions, widgetOptions]);
}
