import type { PropsWithChildren, RefAttributes } from "react";
import { useEffect, useId } from "react";

import { cross } from "@simplybusiness/icons";
import type { DOMProps } from "../../types/dom";
import { Button } from "../Button";
import { Icon } from "../Icon";
import { useModal } from "./useModal";

export type HeaderElementType = HTMLDivElement;

export interface HeaderProps
  extends DOMProps, RefAttributes<HeaderElementType>, PropsWithChildren {}

const Header = ({ ref, children, ...otherProps }: HeaderProps) => {
  const { onClose, closeLabel, setTitleId } = useModal();
  const titleId = useId();

  useEffect(() => {
    setTitleId(titleId);
  }, [titleId, setTitleId]);

  return (
    <header
      ref={ref}
      {...otherProps}
      className="mobius-modal__header"
      id={titleId}
    >
      {children}
      <Button
        aria-label="Close"
        variant="basic"
        onPress={onClose}
        className="mobius-modal__close"
      >
        <Icon icon={cross} /> {closeLabel}
      </Button>
    </header>
  );
};

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