import toast, { ToastOptions } from 'react-hot-toast';
import { clientErrorLogger } from './client-error-logger';

/**
 * Extract subsystem from current route
 */
function getCurrentSubsystem(): string {
  if (typeof window === 'undefined') return 'unknown';

  const path = window.location.pathname;

  // Map routes to subsystems
  if (path.includes('/storage')) return 'storage';
  if (path.includes('/system')) return 'system';
  if (path.includes('/docker')) return 'docker';
  if (path.includes('/updates')) return 'updates';
  if (path.includes('/agent/')) return 'agent';

  return 'unknown';
}

/**
 * Wrap toast.error to automatically log errors to backend
 * Implements ETHOS #1: Errors are History
 */
export const toastWithLogging = {
  error: (message: string, options?: ToastOptions & { subsystem?: string }) => {
    const subsystem = options?.subsystem || getCurrentSubsystem();

    // Log to backend asynchronously - don't block UI
    clientErrorLogger.logError({
      subsystem,
      error_type: 'ui_error',
      message: message.substring(0, 5000), // Prevent excessively long messages
      metadata: {
        component: options?.id,
        duration: options?.duration,
        position: options?.position,
        timestamp: new Date().toISOString(),
      },
    }).catch(() => {
      // Silently ignore logging failures - don't crash the UI
    });

    // Show toast to user
    return toast.error(message, options);
  },

  // Passthrough methods
  success: toast.success,
  info: (message: string, options?: ToastOptions) => toast(message, options),
  warning: (message: string, options?: ToastOptions) => toast(message, options),
  loading: toast.loading,
  dismiss: toast.dismiss,
  remove: toast.remove,
  promise: toast.promise,
};

/**
 * React hook for toast with automatic subsystem detection
 */
export function useToastWithLogging() {
  return {
    error: (message: string, options?: ToastOptions & { subsystem?: string }) => {
      return toastWithLogging.error(message, {
        ...options,
        subsystem: options?.subsystem || getCurrentSubsystem(),
      });
    },
    success: toast.success,
    info: (message: string, options?: ToastOptions) => toast(message, options),
    warning: (message: string, options?: ToastOptions) => toast(message, options),
    loading: toast.loading,
    dismiss: toast.dismiss,
  };
}
