import { NgClass } from "@angular/common";
import { ChangeDetectionStrategy, Component, ElementRef, signal, ViewChild } from "@angular/core";

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

interface ToastOptions {
  message: string;
  type?: TOAST_TYPE;
}

@Component({
  selector: "fast-toast",
  imports: [NgClass],
  template: `
    <div #toastPop popover="manual"
      class="flex items-center justify-center rounded-md px-4 py-3 shadow-md text-white toaster"
      [ngClass]="{
    'bg-inverse': !type(),
    'bg-green-500': type() === 'success',
    'bg-red-500': type() === 'error',
    'bg-yellow-500': type() === 'warning',
  }"
    >
      <div>{{ message() }}</div>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  styles: [`
    [popover] {
      inset: unset;
      position: fixed;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%) translateY(0);
      pointer-events: auto;
      opacity: 0;
      transition: opacity 250ms ease-out, transform 250ms ease-out;
    }

    [popover]:popover-open {
      opacity: 1;
      transform: translateX(-50%) translateY(0);
    }

    [popover]:not(:popover-open) {
      opacity: 0;
      transform: translateX(-50%) translateY(20px);
    }
    `],
  host: {
    role: "alert",
    "[class.toaster]": "true",
    "[class]": "type()",
  },
})

export class FastToastComponent {
  message = signal<string>("");
  type = signal<string | undefined>(undefined);
  @ViewChild('toastPop') toastPopElem!: ElementRef<HTMLDivElement>;
  timeoutId: NodeJS.Timeout;

  show(options: ToastOptions) {
    this.message.set(options.message);
    this.type.set(options.type);
    const pop = this.toastPopElem.nativeElement;
    clearTimeout(this.timeoutId);

    pop.showPopover();
    this.timeoutId = setTimeout(() => {
      pop.hidePopover();
    }, 4000);
  }
}