import React, { useEffect, useCallback } from 'react';
import clsx from 'clsx';
import { Check, X, AlertTriangle, Info } from 'lucide-react';
import { useUIStore, Toast as ToastType } from '@/store/uiStore';

const toastStyles: Record<ToastType['type'], string> = {
  success: 'bg-success-50 border-success-500 text-success-800',
  error: 'bg-danger-50 border-danger-500 text-danger-800',
  warning: 'bg-warning-50 border-warning-500 text-warning-800',
  info: 'bg-primary-50 border-primary-500 text-primary-800',
};

const toastIcons: Record<ToastType['type'], React.ComponentType<{ className?: string }>> = {
  success: Check,
  error: X,
  warning: AlertTriangle,
  info: Info,
};

function ToastItem({ toast, onRemove }: { toast: ToastType; onRemove: (id: string) => void }) {
  useEffect(() => {
    const duration = toast.duration ?? 5000;
    const timer = setTimeout(() => onRemove(toast.id), duration);
    return () => clearTimeout(timer);
  }, [toast.id, toast.duration, onRemove]);

  return (
    <div
      className={clsx(
        'flex items-start gap-3 p-4 rounded-lg border-l-4 shadow-md min-w-72 max-w-md',
        'motion-safe:animate-slide-in',
        toastStyles[toast.type]
      )}
      role="alert"
      aria-live="polite"
    >
      {(() => {
        const Icon = toastIcons[toast.type];
        return <Icon className="h-5 w-5 flex-shrink-0 mt-0.5" aria-hidden="true" />;
      })()}
      <p className="flex-1 text-sm font-medium">{toast.message}</p>
      <button
        onClick={() => onRemove(toast.id)}
        className="flex-shrink-0 text-current opacity-60 hover:opacity-100 min-h-touch min-w-touch flex items-center justify-center rounded focus:outline-none focus-visible:ring-2 focus-visible:ring-current"
        aria-label="Close notification"
      >
        <X className="h-4 w-4" aria-hidden="true" />
      </button>
    </div>
  );
}

export function ToastContainer() {
  const { toasts, removeToast } = useUIStore();
  const handleRemove = useCallback((id: string) => removeToast(id), [removeToast]);

  return (
    <div
      className="fixed top-4 right-4 z-[100] flex flex-col gap-2"
      aria-live="polite"
      aria-atomic="false"
      data-testid="toast-container"
    >
      {toasts.map((toast) => (
        <ToastItem key={toast.id} toast={toast} onRemove={handleRemove} />
      ))}
    </div>
  );
}

export function useToast() {
  const { addToast, removeToast } = useUIStore();
  return {
    success: (message: string, duration?: number) => addToast({ type: 'success', message, duration }),
    error: (message: string, duration?: number) => addToast({ type: 'error', message, duration }),
    warning: (message: string, duration?: number) => addToast({ type: 'warning', message, duration }),
    info: (message: string, duration?: number) => addToast({ type: 'info', message, duration }),
    remove: removeToast,
  };
}
