'use client';

import React, { createContext, useContext, useState, useCallback } from 'react';

export interface Toast {
  id: string;
  type: 'success' | 'error' | 'warning' | 'info';
  title?: string;
  message: string;
  duration?: number;
}

interface ToastContextType {
  toasts: Toast[];
  addToast: (toast: Omit<Toast, 'id'>) => void;
  removeToast: (id: string) => void;
  showSuccess: (message: string, title?: string) => void;
  showError: (message: string, title?: string) => void;
  showWarning: (message: string, title?: string) => void;
  showInfo: (message: string, title?: string) => void;
}

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

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

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

  const addToast = useCallback((toast: Omit<Toast, 'id'>) => {
    const id = Math.random().toString(36).substr(2, 9);
    
    // Set default duration based on toast type if not provided
    let defaultDuration = 5000; // Default 5 seconds
    switch (toast.type) {
      case 'success':
        defaultDuration = 4000; // Success messages can be shorter
        break;
      case 'error':
        defaultDuration = 7000; // Error messages need more time to read
        break;
      case 'warning':
        defaultDuration = 6000; // Warnings need attention
        break;
      case 'info':
        defaultDuration = 5000; // Standard info duration
        break;
    }
    
    const newToast: Toast = {
      id,
      duration: toast.duration ?? defaultDuration,
      ...toast,
    };

    setToasts(prev => {
      // Limit to 5 toasts maximum to prevent UI overflow
      const updated = [...prev, newToast];
      return updated.length > 5 ? updated.slice(-5) : updated;
    });

    // Auto remove after duration
    if (newToast.duration && newToast.duration > 0) {
      const timer = setTimeout(() => {
        removeToast(id);
      }, newToast.duration);
      // Note: We might need to clear this timer if the component unmounts
      // but since ToastProvider is at the root, it's less of a concern.
    }
  }, [removeToast]);

  const showSuccess = useCallback((message: string, title?: string) => {
    addToast({ type: 'success', message, title });
  }, [addToast]);

  const showError = useCallback((message: string, title?: string) => {
    addToast({ type: 'error', message, title });
  }, [addToast]);

  const showWarning = useCallback((message: string, title?: string) => {
    addToast({ type: 'warning', message, title });
  }, [addToast]);

  const showInfo = useCallback((message: string, title?: string) => {
    addToast({ type: 'info', message, title });
  }, [addToast]);

  const value: ToastContextType = {
    toasts,
    addToast,
    removeToast,
    showSuccess,
    showError,
    showWarning,
    showInfo,
  };

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

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