"use client";

import { useCallback, useMemo, useState } from "react";

export type SimpleToastVariant = "info" | "success" | "error";

export interface SimpleToast {
  id: string;
  title: string;
  description?: string;
  variant: SimpleToastVariant;
}

interface PushToastInput {
  title: string;
  description?: string;
  variant?: SimpleToastVariant;
  durationMs?: number;
}

const DEFAULT_DURATION_MS = 3200;

function createToastId() {
  return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}

export function useSimpleToast() {
  const [toasts, setToasts] = useState<SimpleToast[]>([]);

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

  const pushToast = useCallback(
    ({ title, description, variant = "info", durationMs = DEFAULT_DURATION_MS }: PushToastInput) => {
      const id = createToastId();

      setToasts((currentToasts) => [
        ...currentToasts,
        {
          id,
          title,
          description,
          variant
        }
      ]);

      const timeout = setTimeout(() => {
        dismissToast(id);
      }, durationMs);

      if (typeof timeout.unref === "function") {
        timeout.unref();
      }

      return id;
    },
    [dismissToast]
  );

  return useMemo(
    () => ({
      toasts,
      pushToast,
      dismissToast
    }),
    [dismissToast, pushToast, toasts]
  );
}
