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

type Flash = {
  success?: string | null;
  error?: string | null;
};

type Toast = {
  id: number;
  type: 'success' | 'error';
  message: string;
};

export function FlashToast() {
  const { flash } = usePage<{ flash: Flash }>().props;
  const [toasts, setToasts] = useState<Toast[]>([]);
  const counterRef = useRef(0);
  const prevFlashRef = useRef<Flash>({});

  useEffect(() => {
    const prev = prevFlashRef.current;
    const added: Toast[] = [];

    if (flash?.success && flash.success !== prev.success) {
      added.push({ id: ++counterRef.current, type: 'success', message: flash.success });
    }
    if (flash?.error && flash.error !== prev.error) {
      added.push({ id: ++counterRef.current, type: 'error', message: flash.error });
    }

    if (added.length > 0) {
      setToasts((prev) => [...prev, ...added]);
      prevFlashRef.current = { success: flash?.success, error: flash?.error };
    }
  }, [flash?.success, flash?.error]);

  function dismiss(id: number) {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }

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

  return (
    <div className="toast-stack" role="status" aria-live="polite">
      {toasts.map((toast) => (
        <ToastItem key={toast.id} toast={toast} onDismiss={() => dismiss(toast.id)} />
      ))}
    </div>
  );
}

function ToastItem({ toast, onDismiss }: { toast: Toast; onDismiss: () => void }) {
  useEffect(() => {
    const t = setTimeout(onDismiss, 4500);
    return () => clearTimeout(t);
  }, [onDismiss]);

  return (
    <div className={`toast-item toast-${toast.type}`}>
      <i className={`bi ${toast.type === 'success' ? 'bi-check-circle-fill' : 'bi-x-circle-fill'}`} />
      <span>{toast.message}</span>
      <button type="button" className="toast-close" aria-label="بستن" onClick={onDismiss}>
        <i className="bi bi-x" />
      </button>
    </div>
  );
}
