import { Block, Button, ButtonProps, useStyletron } from "@mezo-org/mezo-clay"
import React, { forwardRef, ReactNode, useMemo } from "react"

type ConnectedTriggerProps = Omit<ButtonProps, "children" | "size"> & {
  avatar: ReactNode
  size?: "medium" | "large"
}

const ConnectedTrigger = forwardRef<HTMLButtonElement, ConnectedTriggerProps>(
  (props, ref) => {
    const { onClick, avatar, size = "medium", ...restProps } = props

    const [, theme] = useStyletron()

    const avatarSize = useMemo(() => {
      const sizeMap = {
        medium: theme.sizing.scale950,
        large: theme.sizing.scale1400,
      }

      return sizeMap[size]
    }, [theme, size])

    const buttonPadding = useMemo(() => {
      const paddingMap = {
        medium: theme.sizing.scale0,
        large: theme.sizing.scale100,
      }

      return paddingMap[size]
    }, [theme, size])

    return (
      <Button
        overrides={{
          BaseButton: {
            props: { ref, ...restProps },
            style: {
              borderRadius: "100%",
              overflow: "hidden",
              padding: buttonPadding,
            },
          },
        }}
        onClick={onClick}
      >
        {typeof avatar === "string" ? (
          <Block
            width={avatarSize}
            height={avatarSize}
            as="img"
            src={avatar}
            alt=""
          />
        ) : (
          <Block
            width={avatarSize}
            height={avatarSize}
            overrides={{
              Block: {
                style: {
                  borderRadius: "100%",
                  overflow: "hidden",
                },
              },
            }}
          >
            {avatar}
          </Block>
        )}
      </Button>
    )
  },
)

export default ConnectedTrigger
