"use client";

import { AlertTriangle, RotateCcw } from "lucide-react";
import type { ErrorBlock as ErrorBlockData, OutgoingInput } from "@/lib/chat/types";
import { useChatBlocks } from "../ChatBlockContext";

/**
 * A handled failure reported by the bot. The original turn already has a
 * stored reply on the server, so "retry" re-asks with a fresh message id
 * rather than replaying the old one (which would just return this error).
 * A form submit is re-asked on behalf of that form, so a success marks it
 * submitted and later attempts share the form's id (see `useChat`).
 */
export default function ErrorBlock({
  block,
  source,
  sourceFormKey,
}: {
  block: ErrorBlockData;
  source: OutgoingInput | null;
  sourceFormKey?: string;
}) {
  const { copy, busy, sendAction, sendText, isFormSubmitted, isFormDismissed } = useChatBlocks();
  // Re-asking a submit whose form has since gone through would write twice.
  const canRetry =
    block.retryable && !(sourceFormKey && (isFormSubmitted(sourceFormKey) || isFormDismissed(sourceFormKey)));

  const retry = () => {
    if (!source) return void sendAction({ type: "menu" });
    if (source.kind === "message") void sendText(source.text);
    else void sendAction(source.action, sourceFormKey ? { formKey: sourceFormKey } : undefined);
  };

  return (
    <div role="alert" className="w-full rounded-xl bg-red-50 px-3 py-2 text-xs text-red-800 ring-1 ring-red-100">
      <div className="flex items-start gap-2">
        <AlertTriangle size={14} className="mt-0.5 shrink-0" aria-hidden />
        <p className="flex-1 whitespace-pre-line break-words">{block.text}</p>
      </div>
      {canRetry ? (
        <button
          type="button"
          onClick={retry}
          disabled={busy}
          className="mt-2 inline-flex items-center gap-1 rounded-md bg-white px-2 py-1 text-[11px] font-semibold text-[#CC1414] ring-1 ring-red-200 hover:bg-red-100 disabled:opacity-60"
        >
          <RotateCcw size={12} aria-hidden /> {copy.retry}
        </button>
      ) : null}
    </div>
  );
}
