/**
 * Structured chat error message component.
 *
 * Renders SSE error events in the chat area with a visually distinct
 * background and red accent left border, clearly separated from normal
 * assistant messages. Displays error code, message, detail, and an
 * optional `suggestedAction` as a highlighted tip.
 *
 * Error-code-specific behaviors:
 * - `AGENT_TIMEOUT`         — informational (user can send a message to resume)
 * - `SDK_SUBPROCESS_TIMEOUT` — informational (user can send a message to resume)
 * - `RATE_LIMIT_EXCEEDED`   — countdown timer, auto-re-enables on expiry
 * - `SERVICE_UNAVAILABLE`   — triggers immediate health check
 *
 * Key exports:
 * - `ChatErrorMessage`      — React component
 * - `ChatErrorMessageProps`  — prop interface
 */

import { useEffect, useState } from 'react';
import { useHealth } from '../../contexts/HealthContext';

export interface ChatErrorMessageProps {
  error: {
    code?: string;
    message?: string;
    detail?: string;
    suggestedAction?: string;
    retryAfter?: number;
  };
  /** Callback for QUEUE_TIMEOUT retry — re-sends the saved message when a slot opens. */
  onRetry?: () => void;
}

export function ChatErrorMessage({ error, onRetry }: ChatErrorMessageProps) {
  const { triggerHealthCheck } = useHealth();

  // SERVICE_UNAVAILABLE triggers immediate health check
  useEffect(() => {
    if (error.code === 'SERVICE_UNAVAILABLE') {
      triggerHealthCheck();
    }
  }, [error.code, triggerHealthCheck]);

  return (
    <div
      className={`border-l-4 rounded-r-lg p-4 my-2 ${
        // Informational errors (timeouts, queue) get amber styling — less alarming.
        // Hard errors (rate limit, credentials, service down) get red.
        error.code === 'SDK_SUBPROCESS_TIMEOUT' || error.code === 'AGENT_TIMEOUT' || error.code === 'QUEUE_TIMEOUT' || !error.code
          ? 'border-amber-500 bg-amber-950/30'
          : 'border-red-500 bg-red-950/40'
      }`}
      role="alert"
    >
      {/* Error header */}
      <div className="flex items-center gap-2 mb-1">
        <span className={`material-symbols-outlined text-lg ${
          error.code === 'SDK_SUBPROCESS_TIMEOUT' || error.code === 'AGENT_TIMEOUT' || error.code === 'QUEUE_TIMEOUT' || !error.code
            ? 'text-amber-400'
            : 'text-red-400'
        }`}>
          {error.code === 'SDK_SUBPROCESS_TIMEOUT' || error.code === 'AGENT_TIMEOUT'
            ? 'schedule'
            : error.code === 'QUEUE_TIMEOUT'
              ? 'hourglass_top'
              : !error.code
                ? 'sync_problem'
                : 'error'}
        </span>
        <span className={`font-semibold text-sm ${
          error.code === 'SDK_SUBPROCESS_TIMEOUT' || error.code === 'AGENT_TIMEOUT' || error.code === 'QUEUE_TIMEOUT' || !error.code
            ? 'text-amber-400'
            : 'text-red-400'
        }`}>
          {error.code === 'SDK_SUBPROCESS_TIMEOUT'
            ? 'AI Service Timeout'
            : error.code === 'AGENT_TIMEOUT'
              ? 'Response Timeout'
              : error.code === 'RATE_LIMIT_EXCEEDED'
                ? 'Rate Limited'
                : error.code === 'SERVICE_UNAVAILABLE'
                  ? 'Service Unavailable'
                  : error.code === 'CREDENTIALS_EXPIRED'
                    ? 'Credentials Expired'
                    : error.code === 'QUEUE_TIMEOUT'
                      ? 'Slots Busy'
                      : error.code ?? 'Interrupted'}
        </span>
      </div>

      {/* Error message */}
      <p className="text-[var(--color-text)] text-sm mb-1">
        {error.message ?? 'An error occurred'}
      </p>

      {/* Detail */}
      {error.detail && (
        <p className="text-[var(--color-text-muted)] text-xs mb-2">
          {error.detail}
        </p>
      )}

      {/* Suggested action */}
      {error.suggestedAction && (
        <div className="bg-yellow-500/10 border border-yellow-500/30 rounded px-3 py-2 text-yellow-200 text-sm">
          💡 {error.suggestedAction}
        </div>
      )}

      {error.code === 'RATE_LIMIT_EXCEEDED' && error.retryAfter && (
        <RateLimitCountdownInline retryAfterSec={error.retryAfter} />
      )}

      {error.code === 'QUEUE_TIMEOUT' && onRetry && (
        <button
          type="button"
          onClick={onRetry}
          className="mt-3 px-4 py-1.5 bg-blue-600 hover:bg-blue-500 text-white text-sm rounded transition-colors"
        >
          ↻ Retry when slot opens
        </button>
      )}
    </div>
  );
}

/**
 * Inline countdown for RATE_LIMIT_EXCEEDED errors.
 * Self-contained timer that decrements every second.
 */
function RateLimitCountdownInline({ retryAfterSec }: { retryAfterSec: number }) {
  const [remaining, setRemaining] = useState(retryAfterSec);

  // Reset remaining when retryAfterSec prop changes (e.g. new rate limit)
  useEffect(() => {
    setRemaining(retryAfterSec);
  }, [retryAfterSec]);

  useEffect(() => {
    if (remaining <= 0) return;
    const timer = setInterval(() => {
      setRemaining((prev: number) => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, [retryAfterSec]); // restart timer when retryAfterSec changes

  if (remaining <= 0) {
    return (
      <p className="text-green-400 text-sm mt-2">
        ✓ Rate limit expired — you may resume.
      </p>
    );
  }

  return (
    <p className="text-yellow-400 text-sm mt-2">
      ⏳ Rate limited — resuming in {remaining}s
    </p>
  );
}
