import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
import { ComponentPropsWithoutRef, useMemo } from "react";
import AnswerItem from "../AnswerDraggableList/AnswerItem";

type Props = Omit<
  ComponentPropsWithoutRef<typeof AnswerItem>,
  "additionalContent" | "additionalMobile"
> & {
  isMobile: boolean;
  pictureUploding: boolean;
  setSelectedVariantId: (id: string | null) => void;
  openCropModal: (
    image: string | Blob,
    originalImageUrl?: string | null | undefined,
  ) => Promise<void>;
  openImageUploadModal: () => void;
  isOwn: boolean;
};

export default function ImageEditAnswerItem({
  index,
  questionId,
  variant,
  disableKeyDown,
  largeCheck,
  isMobile,
  setSelectedVariantId,
  pictureUploding,
  openCropModal,
  openImageUploadModal,
  isOwn,
}: Props) {
  const addOrEditImageButton = useMemo(() => {
    return (
      !isMobile && (
        <AddOrEditImageButton
          imageSrc={variant.extendedText}
          uploading={pictureUploding}
          onImageClick={() => {
            setSelectedVariantId(variant.id);
            if (variant.extendedText) {
              return openCropModal(
                variant.extendedText,
                variant.originalImageUrl,
              );
            }

            openImageUploadModal();
          }}
          onPlusClick={() => {
            setSelectedVariantId(variant.id);
            openImageUploadModal();
          }}
          sx={{ mx: "10px" }}
        />
      )
    );
  }, [
    isMobile,
    pictureUploding,
    setSelectedVariantId,
    variant,
    openCropModal,
    openImageUploadModal,
  ]);

  const addOrEditImageButtonMobile = useMemo(() => {
    return (
      isMobile && (
        <AddOrEditImageButton
          imageSrc={variant.extendedText}
          uploading={pictureUploding}
          onImageClick={() => {
            setSelectedVariantId(variant.id);
            if (variant.extendedText) {
              return openCropModal(
                variant.extendedText,
                variant.originalImageUrl,
              );
            }

            openImageUploadModal();
          }}
          onPlusClick={() => {
            setSelectedVariantId(variant.id);
            openImageUploadModal();
          }}
          sx={{ m: "8px", width: "auto" }}
        />
      )
    );
  }, [
    isMobile,
    pictureUploding,
    setSelectedVariantId,
    variant,
    openCropModal,
    openImageUploadModal,
  ]);

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