import { useEffect, useState } from 'react';
import { router } from '@inertiajs/react';

const icons = {
    success: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
    ),
    error: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
    ),
};

const styles = {
    success: 'bg-emerald-50 border-emerald-400 text-emerald-800',
    error: 'bg-red-50 border-red-400 text-red-800',
};

const iconStyles = {
    success: 'text-emerald-500',
    error: 'text-red-500',
};

const progressStyles = {
    success: 'bg-emerald-400',
    error: 'bg-red-400',
};

function ToastItem({ type, message, onDismiss }) {
    const [visible, setVisible] = useState(false);
    const [exiting, setExiting] = useState(false);
    const [progress, setProgress] = useState(100);
    const duration = 4000;

    useEffect(() => {
        requestAnimationFrame(() => setVisible(true));

        const start = Date.now();
        const interval = setInterval(() => {
            const elapsed = Date.now() - start;
            const remaining = Math.max(0, 100 - (elapsed / duration) * 100);
            setProgress(remaining);
            if (remaining <= 0) clearInterval(interval);
        }, 30);

        const timer = setTimeout(() => {
            handleDismiss();
        }, duration);

        return () => {
            clearTimeout(timer);
            clearInterval(interval);
        };
    }, []);

    const handleDismiss = () => {
        setExiting(true);
        setTimeout(() => onDismiss(), 300);
    };

    return (
        <div
            className={`relative flex items-start gap-3 w-80 border-l-4 rounded-lg shadow-lg px-4 py-3 transition-all duration-300 ease-out cursor-pointer ${styles[type]} ${
                visible && !exiting ? 'translate-x-0 opacity-100' : 'translate-x-full opacity-0'
            }`}
            onClick={handleDismiss}
        >
            <span className={`flex-shrink-0 mt-0.5 ${iconStyles[type]}`}>{icons[type]}</span>
            <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold capitalize">{type}</p>
                <p className="text-sm mt-0.5 leading-snug">{message}</p>
            </div>
            <button onClick={handleDismiss} className="flex-shrink-0 mt-0.5 opacity-50 hover:opacity-100 transition-opacity">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
            {/* Progress bar */}
            <div className="absolute bottom-0 left-0 right-0 h-1 rounded-b-lg overflow-hidden bg-black/5">
                <div
                    className={`h-full transition-all duration-100 ease-linear ${progressStyles[type]}`}
                    style={{ width: `${progress}%` }}
                />
            </div>
        </div>
    );
}

export default function Toast() {
    const [toasts, setToasts] = useState([]);

    useEffect(() => {
        const removeFinish = router.on('success', (event) => {
            const flash = event.detail.page.props.flash;
            if (flash?.success) {
                setToasts((prev) => [...prev, { id: Date.now(), type: 'success', message: flash.success }]);
            }
            if (flash?.error) {
                setToasts((prev) => [...prev, { id: Date.now() + 1, type: 'error', message: flash.error }]);
            }
        });

        return () => removeFinish();
    }, []);

    const dismiss = (id) => {
        setToasts((prev) => prev.filter((t) => t.id !== id));
    };

    if (toasts.length === 0) return null;

    return (
        <div className="fixed top-4 right-4 z-[9999] flex flex-col gap-3">
            {toasts.map((toast) => (
                <ToastItem key={toast.id} type={toast.type} message={toast.message} onDismiss={() => dismiss(toast.id)} />
            ))}
        </div>
    );
}
