import { useEffect, useState } from 'react'
import { CheckCircle2, X } from 'lucide-react'
import { TOAST_EVENT, type ToastPayload } from '../lib/cart'
import './ToastHost.css'

type ToastItem = ToastPayload & { id: number }

export default function ToastHost() {
  const [toasts, setToasts] = useState<ToastItem[]>([])

  useEffect(() => {
    function onToast(event: Event) {
      const custom = event as CustomEvent<ToastPayload>
      const id = Date.now() + Math.random()
      const payload = custom.detail
      if (!payload?.message) return
      setToasts((current) => [...current, { ...payload, id }])
      window.setTimeout(() => {
        setToasts((current) => current.filter((toast) => toast.id !== id))
      }, 3200)
    }

    window.addEventListener(TOAST_EVENT, onToast)
    return () => window.removeEventListener(TOAST_EVENT, onToast)
  }, [])

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

  return (
    <div className="toast-host" aria-live="polite">
      {toasts.map((toast) => (
        <div key={toast.id} className="toast-card">
          <div className="toast-card__icon" aria-hidden>
            <CheckCircle2 size={22} strokeWidth={1.75} />
          </div>
          <div className="toast-card__body">
            <p className="toast-card__message">{toast.message}</p>
            {toast.detail && <p className="toast-card__detail">{toast.detail}</p>}
          </div>
          <button
            type="button"
            className="toast-card__close"
            aria-label="بستن"
            onClick={() =>
              setToasts((current) => current.filter((item) => item.id !== toast.id))
            }
          >
            <X size={16} />
          </button>
        </div>
      ))}
    </div>
  )
}
