import {
  ButtonProps,
  StatefulPopover,
  StatefulPopoverProps,
  useStyletron,
} from "@mezo-org/mezo-clay"
import { useConnectModal } from "@rainbow-me/rainbowkit"
import React from "react"
import DefaultAvatar from "../../assets/DefaultAvatar"
import ConnectedTrigger from "./ConnectedTrigger"
import Content from "./Content"
import DisconnectedTrigger from "./DisconnectedTrigger"
import { useWalletAccount } from "../../hooks/useWalletAccount"
import { useWatchTransferEventsForAllTokens } from "../../hooks/useWatchTransferEvents"

export type DropdownProps = {
  /** The callback to be called when the user clicks the sign-out button */
  onSignOut?: () => void
  /** The callback to be called when the user clicks the button in sign-in state */
  onSignIn?: () => void
  /** The props to be passed to the trigger button */
  triggerProps?: {
    signedIn?: Omit<ButtonProps, "onClick" | "size"> & {
      size: "medium" | "large"
    }
    signedOut?: Omit<ButtonProps, "onClick">
  }
  onOtherAssetsClick?: () => void
} & Omit<StatefulPopoverProps, "children" | "content">

/**
 * Passport Dropdown component that displays user's wallet and assets information.
 * @param {DropdownProps} props - Component props.
 * @returns {JSX.Element}
 */
export function Dropdown(props: DropdownProps) {
  const {
    placement = "bottomRight",
    animateOutTime = 120,
    onSignIn,
    onSignOut,
    overrides,
    triggerProps,
    onOtherAssetsClick,
    ...restProps
  } = props

  const [, theme] = useStyletron()

  const walletAccount = useWalletAccount()

  useWatchTransferEventsForAllTokens()

  const { openConnectModal } = useConnectModal()

  if (!walletAccount?.isConnected) {
    return (
      <DisconnectedTrigger
        // If connect wallet flow is not provided it fallbacks to RainbowKit's
        // connect modal
        onClick={onSignIn || openConnectModal}
        {...triggerProps?.signedOut}
      >
        Sign in
      </DisconnectedTrigger>
    )
  }

  return (
    <StatefulPopover
      content={
        <Content
          onSignOut={onSignOut}
          onOtherAssetsClick={onOtherAssetsClick}
        />
      }
      placement={placement}
      animateOutTime={animateOutTime}
      overrides={{
        ...overrides,
        Body: {
          ...overrides?.Body,
          style: {
            width: "402px",
            borderRadius: theme.borders.radius500,
            boxShadow: theme.lighting.shadow500,
            overflow: "hidden",
            ...overrides?.Body?.style,
          },
        },
      }}
      {...restProps}
    >
      <ConnectedTrigger
        avatar={<DefaultAvatar />}
        {...triggerProps?.signedIn}
      />
    </StatefulPopover>
  )
}
