import { createContext, useContext, useCallback, useState, useMemo, type ReactNode } from 'react';
import { ToastContainer, type ToastType, type ToastItem } from '../components/ui/Toast';

interface ToastContextValue {
  showToast(message: string, type?: ToastType, duration?: number): void;
}

const ToastContext = createContext<ToastContextValue | null>(null);

let nextId = 0;

interface ToastProviderProps {
  readonly children: ReactNode;
}

export function ToastProvider({ children }: ToastProviderProps) {
  const [toasts, setToasts] = useState<readonly ToastItem[]>([]);

  const showToast = useCallback(
    (message: string, type: ToastType = 'info', duration = 3000) => {
      const id = String(++nextId);
      const toast: ToastItem = { id, message, type, duration };
      setToasts((prev) => [...prev, toast]);
    },
    [],
  );

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

  const value = useMemo<ToastContextValue>(() => ({ showToast }), [showToast]);

  return (
    <ToastContext.Provider value={value}>
      {children}
      <ToastContainer toasts={toasts} onDismiss={dismissToast} />
    </ToastContext.Provider>
  );
}

export function useToast(): ToastContextValue {
  const ctx = useContext(ToastContext);
  if (!ctx) {
    throw new Error('useToast must be used within a ToastProvider');
  }
  return ctx;
}
