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

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

type Toast = {
    id: string;
    type: ToastType;
    message: string;
    duration: number;
};

type ToastInput = {
    type?: ToastType;
    message: string;
    duration?: number;
};

type ToastContextValue = {
    showToast: (toast: ToastInput) => void;
};

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

const removeToastAfter = (toastId: string, duration: number, onRemove: (id: string) => void) => {
    window.setTimeout(() => onRemove(toastId), duration);
};

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 showToast = useCallback(
        ({ type = 'info', message, duration = 3000 }: ToastInput) => {
            const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
            const toast: Toast = { id, type, message, duration };
            setToasts((prev) => [...prev, toast]);
            removeToastAfter(id, duration, removeToast);
        },
        [removeToast],
    );

    const value = useMemo(() => ({ showToast }), [showToast]);

    return (
        <ToastContext.Provider value={value}>
            {children}
            <ToastContainer toasts={toasts} onDismiss={removeToast} />
        </ToastContext.Provider>
    );
}

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

function ToastContainer({
    toasts,
    onDismiss,
}: {
    toasts: Toast[];
    onDismiss: (id: string) => void;
}) {
    if (toasts.length === 0) {
        return null;
    }

    return (
        <div className="fixed right-6 top-6 z-50 flex flex-col gap-2">
            {toasts.map((toast) => (
                <div
                    key={toast.id}
                    className={`flex items-center justify-between gap-3 rounded-lg border px-4 py-3 text-sm shadow-md ${
                        toast.type === 'success'
                            ? 'border-green-200 bg-green-50 text-green-700'
                            : toast.type === 'error'
                              ? 'border-red-200 bg-red-50 text-red-700'
                              : 'border-slate-200 bg-white text-slate-700'
                    }`}
                >
                    <span>{toast.message}</span>
                    <button
                        type="button"
                        className="text-xs font-semibold uppercase tracking-wide opacity-70 hover:opacity-100"
                        onClick={() => onDismiss(toast.id)}
                    >
                        Fermer
                    </button>
                </div>
            ))}
        </div>
    );
}
