import { useState } from 'react';
import { AlertCircle } from 'lucide-react';
import { toast } from 'sonner';
import type { Message } from '@/api/types';
import { api } from '@/api/client';
import { Button } from '@/components/ui/button';

// feature #12: mistake-recovery sentinel. Inserted by the backend as a
// role='system', metadata.kind='mistake_recovery' row when the model hit
// repeated *different* errors (distinct from doom_loop, which is the same
// call repeated). Visual treatment mirrors CapHitSentinel / DoomLoopSentinel
// (amber card + alert icon). Non-escalated → recovery guidance was injected
// and the turn continues. Escalated → the turn was stopped; if can_continue
// is set, offer the same Continue affordance as the cap-hit sentinel.
// Loose `!= null` guards per the CLAUDE.md coder-message note (coder rows pass
// metadata as undefined, not null).
export function MistakeRecoverySentinel({ message }: { message: Message }) {
  const meta = message.metadata;
  const isMistakeRecovery =
    meta != null && typeof meta === 'object' && meta.kind === 'mistake_recovery';
  const failureKinds = isMistakeRecovery ? meta.failure_kinds : [];
  const escalated = isMistakeRecovery ? meta.escalated : false;
  const canContinue = isMistakeRecovery ? meta.can_continue === true : false;

  const [continuing, setContinuing] = useState(false);

  async function handleContinue() {
    if (continuing || !canContinue) return;
    setContinuing(true);
    try {
      await api.chats.continue(message.chat_id, message.id);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'continue failed');
    } finally {
      setContinuing(false);
    }
  }

  const kindsLabel =
    Array.isArray(failureKinds) && failureKinds.length > 0
      ? failureKinds.join(', ')
      : null;

  return (
    <div className="rounded-md border border-amber-500/40 bg-amber-500/10 text-sm">
      <div className="px-3 py-2 flex items-start gap-2">
        <AlertCircle className="size-4 text-amber-500 shrink-0 mt-0.5" />
        <div className="flex-1 min-w-0 space-y-1">
          <div className="text-xs font-medium text-amber-700 dark:text-amber-300">
            {escalated ? 'Repeated errors — turn stopped' : 'Recovering from repeated errors'}
          </div>
          <div className="text-xs text-muted-foreground">
            {escalated
              ? 'Repeated errors persisted — stopped the turn.'
              : kindsLabel
                ? `Hit repeated different errors (${kindsLabel}) — recovery guidance injected, continuing.`
                : 'Hit repeated different errors — recovery guidance injected, continuing.'}
          </div>
          {escalated && canContinue && (
            <div className="pt-1">
              <Button
                type="button"
                size="sm"
                variant="outline"
                onClick={() => void handleContinue()}
                disabled={continuing}
              >
                {continuing ? 'Continuing…' : 'Continue'}
              </Button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
