import type { ReactNode } from "react";
import "./tag.css";

export type TagType = "simple" | "dot" | "flag" | "avatar" | "icon";
export type TagSize = "xs" | "md" | "lg";
export type TagState = "default" | "active" | "disabled";

export type CatalogTagType = TagType;
export type CatalogTagSize = TagSize;
export type CatalogTagState = TagState;

export type CatalogTagProps = {
  avatar?: ReactNode;
  children?: ReactNode;
  closeLabel?: string;
  dir?: "ltr" | "rtl" | "auto";
  disabled?: boolean;
  flag?: ReactNode;
  icon?: ReactNode;
  onClose?: () => void;
  showCloseButton?: boolean;
  size?: TagSize;
  state?: TagState;
  type?: TagType;
};

function cx(...classes: Array<string | false | undefined>) {
  return classes.filter(Boolean).join(" ");
}

export function CatalogTag({
  avatar,
  children,
  closeLabel,
  dir = "ltr",
  disabled = false,
  flag,
  icon,
  onClose,
  showCloseButton = false,
  size = "md",
  state = "default",
  type = "simple",
}: CatalogTagProps) {
  const isDisabled = disabled || state === "disabled";
  const hasLeadingSlot = type !== "simple";

  return (
    <span
      aria-disabled={isDisabled || undefined}
      className={cx(
        "ds-tag",
        `ds-tag--${type}`,
        `ds-tag--${size}`,
        `ds-tag--${state}`,
        showCloseButton && "ds-tag--closeable",
      )}
      dir={dir}
    >
      {hasLeadingSlot && (
        <span aria-hidden="true" className="ds-tag__leading">
          {type === "dot" && <span className="ds-tag__dot" />}
          {type === "flag" && (flag ?? <span className="ds-tag__flag" />)}
          {type === "avatar" && avatar}
          {type === "icon" && (icon ?? <PlusIcon />)}
        </span>
      )}
      <span className="ds-tag__label">{children}</span>
      {showCloseButton && (
        <button aria-label={closeLabel} className="ds-tag__close" disabled={isDisabled} onClick={onClose} type="button">
          <CloseIcon />
        </button>
      )}
    </span>
  );
}

function PlusIcon() {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16">
      <path d="M8 3.5v9M3.5 8h9" fill="none" stroke="currentColor" strokeLinecap="round" strokeWidth="1.7" />
    </svg>
  );
}

function CloseIcon() {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16">
      <path d="m4.5 4.5 7 7M11.5 4.5l-7 7" fill="none" stroke="currentColor" strokeLinecap="round" strokeWidth="1.6" />
    </svg>
  );
}
