'use client';

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

const ToastContext = createContext();

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

export const ToastProvider = ({ children }) => {
    const [toasts, setToasts] = useState([]);

    const addToast = useCallback((toast) => {
        const id = Date.now() + Math.random();
        const newToast = {
            id,
            type: 'info',
            duration: 5000,
            dismissible: true,
            isAutoRemoving: false,
            ...toast,
        };

        setToasts(prev => [...prev, newToast]);

        if (newToast.duration > 0) {
            setTimeout(() => {
                // First mark the toast for auto-removal
                setToasts(prev => prev.map(t => 
                    t.id === id ? { ...t, isAutoRemoving: true } : t
                ));
                
                // Then remove it after animation (300ms)
                setTimeout(() => {
                    removeToast(id);
                }, 300);
            }, newToast.duration);
        }

        return id;
    }, []);

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

    const clearAllToasts = useCallback(() => {
        setToasts([]);
    }, []);

    // Convenience methods for different toast types
    const success = useCallback((message, options = {}) => {
        return addToast({
            type: 'success',
            message,
            ...options,
        });
    }, [addToast]);

    const error = useCallback((message, options = {}) => {
        return addToast({
            type: 'error',
            message,
            duration: 7000, // Longer duration for errors
            ...options,
        });
    }, [addToast]);

    const warning = useCallback((message, options = {}) => {
        return addToast({
            type: 'warning',
            message,
            duration: 6000,
            ...options,
        });
    }, [addToast]);

    const info = useCallback((message, options = {}) => {
        return addToast({
            type: 'info',
            message,
            ...options,
        });
    }, [addToast]);

    const value = useMemo(() => ({
        toasts,
        addToast,
        removeToast,
        clearAllToasts,
        success,
        error,
        warning,
        info,
    }), [toasts, addToast, removeToast, clearAllToasts, success, error, warning, info]);

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

export default ToastContext;

