"use client";

import React, { useCallback, useRef, useState } from "react";
import { AlertTriangle, CheckCircle2, Info, Undo2, X } from "lucide-react";

export type ToastTone = "info" | "success" | "warning" | "error";

export interface ToastNotice {
  id: string;
  tone: ToastTone;
  title: string;
  message?: string;
  /** Beschriftung der optionalen Aktion, z.B. "Rückgängig". */
  actionLabel?: string;
  onAction?: () => void;
  /** Anzeigedauer in Millisekunden. `0` = bleibt bis zum Schließen stehen. */
  durationMs?: number;
}

export type ToastInput = Omit<ToastNotice, "id">;

/**
 * Minimaler Toast-Speicher ohne zusätzliche Abhängigkeit.
 *
 * Wird u.a. für die "Rückgängig"-Funktion beim Löschen genutzt: Der gelöschte
 * Datensatz lebt in der Closure der Toast-Aktion und verfällt, sobald der Toast
 * abläuft. IndexedDB ist die einzige Kopie der Nutzerdaten – ein sofortiges,
 * kommentarloses Löschen ist deshalb nicht akzeptabel.
 */
export function useToasts() {
  const [toasts, setToasts] = useState<ToastNotice[]>([]);
  const counter = useRef(0);

  const dismiss = useCallback((id: string) => {
    setToasts((prev) => prev.filter((toast) => toast.id !== id));
  }, []);

  const push = useCallback(
    (notice: ToastInput) => {
      counter.current += 1;
      const id = `toast_${counter.current}_${Date.now()}`;
      const duration = notice.durationMs ?? (notice.actionLabel ? 10000 : 6000);
      setToasts((prev) => [...prev, { ...notice, id }]);
      if (duration > 0 && typeof window !== "undefined") {
        window.setTimeout(() => dismiss(id), duration);
      }
      return id;
    },
    [dismiss]
  );

  return { toasts, push, dismiss };
}

const TONE_STYLES: Record<ToastTone, string> = {
  info: "border-[#161C22] bg-white",
  success: "border-emerald-600 bg-white",
  warning: "border-[#F59E0B] bg-[#FEF3C7]",
  error: "border-[#BA1A1A] bg-[#FFDAD6]",
};

function ToneIcon({ tone }: { tone: ToastTone }) {
  if (tone === "success") return <CheckCircle2 className="h-4 w-4 text-emerald-600" />;
  if (tone === "warning") return <AlertTriangle className="h-4 w-4 text-[#92400E]" />;
  if (tone === "error") return <AlertTriangle className="h-4 w-4 text-[#93000A]" />;
  return <Info className="h-4 w-4 text-black" />;
}

export function ToastStack({
  toasts,
  onDismiss,
}: {
  toasts: ToastNotice[];
  onDismiss: (id: string) => void;
}) {
  if (toasts.length === 0) return null;

  return (
    <div
      data-testid="toast-stack"
      className="fixed bottom-6 right-6 z-[100] flex w-[min(26rem,calc(100vw-3rem))] flex-col gap-2 font-sans"
    >
      {toasts.map((toast) => (
        <div
          key={toast.id}
          role="status"
          data-testid="toast"
          className={`flex items-start gap-3 border p-3.5 shadow-none ${TONE_STYLES[toast.tone]}`}
        >
          <div className="mt-0.5 shrink-0">
            <ToneIcon tone={toast.tone} />
          </div>

          <div className="min-w-0 flex-1">
            <p className="text-xs font-bold text-black">{toast.title}</p>
            {toast.message && (
              <p className="mt-0.5 font-mono text-[11px] leading-relaxed text-[#334155]">
                {toast.message}
              </p>
            )}
            {toast.actionLabel && toast.onAction && (
              <button
                type="button"
                data-testid="toast-action"
                onClick={() => {
                  toast.onAction?.();
                  onDismiss(toast.id);
                }}
                className="mt-2 inline-flex items-center gap-1.5 border border-black bg-white px-3 py-1 font-mono text-[10px] uppercase tracking-caps text-black transition-colors hover:bg-black hover:text-white"
              >
                <Undo2 className="h-3 w-3" />
                <span>{toast.actionLabel}</span>
              </button>
            )}
          </div>

          <button
            type="button"
            aria-label="Dismiss notification"
            onClick={() => onDismiss(toast.id)}
            className="shrink-0 p-1 text-[#475569] hover:text-black"
          >
            <X className="h-3.5 w-3.5" />
          </button>
        </div>
      ))}
    </div>
  );
}
