'use client'

import { useEffect, useState } from 'react'
import { FaCheck, FaTimes, FaInfoCircle } from 'react-icons/fa'
import type { Toast as ToastType } from '@/contexts/ToastContext'

interface ToastProps extends ToastType {
    onClose: () => void
}

export default function Toast({ message, type = 'success', duration = 3000, onClose }: ToastProps) {
    const [progress, setProgress] = useState(100)
    const [isVisible, setIsVisible] = useState(true)
    const [isExiting, setIsExiting] = useState(false)

    useEffect(() => {
        const progressInterval = setInterval(() => {
            setProgress((prev) => {
                const newProgress = prev - (100 / (duration / 50))
                return newProgress <= 0 ? 0 : newProgress
            })
        }, 50)
        const timer = setTimeout(() => {
            setIsExiting(true)
            setTimeout(() => {
                setIsVisible(false)
                onClose()
            }, 300)
        }, duration)
        return () => {
            clearInterval(progressInterval)
            clearTimeout(timer)
        }
    }, [duration, onClose])

    if (!isVisible) return null

    const bgColor = type === 'success'
        ? 'bg-green-500'
        : type === 'error'
            ? 'bg-red-500'
            : 'bg-blue-500'

    const progressColor = type === 'success'
        ? 'bg-green-600'
        : type === 'error'
            ? 'bg-red-600'
            : 'bg-blue-600'

    const Icon = type === 'success'
        ? FaCheck
        : type === 'error'
            ? FaTimes
            : FaInfoCircle

    return (
        <div className={isExiting ? 'animate-slide-down-fade-out' : 'animate-slide-up-fade-in'}>
            <div className={`${bgColor} text-white rounded-lg shadow-xl px-6 py-4 min-w-[300px] max-w-[500px] relative overflow-hidden`}>
                <div className="flex items-center gap-3">
                    <div className="flex-shrink-0 w-6 h-6 rounded-full border-2 border-white flex items-center justify-center bg-white/20">
                        <Icon className="w-3.5 h-3.5" />
                    </div>
                    <span className="font-semibold text-base">{message}</span>
                </div>
                <div className="absolute bottom-0 left-0 right-0 h-1.5 bg-black/20">
                    <div
                        className={`${progressColor} h-full transition-all duration-50 ease-linear`}
                        style={{ width: `${progress}%` }}
                    />
                </div>
            </div>
        </div>
    )
}

