import { circleInfo, circleTick, error, warning } from "@simplybusiness/icons";
import classNames from "classnames/dedupe";
import type { ReactNode, RefAttributes } from "react";
import type { DOMProps } from "../../types/dom";
import { Icon } from "../Icon";
import { TextOrHTML } from "../TextOrHTML";
import "./Alert.css";

export type AlertElementType = HTMLDivElement;

export interface AlertProps extends DOMProps, RefAttributes<AlertElementType> {
  children?: ReactNode;
  /** Custom class name for setting specific CSS */
  className?: string;
  elementType?: React.ElementType;
  variant?: string;
  show?: boolean;
  header?: string;
}

type AlertVariant = "info" | "success" | "warning" | "error";

function isAlertVariant(value: string): value is AlertVariant {
  return (
    value === "info" ||
    value === "success" ||
    value === "warning" ||
    value === "error"
  );
}

const Alert = ({ ref, ...props }: AlertProps) => {
  const {
    elementType: Element = "div",
    variant: variantProp,
    show = true,
    header,
    children,
    ...otherProps
  } = props;

  if (!show) return null;

  const variant: AlertVariant =
    variantProp && isAlertVariant(variantProp) ? variantProp : "info";

  const colorValue =
    variant === "success" ? `var(--color-valid)` : `var(--color-${variant})`;

  const classes = classNames(
    "mobius",
    "mobius-alert",
    {
      "--info": variant === "info",
      "--success": variant === "success",
      "--warning": variant === "warning",
      "--error": variant === "error",
      "--has-header": header,
    },
    otherProps.className,
  );
  const icon = {
    info: circleInfo,
    success: circleTick,
    warning,
    error,
  };

  const headerClasses = classNames("mobius", "mobius-alert__header");
  const iconClasses = classNames("mobius", "mobius-alert__icon");
  const contentClasses = classNames("mobius", "mobius-alert__content");

  return (
    <Element ref={ref} role="alert" {...otherProps} className={classes}>
      <span className={iconClasses}>
        <Icon icon={icon[variant]} color={colorValue} />
      </span>
      <div>
        {header && (
          <TextOrHTML
            autoDetect
            htmlElementType="span"
            className={headerClasses}
            htmlClassName={headerClasses}
            text={header}
          />
        )}
        <div className={contentClasses}>{children}</div>
      </div>
    </Element>
  );
};

Alert.displayName = "Alert";
export { Alert };
