import { createPortal } from 'react-dom';
import { createContext, useContext, useState, useCallback, ReactNode } from 'react';
import ToastItem, { Toast, ToastVariant } from './Toast';

interface ToastContextType {
  success: (title: string, message?: string) => string;
  error: (title: string, message?: string) => string;
  warning: (title: string, message?: string) => string;
  info: (title: string, message?: string) => string;
}

const ToastContext = createContext<ToastContextType | undefined>(undefined);

let toastIdCounter = 0;

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

  const showToast = useCallback((variant: ToastVariant, title: string, message?: string) => {
    const id = `toast-${++toastIdCounter}`;
    const newToast: Toast = { id, variant, title, message };
    
    setToasts((prev) => [...prev, newToast]);
    
    return id;
  }, []);

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

  const success = useCallback((title: string, message?: string) => {
    return showToast('success', title, message);
  }, [showToast]);

  const error = useCallback((title: string, message?: string) => {
    return showToast('error', title, message);
  }, [showToast]);

  const warning = useCallback((title: string, message?: string) => {
    return showToast('warning', title, message);
  }, [showToast]);

  const info = useCallback((title: string, message?: string) => {
    return showToast('info', title, message);
  }, [showToast]);

  return (
    <ToastContext.Provider value={{ success, error, warning, info }}>
      {children}
      <ToastContainer toasts={toasts} onClose={removeToast} />
    </ToastContext.Provider>
  );
}

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

interface ToastContainerProps {
  toasts: Toast[];
  onClose: (id: string) => void;
}

function ToastContainer({ toasts, onClose }: ToastContainerProps) {
  if (toasts.length === 0) return null;

  return createPortal(
    <div className="fixed top-6 right-4 z-[999999] flex flex-col gap-3 pointer-events-none">
      {toasts.map((toast, index) => (
        <div key={toast.id} className="pointer-events-auto" style={{ animationDelay: `${index * 50}ms` }}>
          <ToastItem {...toast} onClose={onClose} />
        </div>
      ))}
    </div>,
    document.body
  );
}

