import React, { useState, useEffect } from "react";
import {
  IconButton,
  Badge,
  Tooltip,
  styled,
  useTheme,
  useMediaQuery,
} from "@mui/material";
import WhatsAppIcon from "@mui/icons-material/WhatsApp";

interface WhatsAppChatProps {
  phoneNumber: string;
  message?: string;
  position?: "left" | "right";
  offsetY?: number;
  offsetX?: number;
  size?: "small" | "medium" | "large" | number;
  color?: string;
  backgroundColor?: string;
  autoOpenTimeout?: number;
  zIndex?: number;
  buttonStyle?: "round" | "square";
  icon?: "default" | "custom";
  customIcon?: React.ReactNode;
  showNotification?: boolean;
  notificationCount?: number;
}

const WhatsAppButton = styled(IconButton, {
  shouldForwardProp: (prop) =>
    ![
      "position",
      "offsetX",
      "offsetY",
      "customSize",
      "customColor",
      "customBackgroundColor",
      "buttonStyle",
    ].includes(prop.toString()),
})<{
  position: "left" | "right";
  offsetX: number;
  offsetY: number;
  customSize: number;
  customColor: string;
  customBackgroundColor: string;
  buttonStyle: "round" | "square";
}>(
  ({
    theme,
    position,
    offsetX,
    offsetY,
    customSize,
    customColor,
    customBackgroundColor,
    buttonStyle,
  }) => ({
    position: "fixed",
    [position]: theme.spacing(offsetX / 8),
    bottom: theme.spacing(offsetY / 8),
    zIndex: theme.zIndex.speedDial,
    width: theme.spacing(customSize / 8),
    height: theme.spacing(customSize / 8),
    color: customColor,
    backgroundColor: customBackgroundColor,
    borderRadius: buttonStyle === "round" ? "50%" : theme.shape.borderRadius,
    "&:hover": {
      backgroundColor: theme.palette.augmentColor({
        color: { main: customBackgroundColor },
      }).dark,
      transform: "scale(1.1)",
    },
    transition: theme.transitions.create(["transform", "background-color"], {
      duration: theme.transitions.duration.short,
    }),
  })
);

const WhatsAppChat: React.FC<WhatsAppChatProps> = ({
  phoneNumber,
  message = "Hello, I have a question about...",
  position = "right",
  offsetY = 20,
  offsetX = 20,
  size = "medium",
  color = "#fff",
  backgroundColor = "#25D366",
  autoOpenTimeout = 0,
  zIndex = 1000,
  buttonStyle = "round",
  icon = "default",
  customIcon,
  showNotification = false,
  notificationCount = 0,
}) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const [notification, setNotification] = useState(showNotification);
  const [count, setCount] = useState(notificationCount);
  const [openTooltip, setOpenTooltip] = useState(false);

  // Calculate size based on prop
  const getSizeValue = () => {
    if (typeof size === "number") return size;
    switch (size) {
      case "small":
        return isMobile ? 40 : 48;
      case "large":
        return isMobile ? 64 : 72;
      case "medium":
      default:
        return isMobile ? 56 : 60;
    }
  };
  const calculatedSize = getSizeValue();

  useEffect(() => {
    if (autoOpenTimeout > 0) {
      const timer = setTimeout(() => {
        setNotification(true);
      }, autoOpenTimeout * 1000);
      return () => clearTimeout(timer);
    }
  }, [autoOpenTimeout]);

  const handleClick = () => {
    const encodedMessage = encodeURIComponent(message);
    window.open(
      `https://wa.me/${phoneNumber}?text=${encodedMessage}`,
      "_blank"
    );
    setNotification(false);
    setCount(0);
  };

  return (
    <Tooltip
      title="Chat with us on WhatsApp!"
      placement={position === "right" ? "left" : "right"}
      open={openTooltip}
      onOpen={() => setOpenTooltip(true)}
      onClose={() => setOpenTooltip(false)}
      arrow
    >
      <WhatsAppButton
        position={position}
        offsetX={offsetX}
        offsetY={offsetY}
        customSize={calculatedSize}
        customColor={color}
        customBackgroundColor={backgroundColor}
        buttonStyle={buttonStyle}
        onClick={handleClick}
        onMouseEnter={() => setOpenTooltip(true)}
        onMouseLeave={() => setOpenTooltip(false)}
        aria-label="Chat via WhatsApp"
        sx={{ zIndex }}
      >
        <Badge
          color="error"
          overlap="circular"
          badgeContent={notification && count > 0 ? count : 0}
          invisible={!notification || count <= 0}
          max={9}
        >
          {icon === "default" ? (
            <WhatsAppIcon
              sx={{
                fontSize: calculatedSize * 0.6,
              }}
            />
          ) : (
            customIcon
          )}
        </Badge>
      </WhatsAppButton>
    </Tooltip>
  );
};

export default WhatsAppChat;
