import React from "react";
import { describeUniDeskError } from "./unidesk-error";

type AnyRecord = Record<string, any>;

const h = React.createElement;

function row(label: string, value: any) {
  return value ? [h("dt", { key: `${label}-label` }, label), h("dd", { key: label }, value)] : null;
}

export function UniDeskErrorBanner({ error, wide = false, fallback = "操作失败", className = "" }: AnyRecord) {
  if (!error) return null;
  const detail = describeUniDeskError(error, fallback);
  const rows = [
    row("请求", [detail.method, detail.url].filter(Boolean).join(" ")),
    row("状态", detail.status ? `HTTP ${detail.status}${detail.statusText ? ` ${detail.statusText}` : ""}` : ""),
    row("时间", detail.occurredAt),
    row("解析错误", detail.parseError),
    row("响应预览", detail.responsePreview),
  ].filter(Boolean);
  return h("div", {
    className: `form-error unidesk-error${wide ? " wide" : ""}${className ? ` ${className}` : ""}`,
    role: "alert",
    "data-testid": "unidesk-error",
  },
    h("div", { className: "unidesk-error-title" },
      h("strong", null, detail.title),
      detail.status ? h("span", { className: "unidesk-error-code" }, `HTTP ${detail.status}`) : null,
    ),
    detail.message ? h("pre", { className: "unidesk-error-message" }, detail.message) : null,
    rows.length > 0 ? h("dl", { className: "unidesk-error-details" }, rows) : null,
  );
}
