'use client';

import { createContext, useContext, useState, ReactNode } from 'react';
import { Toast } from '../app/components/ui/Toast';

type ToastType = 'success' | 'error' | 'warning' | 'info';

interface ToastState {
  id: number;
  type: ToastType;
  message: string;
}

interface ToastContextType {
  showToast: (
    type: ToastType,
    message: string
  ) => void;
}

const ToastContext = createContext<ToastContextType | null>(null);

export function ToastProvider({ children }: { children: ReactNode; }) {
  const [toasts, setToasts] = useState<ToastState[]>([]);

  const showToast = (type: ToastType, message: string) => {
    const id = Date.now();

    setToasts((prev) => [
      ...prev,
      {
        id,
        type,
        message
      }
    ]);

    setTimeout(() => {
      setToasts((prev) =>
        prev.filter((t) => t.id !== id)
      );
    }, 4000);
  };

  return (
    <ToastContext.Provider
      value={{ showToast }}
    >
      {children}

      <div className="fixed top-6 left-1/2 -translate-x-1/2 z-[9999] flex flex-col gap-3 w-full max-w-md px-4">
        {toasts.map((toast) => (
          <Toast
            key={toast.id}
            type={toast.type}
            message={toast.message}
          />
        ))}
      </div>
    </ToastContext.Provider>
  );
}

export function useToast() {
  const context = useContext(ToastContext);

  if (!context) {
    throw new Error('useToast doit être utilisé dans ToastProvider');
  }

  return context;
}