import { useRef } from 'react';
import { twMerge } from 'tailwind-merge';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import logWebUserEvent from '@/logging/logWebUserEvent';

import { useChatContext } from '../../useChat';
import { useChatMessageActions } from '../../useChatMessageActions';

type ChatChoicesProps = {
  choices?: string[];
};

export const ChoiceButton = ({
  choice,
  onSelect,
  className = '',
}: {
  choice: string;
  onSelect: () => void;
  className?: string;
}) => {
  return (
    <Button
      className={twMerge(
        'animate-[fade-in_300ms_ease-out_forwards] border border-border-primary bg-background-glass-thin/60 px-3 py-2 font-mono text-[10px] font-light whitespace-nowrap text-foreground-secondary uppercase opacity-0 backdrop-blur-lg',
        className
      )}
      variant={ButtonVariant.Standard}
      size={ButtonSize.Mini}
      shape={ButtonShape.Pill}
      onClick={onSelect}
    >
      {choice}
    </Button>
  );
};

export const ChatChoices = ({ choices }: ChatChoicesProps) => {
  const { handleSend: sendMessage } = useChatMessageActions();
  const { chatUUID } = useChatContext();
  const { session } = useStores();
  const choicesRef = useRef<HTMLDivElement>(null);
  if (!choices) return null;
  return (
    <div className='grid w-full max-w-full rounded-none'>
      <div
        className='scrollbar-hide flex h-auto w-full flex-nowrap gap-2 overflow-x-auto overflow-y-hidden rounded-none px-0 pb-3'
        role='toolbar'
        aria-label='Suggested responses'
        tabIndex={0}
        onKeyDown={(e) => {
          if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
            choicesRef.current?.scrollBy({
              left: e.key === 'ArrowRight' ? 100 : -100,
              behavior: 'smooth',
            });
          }
        }}
        onWheel={(e) => {
          if (choicesRef.current) {
            if (e.deltaY > 0 && Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
              choicesRef.current.scrollBy({
                left: -100,
                behavior: 'smooth',
              });
              e.preventDefault();
            } else if (
              e.deltaY < 0 &&
              Math.abs(e.deltaY) > Math.abs(e.deltaX)
            ) {
              choicesRef.current.scrollBy({
                left: 100,
                behavior: 'smooth',
              });
              e.preventDefault();
            }
          }
        }}
        ref={choicesRef}
      >
        {choices.map((choice, index) =>
          !!choice.trim()?.length ? (
            <ChoiceButton
              key={`${choice}-${index}`}
              choice={choice}
              onSelect={() => {
                logWebUserEvent(
                  {
                    actionName: 'OrpheusChatInputPivotClicked',
                    context: {
                      sessionId: chatUUID,
                      pivotText: choice,
                      pivotIndex: index,
                      totalPivots: choices.length,
                    },
                  },
                  session
                );
                sendMessage({ message: choice });
              }}
            />
          ) : null
        )}
      </div>
    </div>
  );
};
