import type * as React from "react";
import { useTranslation } from "react-i18next";
import { Toast as ToastPrimitive } from "@base-ui/react/toast";
import { X } from "lucide-react";

import { cn } from "@/lib/utils";
import { toastManager } from "@/toast/toast-manager";

function ToastList() {
  const { t } = useTranslation();
  const { toasts } = ToastPrimitive.useToastManager();
  return toasts.map((toast) => (
    <ToastPrimitive.Root
      key={toast.id}
      toast={toast}
      data-slot="toast"
      className={cn(
        "flex items-start gap-2 rounded-md border bg-popover p-3 text-sm text-popover-foreground shadow-md",
        toast.type === "error" && "border-destructive",
        toast.type === "success" && "border-success",
      )}
    >
      <div className="flex-1">
        {toast.title && (
          <ToastPrimitive.Title
            data-slot="toast-title"
            className="font-medium"
          />
        )}
        <ToastPrimitive.Description
          data-slot="toast-description"
          className="text-muted-foreground"
        />
      </div>
      <ToastPrimitive.Close
        data-slot="toast-close"
        aria-label={t("common.close")}
        className="text-muted-foreground hover:text-foreground"
      >
        <X className="size-4" aria-hidden="true" />
      </ToastPrimitive.Close>
    </ToastPrimitive.Root>
  ));
}

/** App-wide toast region: provides the external manager + a portaled viewport. */
export function ToastRegion({ children }: { children: React.ReactNode }) {
  return (
    <ToastPrimitive.Provider toastManager={toastManager}>
      {children}
      <ToastPrimitive.Portal>
        <ToastPrimitive.Viewport className="fixed bottom-4 right-4 z-50 flex w-80 flex-col gap-2">
          <ToastList />
        </ToastPrimitive.Viewport>
      </ToastPrimitive.Portal>
    </ToastPrimitive.Provider>
  );
}
