import { PrimariaNotificationService } from "./notification-service";

const CONTAINER_ID = "primaria-toast-container";

export class PrimariaNotificationServiceImpl extends PrimariaNotificationService {
  private getOrCreateContainer(): HTMLElement {
    let container = document.getElementById(CONTAINER_ID);
    if (!container) {
      container = document.createElement("div");
      container.id = CONTAINER_ID;
      container.style.cssText =
        "position:fixed;bottom:var(--dss-spacing-xxs,8px);left:var(--dss-spacing-xxs,8px);display:flex;flex-direction:column-reverse;gap:var(--dss-spacing-xs,4px);z-index:999;pointer-events:none;";
      document.body.appendChild(container);
    }
    return container;
  }

  private removeContainerIfEmpty(container: HTMLElement): void {
    if (container.childElementCount === 0) {
      container.remove();
    }
  }

  private notify(
    message: string,
    state: "info" | "warning" | "error" | "success",
    duration = 3000,
  ): void {
    const container = this.getOrCreateContainer();

    const toast = document.createElement("dss-toast");
    toast.setAttribute("isshow", "true");
    toast.setAttribute("state", state);
    toast.setAttribute("position", "bottom-left");
    toast.setAttribute("text", message);
    toast.setAttribute("hasicon", "true");
    toast.setAttribute("duration", duration.toString());
    toast.style.position = "relative";
    toast.style.bottom = "auto";
    toast.style.left = "auto";
    toast.style.pointerEvents = "auto";

    container.appendChild(toast);

    setTimeout(() => {
      toast.setAttribute("isshow", "false");
      setTimeout(() => {
        toast.remove();
        this.removeContainerIfEmpty(container);
      }, 300);
    }, duration);
  }

  info(message: string, duration?: number): void {
    this.notify(message, "info", duration);
  }

  warning(message: string, duration?: number): void {
    this.notify(message, "warning", duration);
  }

  error(message: string, duration?: number): void {
    this.notify(message, "error", duration);
  }

  success(message: string, duration?: number): void {
    this.notify(message, "success", duration);
  }
}
