import React, { useEffect, useState } from 'react';
import { X, CheckCircle, AlertCircle, Info } from 'lucide-react';

export type ToastType = 'success' | 'error' | 'info';

export interface ToastMessage {
    id: string;
    message: string;
    type: ToastType;
    duration?: number;
}

interface ToastProps {
    toast: ToastMessage;
    onClose: (id: string) => void;
}

const Toast: React.FC<ToastProps> = ({ toast, onClose }) => {
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        // Determine background color based on type
        // Animate in
        requestAnimationFrame(() => setIsVisible(true));

        const timer = setTimeout(() => {
            setIsVisible(false);
            setTimeout(() => onClose(toast.id), 300); // Wait for animation
        }, toast.duration || 3000);

        return () => clearTimeout(timer);
    }, [toast, onClose]);

    const bgColors = {
        success: 'bg-green-600',
        error: 'bg-destructive',
        info: 'bg-blue-600'
    };

    const icon = {
        success: <CheckCircle size={18} />,
        error: <AlertCircle size={18} />,
        info: <Info size={18} />
    };

    return (
        <div
            className={`
        flex items-center gap-3 px-4 py-3 rounded-lg shadow-lg text-white mb-2 transition-all duration-300 transform
        ${bgColors[toast.type]}
        ${isVisible ? 'translate-x-0 opacity-100' : 'translate-x-full opacity-0'}
      `}
            style={{ minWidth: '300px', maxWidth: '400px' }}
        >
            <div className="shrink-0">
                {icon[toast.type]}
            </div>
            <p className="text-sm font-medium flex-1">{toast.message}</p>
            <button
                onClick={() => { setIsVisible(false); setTimeout(() => onClose(toast.id), 300); }}
                className="text-white/80 hover:text-white"
            >
                <X size={16} />
            </button>
        </div>
    );
};

export const ToastContainer: React.FC<{ toasts: ToastMessage[], removeToast: (id: string) => void }> = ({ toasts, removeToast }) => {
    return (
        <div className="fixed bottom-4 right-4 z-50 flex flex-col items-end pointer-events-none">
            <div className="pointer-events-auto">
                {toasts.map(t => (
                    <Toast key={t.id} toast={t} onClose={removeToast} />
                ))}
            </div>
        </div>
    );
};

export default ToastContainer;
