import { AlertCircle, RefreshCw } from 'lucide-react';

import { cn } from '@/lib/utils';

import { Button } from './button';

interface ErrorWithRetryProps {
  title?: string;
  message?: string;
  onRetry?: () => void;
  retrying?: boolean;
  className?: string;
  size?: 'sm' | 'md';
}

/**
 * Reusable error state with optional retry button for async/network failures.
 *
 * Usage:
 * ```tsx
 * <ErrorWithRetry
 *   message="Failed to load recommendations."
 *   onRetry={() => fetchData()}
 *   retrying={isLoading}
 * />
 * ```
 */
export function ErrorWithRetry({
  title = 'Something went wrong',
  message = 'An error occurred. Try again.',
  onRetry,
  retrying = false,
  className,
  size = 'md',
}: ErrorWithRetryProps) {
  const isSmall = size === 'sm';

  return (
    <div
      role="alert"
      className={cn(
        'flex flex-col items-center justify-center text-center',
        isSmall ? 'py-4 px-3' : 'py-8 px-4',
        className,
      )}
    >
      <div
        className={cn(
          'mb-3 rounded-full bg-destructive/10 flex items-center justify-center',
          isSmall ? 'p-2' : 'p-3',
        )}
      >
        <AlertCircle className={cn('text-destructive', isSmall ? 'h-4 w-4' : 'h-5 w-5')} />
      </div>
      <h3 className={cn('font-semibold text-foreground mb-1', isSmall ? 'text-sm' : 'text-base')}>
        {title}
      </h3>
      <p className={cn('text-muted-foreground max-w-sm mb-3', isSmall ? 'text-xs' : 'text-sm')}>
        {message}
      </p>
      {onRetry && (
        <Button
          variant="outline"
          size={isSmall ? 'sm' : 'default'}
          onClick={onRetry}
          disabled={retrying}
        >
          <RefreshCw
            className={cn('mr-1.5', isSmall ? 'h-3 w-3' : 'h-4 w-4', retrying && 'animate-spin')}
          />
          {retrying ? 'Retrying...' : 'Try Again'}
        </Button>
      )}
    </div>
  );
}
