import { ComponentPropsWithoutRef, MouseEvent, useMemo } from "react";
import AnswerItem from "../../AnswerDraggableList/AnswerItem";
import VariantAdornment from "./VariantAdornment";
import VariantAdornmentMobile from "./VariantAdornmentMobile";
import { updateQuestion } from "@/stores/questions/actions";

type Props = Omit<
  ComponentPropsWithoutRef<typeof AnswerItem>,
  "additionalContent" | "additionalMobile"
> & {
  isTablet: boolean;
  setAnchorElement: React.Dispatch<React.SetStateAction<HTMLDivElement | null>>;
  setSelectedVariant: React.Dispatch<React.SetStateAction<string | null>>;
  setOpen: React.Dispatch<React.SetStateAction<boolean>>;
  isOwn: boolean;
  ownPlaceholder: string;
};

export default function EmojiAnswerItem({
  index,
  questionId,
  variant,
  disableKeyDown,
  largeCheck,
  isTablet,
  setAnchorElement,
  setSelectedVariant,
  setOpen,
  isOwn,
  ownPlaceholder,
}: Props) {


  const clearEmoji = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation()
    updateQuestion(questionId, (question) => {
      if (question.type !== "emoji") return;

      const v = question.content.variants.find((v) => v.id === variant.id);
      if (!v) return;

      v.extendedText = "";
    });
  }
  const addOrEditImageButton = useMemo(() => {
    return (
      !isTablet && (
        <VariantAdornment
          extendedText={variant.extendedText}
          onClick={({ currentTarget }) => {
            setAnchorElement(currentTarget);
            setSelectedVariant(variant.id);
            setOpen(true);
          }}
          clearEmoji={clearEmoji}
        />
      )
    );
  }, [
    isTablet,
    variant.extendedText,
    variant.id,
    setAnchorElement,
    setSelectedVariant,
    setOpen,
  ]);

  const addOrEditImageButtonMobile = useMemo(() => {
    return (
      isTablet && (
        <VariantAdornmentMobile
          extendedText={variant.extendedText}
          onClick={({ currentTarget }) => {
            setAnchorElement(currentTarget);
            setSelectedVariant(variant.id);
            setOpen(true);
          }}
          clearEmoji={clearEmoji}
        />
      )
    );
  }, [
    isTablet,
    variant.extendedText,
    variant.id,
    setAnchorElement,
    setSelectedVariant,
    setOpen,
  ]);

  return (
    <AnswerItem
      index={index}
      disableKeyDown={disableKeyDown}
      questionId={questionId}
      largeCheck={largeCheck}
      variant={variant}
      additionalContent={addOrEditImageButton}
      additionalMobile={addOrEditImageButtonMobile}
      isOwn={isOwn}
      ownPlaceholder={ownPlaceholder}
    />
  );
}
