import { useEffect, useState } from 'react';

import SpinnerSVG from '@/components/svg/SpinnerSVG';

import { ChoiceButton } from './components/input/ChatChoices';
import { PresetSuggestion, useChatInputStore } from './stores';
import { usePresetsData } from './usePresetsData';
import { formatString, getOptionValue } from './utils';

type SuggestionProps = {
  suggestion: PresetSuggestion;
  index: number;
  suggestionIndexes: Record<string, number>[];
  onClickPreset: (text: string) => void;
};

export const Suggestion = ({
  suggestion,
  index,
  suggestionIndexes,
  onClickPreset,
}: SuggestionProps) => {
  const setInput = useChatInputStore((state) => state.setInput);
  const suggestionText = !!suggestion.options_config
    ? formatString(
        suggestion.template,
        Object.entries(suggestion.options_config ?? {}).reduce(
          (acc, [key, values]) => {
            const selectedOption =
              values.options[suggestionIndexes[index]?.[key] ?? 0];
            acc[key] = getOptionValue(
              selectedOption,
              values.prefix_with_article
            );
            return acc;
          },
          {} as Record<string, string>
        )
      )
    : suggestion.template;
  const suggestionButtonText = suggestion.button_text;
  return (
    <span className='flex gap-2'>
      <ChoiceButton
        className={
          'animate-[fade-in_1000ms_ease-out_forwards] bg-background-fog-thick text-[11px] backdrop-blur-xl'
        }
        choice={suggestionButtonText}
        onSelect={() => {
          onClickPreset(suggestionText);
          setInput('');
        }}
      />
    </span>
  );
};

export const Presets = ({
  onClickPreset,
}: {
  onClickPreset: (preset: string) => void;
}) => {
  const presetsData = usePresetsData();
  const [suggestionIndexes, setSuggestionIndexes] = useState<
    Record<string, number>[] | null
  >(null);
  useEffect(() => {
    if (presetsData?.data) {
      setSuggestionIndexes(
        (presetsData.data.suggestions ?? []).map(
          (suggestion: PresetSuggestion) => {
            return Object.entries(suggestion.options_config ?? {}).reduce(
              (acc, [key, values]) => {
                const optionConfig = values;
                acc[key] = Math.floor(
                  Math.random() * (optionConfig?.options?.length ?? 0)
                );
                return acc;
              },
              {} as Record<string, number>
            );
          }
        )
      );
    }
  }, [presetsData.data]);
  if (presetsData.isLoading) {
    return (
      <div className='w-full text-center'>
        <SpinnerSVG />
      </div>
    );
  }

  if (presetsData.isError || !presetsData.data || !suggestionIndexes) {
    return null;
  }
  return (
    <div className='flex w-full flex-row justify-center px-12'>
      <div className='flex flex-row flex-wrap justify-center gap-2'>
        {(presetsData.data?.suggestions ?? []).map(
          (suggestion: PresetSuggestion, i: number) => (
            <Suggestion
              suggestion={suggestion}
              key={`${suggestion.button_text}-${i}`}
              index={i}
              suggestionIndexes={suggestionIndexes}
              onClickPreset={onClickPreset}
            />
          )
        )}
      </div>
    </div>
  );
};
