import { type Accessor, createSignal } from "solid-js";

export type ToastType = "default" | "success" | "error" | "loading";

export interface ToastData {
	id: string;
	title: string;
	description?: string | undefined;
	type: ToastType;
	duration?: number | undefined;
}

const [toasts, setToasts] = createSignal<ToastData[]>([]);
let nextId = 0;

/** Generates a unique toast ID. */
function generateId(): string {
	nextId += 1;
	return `toast-${nextId}`;
}

/** Adds a toast to the store. Returns the toast ID. */
function addToast(data: Omit<ToastData, "id"> & { id?: string | undefined }): string {
	const id = data.id ?? generateId();
	setToasts((prev) => [...prev, { ...data, id }]);
	return id;
}

/** Removes a toast by ID. */
function dismissToast(id: string): void {
	setToasts((prev) => prev.filter((t) => t.id !== id));
}

/** Removes all toasts. */
function clearToasts(): void {
	setToasts([]);
}

/** Updates an existing toast by ID. */
function updateToast(id: string, data: Partial<Omit<ToastData, "id">>): void {
	setToasts((prev) => prev.map((t) => (t.id === id ? { ...t, ...data } : t)));
}

/** Returns the reactive toast list accessor. */
export function useToastStore(): Accessor<ToastData[]> {
	return toasts;
}

export const toastActions = { addToast, dismissToast, clearToasts, updateToast };
