import React from "react";
import { useState, useEffect } from "react";
import classNames from "classnames";
import { filterAttrs } from "@arc-ui/community-utils/filter-attrs";
import {
  NavigationHeaderAction,
  NavigationHeaderActionProps,
} from "@arc-ui/components/NavigationHeader";
import { Popover } from "@arc-ui/components/Popover";
import { Icon } from "@arc-ui/components/Icon";
import { Image } from "@arc-ui/components/Image";
import { Heading } from "@arc-ui/components/Heading";
import { Text } from "@arc-ui/components/Text";
import { Tooltip } from "@arc-ui/components/Tooltip";
import { ButtonV2 } from "@arc-ui/components/ButtonV2";

import { BtIconCrossAlt } from "@arc-ui/icons/BtIconCrossAlt";
import styles from "./HeaderBarNotification.module.css";

export const HeaderBarNotification: React.FC<HeaderBarNotificationProps> = ({
  headerActionProps,
  notificationId,
  isPersistant = false,
  icon,
  image,
  heading,
  tagline,
  children,
  button,
  showAtSize,
  ...props
}) => {
  const [showNotification, setShowNotification] =
    useState<boolean>(isPersistant);
  const localStorageId = `hide${notificationId.replace(/[^a-zA-Z0-9\-_]/g, "")}`;

  // Check to see if the notication has been hidden or not and show it if so
  useEffect(() => {
    if (typeof window !== "undefined" && !isPersistant) {
      setShowNotification(!localStorage.getItem(localStorageId));
    }
  }, []);

  // Handle the closure of the notification, store it in the session so we don't keep showing it.
  const handleClosePopup = () => {
    if (!isPersistant) localStorage.setItem(localStorageId, "true");
    setShowNotification(false);
  };

  return (
    <Popover
      open={showNotification}
      side={"bottom"}
      sideOffset={12}
      maxWidth={900}
      arrow={true}
      asChild={true}
      onOpenAutoFocus={(e) => e.preventDefault()}
      className={classNames(
        styles.popupNotification,
        { [styles.hiddenByDefault]: showAtSize },
        showAtSize?.map((s) => styles[s]),
      )}
      content={
        <div className={styles.container}>
          <div className={styles.content}>
            {(image || icon) && (
              <div className={styles.image}>
                {image && (
                  <Image src={image} alt={heading} fit={"cover"} width={55} />
                )}
                {icon && <Icon icon={icon} size={35} />}
              </div>
            )}

            <div className={styles.details}>
              {tagline && (
                <Text size="m" tone="muted">
                  {tagline}
                </Text>
              )}
              <Heading size="s" level={"3"}>
                {heading}
              </Heading>
              {children}
            </div>
          </div>
          {button && (
            <ButtonV2
              onClick={button.handleClick}
              label={button.text}
              buttonStyle="secondary"
              isFullWidth={true}
            />
          )}
          <div className={styles.closeButtonContainer}>
            <Tooltip
              side="bottom"
              title={"Dismiss Notification"}
              asChild={true}
            >
              <ButtonV2
                data-testid={localStorageId}
                buttonStyle="tertiary"
                aria-label={`Close ${notificationId} popup`}
                onClick={handleClosePopup}
                icon={BtIconCrossAlt}
              />
            </Tooltip>
          </div>
        </div>
      }
      {...filterAttrs(props)}
    >
      <NavigationHeaderAction isAttention={true} {...headerActionProps} />
    </Popover>
  );
};

export interface HeaderBarNotificationProps {
  /**
   * Header Element to attach the notifcation too.
   */
  headerActionProps: NavigationHeaderActionProps;
  /**
   * Nofication ID used to store dismissal in users session
   */
  notificationId: string;
  /**
   * Always show on every reload, ignore saving dismissal to users session
   */
  isPersistant?: boolean;
  /**
   * Notification Icon
   */
  icon?: string;
  /**
   * Notification Image
   */
  image?: string;
  /**
   * Notification Heading
   */
  heading: string;
  /**
   * Notification tagline
   */
  tagline?: string;
  /**
   * Notification content
   */
  children?: React.ReactNode;
  /**
   * Data for the button, click events and text
   */
  button?: {
    handleClick: () => void;
    text: string;
  };
  /**
   * Specify a size or mutliple sizes where the notification only appears.
   */
  showAtSize?: ("s" | "m" | "l" | "xl")[];
}
