import React from 'react';
import { inject } from '../lib/inject';
import { Toast } from './Toast';

const css = `
.nbl-toast-stack{position:fixed;bottom:24px;right:24px;z-index:9000;display:flex;flex-direction:column;gap:10px;align-items:flex-end;pointer-events:none;}
.nbl-toast-stack .nbl-toast{pointer-events:all;}
`;

inject('nbl-toast-stack-css', css);

export interface ToastItem {
  id: string;
  tone?: 'success' | 'danger' | 'info';
  title: string;
  message?: string;
}

interface ToastContextValue {
  toasts: ToastItem[];
  addToast: (item: Omit<ToastItem, 'id'>) => void;
  removeToast: (id: string) => void;
  success: (title: string, message?: string) => void;
  danger: (title: string, message?: string) => void;
  info: (title: string, message?: string) => void;
}

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

export function ToastProvider({ children }: { children: React.ReactNode }) {
  inject('nbl-toast-stack-css', css);
  const [toasts, setToasts] = React.useState<ToastItem[]>([]);

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

  const addToast = React.useCallback(
    (item: Omit<ToastItem, 'id'>) => {
      const id = `toast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
      setToasts((prev) => [...prev, { ...item, id }]);
      setTimeout(() => removeToast(id), 4000);
    },
    [removeToast]
  );

  const success = React.useCallback(
    (title: string, message?: string) => addToast({ tone: 'success', title, message }),
    [addToast]
  );

  const danger = React.useCallback(
    (title: string, message?: string) => addToast({ tone: 'danger', title, message }),
    [addToast]
  );

  const info = React.useCallback(
    (title: string, message?: string) => addToast({ tone: 'info', title, message }),
    [addToast]
  );

  const value: ToastContextValue = { toasts, addToast, removeToast, success, danger, info };

  return (
    <ToastContext.Provider value={value}>
      {children}
      <div className="nbl-toast-stack" aria-live="polite" aria-label="Notifications">
        {toasts.map((t) => (
          <Toast
            key={t.id}
            tone={t.tone}
            title={t.title}
            message={t.message}
            onClose={() => removeToast(t.id)}
          />
        ))}
      </div>
    </ToastContext.Provider>
  );
}

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