"use client";

import { createContext, useContext, useState, ReactNode } from "react";
import { X } from "lucide-react";

interface ToastOptions {
  title: string;
  status?: "success" | "error" | "info";
  duration?: number;
  isClosable?: boolean;
}

interface Toast extends ToastOptions {
  id: string;
}

interface ToastContextType {
  toast: (options: ToastOptions) => void;
}

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

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

  const toast = (options: ToastOptions) => {
    const id = Math.random().toString(36).substring(7);
    const newToast: Toast = { ...options, id };
    setToasts((prev) => [...prev, newToast]);

    if (options.duration !== 0) {
      setTimeout(() => {
        setToasts((prev) => prev.filter((t) => t.id !== id));
      }, options.duration || 3000);
    }
  };

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

  const getToastStyles = (status?: string) => {
    switch (status) {
      case "success":
        return "bg-green-500 text-white";
      case "error":
        return "bg-red-500 text-white";
      default:
        return "bg-gray-800 text-white dark:bg-gray-200 dark:text-gray-800";
    }
  };

  return (
    <ToastContext.Provider value={{ toast }}>
      {children}
      <div className="fixed top-4 right-4 z-50 flex flex-col gap-2">
        {toasts.map((t) => (
          <div
            key={t.id}
            className={`flex items-center gap-3 px-4 py-3 rounded-lg shadow-lg min-w-[300px] max-w-md ${getToastStyles(
              t.status
            )}`}
          >
            <span className="flex-1">{t.title}</span>
            {t.isClosable && (
              <button
                onClick={() => removeToast(t.id)}
                className="hover:opacity-70 transition-opacity"
                aria-label="Close"
              >
                <X size={16} />
              </button>
            )}
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}

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

// Legacy export for compatibility
export function toast(options: ToastOptions) {
  // This is a fallback for non-hook usage
  console.warn("Toast called outside of React context", options);
}
