'use client'
import { CloseCircle, InfoCircle, TickCircle } from 'iconsax-react';
import React, { useState, useEffect } from 'react';

interface ToastAction {
    label: string;
    onClick: () => void;
}

interface Toast {
    id: string;
    message: string;
    type?: 'success' | 'error' | 'info';
    isExiting?: boolean;
    action?: ToastAction;
}

let addToast: (toast: Toast) => void;

const ToastContainer: React.FC = () => {
    const [toasts, setToasts] = useState<Toast[]>([]);

    // ثبت toast جدید
    const showToast = (toast: Toast) => {
        setToasts((prev) => [...prev, toast]);

        const dismissAfter = toast.action ? 6000 : 3000;

        setTimeout(() => {
            setToasts((prev) => prev.map(t =>
                t.id === toast.id ? { ...t, isExiting: true } : t
            ));

            // حذف از DOM بعد از اتمام انیمیشن
            setTimeout(() => {
                setToasts((prev) => prev.filter((t) => t.id !== toast.id));
            }, 300); // مدت زمان انیمیشن خروج
        }, dismissAfter);
    };

    const dismissToast = (id: string) => {
        setToasts((prev) => prev.map((t) =>
            t.id === id ? { ...t, isExiting: true } : t
        ));
        setTimeout(() => {
            setToasts((prev) => prev.filter((t) => t.id !== id));
        }, 300);
    };

    // تخصیص تابع نمایش toast به متغیر سراسری
    useEffect(() => {
        addToast = showToast;
    }, []);

    return (
        <div className="fixed top-4 text-sm right-0 left-0 mx-auto w-fit z-50 flex flex-col gap-2">
            {toasts.map((toast) => {
                const handleAction = () => {
                    toast.action?.onClick();
                    dismissToast(toast.id);
                };

                return (
                    <div
                        key={toast.id}
                        role={toast.action ? 'button' : undefined}
                        tabIndex={toast.action ? 0 : undefined}
                        onClick={toast.action ? handleAction : undefined}
                        onKeyDown={toast.action ? (e) => {
                            if (e.key === 'Enter' || e.key === ' ') {
                                e.preventDefault();
                                handleAction();
                            }
                        } : undefined}
                        className={`px-4 flex items-center gap-2 backdrop-blur-2xl h-16 min-w-[300px] rounded-2xl shadow-md 
                        ${toast.isExiting ? 'animate-slide-out-right' : 'animate-slide-in-right'} ${toast.type === 'success'
                            ? 'bg-white/70 text-black'
                            : toast.type === 'error'
                                ? 'bg-white/70 text-black'
                                : 'bg-white/70 text-black'
                        } ${toast.action ? 'cursor-pointer active:scale-[0.98] transition-transform' : ''}`}
                        style={{
                            animationFillMode: 'forwards',
                            animationDuration: '0.3s',
                            animationTimingFunction: 'ease-out'
                        }}
                    >
                        <div className="flex items-center gap-2 flex-1 min-w-0">
                            {
                                toast.type === 'success' ? <TickCircle className='size-5 shrink-0' color='green' /> :
                                    toast.type === 'error' ? <CloseCircle className='size-5 shrink-0' color='red' /> :
                                        <InfoCircle className='size-5 shrink-0' color='blue' />
                            }
                            <span className="truncate">{toast.message}</span>
                        </div>
                        {toast.action && (
                            <span className="shrink-0 rounded-xl bg-primary px-3 py-1.5 text-xs font-medium text-white pointer-events-none">
                                {toast.action.label}
                            </span>
                        )}
                    </div>
                );
            })}
        </div>
    );
};

type ToastOptions = {
    action?: ToastAction;
};

export const toast = (
    message?: string,
    type: 'success' | 'error' | 'info' = 'info',
    options?: ToastOptions
) => {
    addToast({ id: Date.now().toString(), message: message || '', type, action: options?.action });
};

export const toastLoginRequired = (
    onLogin: () => void,
    type: 'success' | 'error' | 'info' = 'info'
) => {
    toast('ابتدا لاگین کنید', type, {
        action: { label: 'ورود', onClick: onLogin },
    });
};

export default ToastContainer;