import React from "react";
import classNames from "classnames";
import { Button } from "../button";
import { Icon } from "../icon";
import { StyledProps } from "../_type";
import { useDefault } from "../_util/use-default";
import { useConfig } from "../_util/config-context";
import { useTranslation } from "../i18n";

export interface AlertNoticeProps extends StyledProps {
  /**
   * 通告标题
   */
  title?: React.ReactNode;

  /**
   * 通告内容
   */
  children?: React.ReactNode;

  /**
   * 是否默认展开
   */
  defaultOpen?: boolean;

  /**
   * 是否展开（受控）
   */
  open?: boolean;

  /**
   * 展开变化回调（受控）
   */
  onOpenChange?: (open: boolean) => void;
}

export const AlertNotice = React.forwardRef(function AlertNotice(
  {
    title,
    children,
    className,
    open,
    defaultOpen,
    onOpenChange,
    ...props
  }: AlertNoticeProps,
  ref: React.Ref<HTMLDivElement>
) {
  const [isOpened, setIsOpened] = useDefault(open, defaultOpen, onOpenChange);
  const { classPrefix } = useConfig();
  const t = useTranslation();

  const alertClassName = classNames(
    `${classPrefix}-alert`,
    `${classPrefix}-alert--notice`,
    isOpened && "is-expanded",
    className
  );

  const alertElement = (
    <div ref={ref} className={alertClassName} {...props}>
      <span className={`${classPrefix}-alert__decoration`}>
        <Icon type="notice-blue" />
      </span>

      <div className={`${classPrefix}-alert__info`}>
        <p>{title}</p>
        {isOpened && children}
      </div>
      <div className={`${classPrefix}-alert__operational`}>
        {children && (
          <Button
            type="icon"
            htmlType="button"
            icon={isOpened ? "arrowup" : "arrowdown"}
            aria-label={isOpened ? t.collapse : t.expand}
            onClick={() => setIsOpened(!isOpened)}
          />
        )}
      </div>
    </div>
  );

  return alertElement;
});

AlertNotice.displayName = "AlertNotice";
