'use client';

import React, { useEffect, useState } from 'react';
import { Toast, useToast } from './ToastContext';
import './ToastContainer.css';

interface ToastItemProps {
  toast: Toast;
  onRemove: (id: string) => void;
}

function ToastItem({ toast, onRemove }: ToastItemProps) {
  const [isVisible, setIsVisible] = useState(false);
  const [isLeaving, setIsLeaving] = useState(false);

  useEffect(() => {
    // Trigger entrance animation
    setTimeout(() => setIsVisible(true), 50);
  }, []);

  const handleRemove = () => {
    setIsLeaving(true);
    setTimeout(() => onRemove(toast.id), 300);
  };

  const getToastIcon = () => {
    switch (toast.type) {
      case 'success':
        return '✓';
      case 'error':
        return '✕';
      case 'warning':
        return '⚠';
      case 'info':
        return 'ℹ';
      default:
        return '';
    }
  };

  return (
    <div
      className={`
        toast-content 
        toast-${toast.type} 
        ${isVisible ? 'toast-enter' : ''}
        ${isLeaving ? 'toast-leave' : ''}
      `}
      style={{
        transform: isVisible ? 'translateX(0)' : 'translateX(100%)',
        opacity: isLeaving ? 0 : 1,
      }}
    >
      <div className="toast-icon">
        {getToastIcon()}
      </div>
      <div className="toast-body">
        {toast.title && (
          <div className="toast-title">{toast.title}</div>
        )}
        <div className="toast-message">{toast.message}</div>
      </div>
      <button 
        className="toast-close" 
        onClick={handleRemove}
        aria-label="Close notification"
      >
        ✕
      </button>
      {toast.duration && toast.duration > 0 && (
        <div className="toast-progress">
          <div 
            className="toast-progress-bar"
            style={{
              animation: `toast-progress ${toast.duration}ms linear forwards`
            }}
          />
        </div>
      )}
    </div>
  );
}

export default function ToastContainer() {
  const { toasts, removeToast } = useToast();

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

  return (
    <div className="toast-container">
      {toasts.map((toast) => (
        <ToastItem
          key={toast.id}
          toast={toast}
          onRemove={removeToast}
        />
      ))}
    </div>
  );
}
