import { Box, ButtonBase, Typography, useTheme, Modal, IconButton } from "@mui/material";
import { useState } from "react";
import { EmojiPicker } from "./EmojiPicker";
import { useTranslation } from "react-i18next";
import CloseIcon from "@mui/icons-material/Close";

interface Props {
  emoji: string;
  onEmojiSelect?: (emoji: string) => void;
  onEmojiRemove?: () => void;
}

export const OwnEmojiPicker = ({ emoji = "", onEmojiSelect, onEmojiRemove }: Props) => {
  const theme = useTheme();
  const { t } = useTranslation();
  const [isPickerOpen, setIsPickerOpen] = useState(false);

  const handleEmojiSelect = (emojiData: any) => {
    onEmojiSelect?.(emojiData.native);
    setIsPickerOpen(false);
  };

  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    setIsPickerOpen(true);
  };

  const handleClose = (e: React.MouseEvent) => {
    e.stopPropagation();
    setIsPickerOpen(false);
  };

  const handleRemoveEmoji = (e: React.MouseEvent) => {
    e.stopPropagation();
    onEmojiRemove?.();
  };

  return (
    <>
      <Box sx={{ width: "100%", height: "100%", position: "relative" }}>
        <ButtonBase
          onClick={handleClick}
          sx={{
            width: "100%",
            height: "100%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            "&:hover": {
              bgcolor: theme.palette.grey[100],
            },
          }}
        >
          <Typography fontSize={emoji ? "100px" : "18px"}>{emoji || t("select emoji")}</Typography>
        </ButtonBase>

        {onEmojiRemove && (
          <IconButton
            onClick={handleRemoveEmoji}
            sx={{
              position: "absolute",
              top: 8,
              left: 8,
              zIndex: 1,
              backgroundColor: "rgba(0, 0, 0, 0.5)",
              color: "white",
              height: "25px",
              width: "25px",
              "&:hover": {
                backgroundColor: "rgba(0, 0, 0, 0.7)",
              },
            }}
          >
            <CloseIcon />
          </IconButton>
        )}
      </Box>

      <Modal
        open={isPickerOpen}
        onClose={handleClose}
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
        keepMounted
      >
        <Box
          onClick={(e) => e.stopPropagation()}
          sx={{
            bgcolor: "background.paper",
            borderRadius: 2,
            p: 2,
            boxShadow: 24,
          }}
        >
          <EmojiPicker onEmojiSelect={handleEmojiSelect} />
        </Box>
      </Modal>
    </>
  );
};
