import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import { CheckCircle2, AlertTriangle, Info, X } from 'lucide-react'

const ToastContext = createContext(null)

const TYPES = {
  success: { Icon: CheckCircle2,  panel: 'border-emerald-800/60 bg-emerald-950/90', icon: 'text-emerald-400' },
  error:   { Icon: AlertTriangle, panel: 'border-red-800/60     bg-red-950/90',     icon: 'text-red-400'     },
  info:    { Icon: Info,          panel: 'border-gray-700       bg-gray-900/95',    icon: 'text-indigo-400'  },
}

const MAX_VISIBLE = 4

export function useToast() {
  const ctx = useContext(ToastContext)
  if (!ctx) throw new Error('useToast doit être utilisé à l\'intérieur d\'un <ToastProvider>')
  return ctx
}

export function ToastProvider({ children }) {
  const [toasts, setToasts] = useState([])
  const nextId = useRef(0)
  const timers = useRef(new Map())

  const dismiss = useCallback((id) => {
    const timer = timers.current.get(id)
    if (timer) { clearTimeout(timer); timers.current.delete(id) }
    setToasts(list => list.filter(t => t.id !== id))
  }, [])

  const push = useCallback((message, { type = 'info', duration = 4500 } = {}) => {
    const id = ++nextId.current
    setToasts(list => [...list.slice(-(MAX_VISIBLE - 1)), { id, message, type }])
    if (duration > 0) timers.current.set(id, setTimeout(() => dismiss(id), duration))
    return id
  }, [dismiss])

  // Nettoyage des minuteries au démontage
  useEffect(() => {
    const pending = timers.current
    return () => { pending.forEach(clearTimeout); pending.clear() }
  }, [])

  const api = useMemo(() => ({
    push,
    dismiss,
    success: (message, opts) => push(message, { type: 'success', ...opts }),
    error:   (message, opts) => push(message, { type: 'error', duration: 8000, ...opts }),
    info:    (message, opts) => push(message, { type: 'info', ...opts }),
  }), [push, dismiss])

  return (
    <ToastContext.Provider value={api}>
      {children}
      <div
        className="fixed bottom-4 right-4 z-[100] flex flex-col gap-2 w-[min(24rem,calc(100vw-2rem))] pointer-events-none"
        role="region"
        aria-label="Notifications"
        aria-live="polite"
      >
        {toasts.map(({ id, message, type }) => {
          const { Icon, panel, icon } = TYPES[type] ?? TYPES.info
          return (
            <div
              key={id}
              className={`pointer-events-auto flex items-start gap-2.5 rounded-xl border px-3 py-2.5 shadow-xl backdrop-blur-sm animate-toast-in ${panel}`}
            >
              <Icon size={15} className={`flex-shrink-0 mt-0.5 ${icon}`} />
              <p className="flex-1 text-xs text-gray-200 leading-relaxed break-words">{message}</p>
              <button
                onClick={() => dismiss(id)}
                aria-label="Fermer la notification"
                className="flex-shrink-0 p-0.5 rounded text-gray-500 hover:text-gray-200 transition-colors"
              >
                <X size={13} />
              </button>
            </div>
          )
        })}
      </div>
    </ToastContext.Provider>
  )
}
