'use client';

import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';

interface ToastProps {
  message: string;
  duration?: number;
  onClose: () => void;
  index: number;
  icon?: string;
}

export function Toast({
  message,
  duration = 2000,
  onClose,
  index,
  icon,
}: ToastProps) {
  const [isVisible, setIsVisible] = useState(true);

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsVisible(false);
      setTimeout(onClose, 200); // Attendre la fin de l'animation
    }, duration);

    return () => clearTimeout(timer);
  }, [duration, onClose]);

  if (typeof window === 'undefined') return null;

  return createPortal(
    <div
      className={`fixed top-4 right-4 z-50 transition-all duration-200 ${
        isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-2'
      }`}
      style={{ transform: `translateY(${index * 60}px)` }}
    >
      <div className="bg-[var(--card)] border border-[var(--border)] rounded-lg px-3 py-2 shadow-lg backdrop-blur-sm flex items-center gap-2">
        {icon && <span className="text-base">{icon}</span>}
        <div className="text-sm text-[var(--foreground)] font-medium">
          {message}
        </div>
      </div>
    </div>,
    document.body
  );
}

interface ToastContextType {
  showToast: (message: string, duration?: number, icon?: string) => void;
}

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

export function ToastProvider({ children }: { children: React.ReactNode }) {
  const [toasts, setToasts] = useState<
    Array<{ id: string; message: string; duration?: number; icon?: string }>
  >([]);
  const MAX_TOASTS = 5;

  const showToast = (message: string, duration?: number, icon?: string) => {
    const id = Math.random().toString(36).substr(2, 9);
    setToasts((prev) => {
      const newToasts = [...prev, { id, message, duration, icon }];
      // Garder seulement les 5 plus récents
      return newToasts.slice(-MAX_TOASTS);
    });
  };

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

  return (
    <ToastContext.Provider value={{ showToast }}>
      {children}
      {toasts.map((toast, index) => (
        <Toast
          key={toast.id}
          message={toast.message}
          duration={toast.duration}
          onClose={() => removeToast(toast.id)}
          index={index}
          icon={toast.icon}
        />
      ))}
    </ToastContext.Provider>
  );
}

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