import { useEffect, useContext, useCallback, useState } from "react";
import { IOConnectDesktop } from "@interopio/desktop";
import { IOConnectContext } from "@interopio/react-hooks";
import { Badge, ButtonIcon } from "@interopio/components-react";

function NotificationsButton() {
  const io = useContext(IOConnectContext) as IOConnectDesktop.API;
  const [notificationsCount, setNotificationsCount] = useState(0);

  const openNotificationPanel = useCallback(async () => {
    const isPanelVisible = await io.notifications.panel.isVisible();

    if (isPanelVisible) {
      return;
    }

    try {
      await io.notifications.panel.show();
    } catch (error) {
      console.error("Failed to open notifications panel.", error);
    }
  }, []);

  useEffect(() => {
    const unCounterChanged = io.notifications.onCounterChanged(info =>
      setNotificationsCount(info.count)
    );

    return () => {
      unCounterChanged();
    };
  }, [io]);

  return (
    <div className="launchpad-header-notifications-button">
      {notificationsCount > 0 && (
        <Badge variant="primary">
          {notificationsCount > 99 ? "99+" : notificationsCount}
        </Badge>
      )}
      <ButtonIcon
        variant="circle"
        icon="bell"
        size="32"
        onClick={openNotificationPanel}
      />
    </div>
  );
}

export default NotificationsButton;
