"use client"

import React, { createContext, useCallback, useContext, useMemo, useState } from "react"

type ToastVariant = "success" | "error" | "info" | "warning"

type Toast = {
  id: string
  title?: string
  description?: string
  variant?: ToastVariant
  durationMs?: number
}

type ToastContextValue = {
  toasts: Toast[]
  show: (toast: Omit<Toast, "id">) => void
  dismiss: (id: string) => void
}

const ToastContext = createContext<ToastContextValue | null>(null)

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

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

  const show = useCallback((toast: Omit<Toast, "id">) => {
    const id = Math.random().toString(36).slice(2)
    const duration = toast.durationMs ?? 4000
    const next: Toast = { id, ...toast }
    setToasts((prev) => [...prev, next])
    if (duration > 0) {
      setTimeout(() => dismiss(id), duration)
    }
  }, [dismiss])

  const value = useMemo(() => ({ toasts, show, dismiss }), [toasts, show, dismiss])

  return (
    <ToastContext.Provider value={value}>
      {children}
      <Toaster />
    </ToastContext.Provider>
  )
}

export function useToast() {
  const ctx = useContext(ToastContext)
  if (!ctx) throw new Error("useToast must be used within <ToastProvider>")
  return ctx
}

export function Toaster() {
  const ctx = useContext(ToastContext)
  if (!ctx) return null
  const { toasts, dismiss } = ctx
  return (
    <div className="fixed top-4 right-4 z-50 space-y-2">
      {toasts.map((t) => (
        <div
          key={t.id}
          className={[
            "min-w-[280px] max-w-sm rounded-md border px-4 py-3 shadow-lg",
            t.variant === "success" && "bg-green-50 border-green-300 text-green-900",
            t.variant === "error" && "bg-red-50 border-red-300 text-red-900",
            t.variant === "warning" && "bg-yellow-50 border-yellow-300 text-yellow-900",
            (!t.variant || t.variant === "info") && "bg-white border-gray-200 text-gray-900",
          ].filter(Boolean).join(" ")}
        >
          <div className="flex items-start justify-between gap-4">
            <div>
              {t.title && <div className="font-semibold">{t.title}</div>}
              {t.description && <div className="text-sm opacity-90 mt-0.5">{t.description}</div>}
            </div>
            <button
              onClick={() => dismiss(t.id)}
              className="text-sm opacity-60 hover:opacity-100"
              aria-label="Dismiss"
            >
              ✕
            </button>
          </div>
        </div>
      ))}
    </div>
  )
}


