import { useEffect, useMemo, useState } from 'react';
import Avatar from './Avatar';
import AgentFamilyAvatar from './AgentFamilyAvatar';
import Button from './Button';
import Form from './Form';
import Icon from './Icon';
import IconLoading from './IconLoading';
import Table from './Table';
import TextArea from './TextArea';
import plannerAgentAvatar from './avatar-assets/planner-agent.png';

const DEFAULT_DETAIL_FIELDS = [
  { key: '退款状态', value: '退款成功' },
  { key: '订单是否已退款', value: '已退款' },
  { key: '订单展示状态', value: '交易完成' },
  { key: '用户退款类型', value: '规则外退款' },
  { key: '预约状态', value: '已预约' },
];

const ROOT = 'tfds-agent-node-card flex w-full items-start gap-3 text-foreground [font-family:inherit]';
const NODE_AVATAR_SIZE = 'xs';
const CONTENT = 'flex min-w-0 flex-1 flex-col gap-3';
const META_ROW = 'flex min-w-0 items-center gap-3';
const TITLE = 'm-0 shrink-0 text-xs [font-weight:var(--font-semibold)] leading-4 text-foreground';
const TIMESTAMP = 'm-0 shrink-0 text-xs leading-4 text-foreground-muted';
const SUMMARY_ROW = 'flex min-w-0 flex-wrap items-center gap-2';
const SUMMARY = 'm-0 min-w-0 text-sm font-normal leading-6 text-foreground';
const MENTION = 'inline-flex shrink-0 items-center rounded-full bg-fill px-2 py-1 text-xs leading-4 text-link';
const HEADER_DETAIL_ACTION = [
  'ml-auto inline-flex h-8 shrink-0 items-center gap-2 rounded-md px-2',
  'text-sm [font-weight:var(--font-semibold)] leading-5 text-foreground-secondary',
  'transition-colors tfds-motion-ui-fast hover:bg-fill hover:text-foreground',
  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blueGrey-400',
].join(' ');
const SURFACE = 'flex w-full min-w-0 flex-col rounded-lg bg-fill p-4';
const STATUS_ROW = 'flex min-w-0 items-center justify-between gap-3';
const STATUS_MAIN = 'flex min-w-0 flex-1 items-center gap-3';
const STATUS_TEXT = 'm-0 min-w-0 truncate text-sm [font-weight:var(--font-semibold)] leading-5 text-foreground';
const INLINE_ACTIONS = 'flex shrink-0 items-center gap-1';
const INLINE_ACTION = [
  'inline-flex h-6 items-center gap-2 rounded-md px-2',
  'text-sm [font-weight:var(--font-semibold)] leading-5 text-foreground',
  'transition-colors tfds-motion-ui-fast hover:bg-surface',
  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blueGrey-400',
].join(' ');
const TOGGLE = [
  'inline-flex size-6 items-center justify-center rounded-md text-foreground-secondary',
  'transition-colors tfds-motion-ui-fast hover:bg-surface hover:text-foreground',
  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blueGrey-400',
].join(' ');
const DETAILS_PANEL = 'flex max-h-[500px] min-w-0 flex-col overflow-y-auto overscroll-contain rounded-lg border border-white bg-card-secondary p-4';
const DETAIL_LIST = 'flex min-w-0 flex-col gap-2';
const DETAIL_ROW = 'grid min-w-0 grid-cols-[112px_minmax(0,1fr)] items-start gap-x-3 gap-y-2';
const DETAIL_KEY = 'min-w-0 text-sm font-normal leading-5 text-foreground-secondary whitespace-normal break-words [overflow-wrap:anywhere]';
const DETAIL_VALUE = 'min-w-0 text-sm font-normal leading-5 text-foreground whitespace-normal break-words [overflow-wrap:anywhere]';
const FOOTER = 'flex w-full items-center justify-end gap-3';
const DETAIL_FORM = 'w-full min-w-0 gap-2';
const FIELD_DESCRIPTION_CARD_TYPE = 'field-description';
const PLAIN_TEXT_CARD_TYPE = 'plain-text';
const CUSTOM_CARD_TYPE = 'custom';
const FORM_CARD_TYPE = 'form';
const AGGREGATE_CARD_TYPE = 'aggregate';
const DEFAULT_PLAIN_TEXT_CONTENT =
  '经核对抖音电商订单状态、退款记录与预约履约信息，当前订单已完成退款，平台侧展示为交易完成。结合现有售后规则判断，本次退款属于规则外退款场景，建议人工客服进一步确认用户当前诉求、补偿口径与后续履约安排，再决定是否继续执行补发或补偿动作，避免出现重复退款、误触发补发流程或对用户承诺不一致的情况。';
const TICKO_FINAL_CONCLUSION =
  '规则、举证与责任策略均支持维持不退运费处理结论';
const DEFAULT_AGGREGATE_CONCLUSION =
  TICKO_FINAL_CONCLUSION;
const DEFAULT_AGGREGATE_FIELDS = [
  { key: '综合结论', value: '规则、举证与责任策略均支持维持不退运费处理结论' },
  { key: '执行动作', value: '确认不退运费，回写工单处理结论，并同步用户解释话术' },
  { key: '客服话术', value: '经核实，本单为无理由退货且未命中商家承担运费规则，退货运费需由消费者承担' },
  { key: '补偿建议', value: '可视用户情绪提供 5 元无门槛券安抚，但不修改责任判定' },
  {
    key: '后续跟进',
    value: '若用户补充有效凭证，重新进入举证研判节点复核',
  },
];
const DEFAULT_AGGREGATE_SECTIONS = [];
const TICKO_FINAL_ACTIONS = {
  secondaryActionText: '修改',
  primaryActionText: '确认执行',
  detailActionLabel: '查看详情',
};
const DEFAULT_AGGREGATE_NODES = [
  {
    title: '规则识别Agent',
    agentFamilyAvatar: 'analysis',
    timestamp: '2026-05-26 14:18:03',
    summary: '已识别工单场景与售后规则',
    statusText: '无理由退运费规则已匹配',
    statusTone: 'success',
    detailFields: [
      { key: '工单类型', value: '抖音电商 · 售后 · 无理由退运费' },
      { key: '订单状态', value: '用户已申请退货退款，商家已签收退货包裹' },
      { key: '命中规则', value: '七天无理由退货场景下，非商品质量问题的退货运费默认由消费者承担' },
      { key: '风险提示', value: '若商家页面承诺包邮退换或商品存在质量异常，需要重新判定运费责任' },
    ],
  },
  {
    title: '举证研判Agent',
    agentFamilyAvatar: 'outbound',
    timestamp: '2026-05-26 14:18:42',
    summary: '已完成用户与商家举证核验',
    statusText: '双方举证材料已核验',
    statusTone: 'success',
    detailFields: [
      { key: '用户举证', value: '上传退货物流单、聊天记录截图，主张商家应承担退货运费' },
      { key: '商家举证', value: '提供商品详情页售后说明，未承诺无理由退货包邮' },
      { key: '物流信息', value: '退货包裹已签收，物流重量与订单商品重量基本一致' },
      { key: '举证结论', value: '未发现商品质量问题或商家承诺包邮退货证据，用户举证不足' },
    ],
  },
  {
    title: '责任策略Agent',
    agentFamilyAvatar: 'execution',
    timestamp: '2026-05-26 14:19:27',
    summary: '已生成平台责任判定与协商策略',
    statusText: '处理策略待客服确认',
    statusTone: 'pending',
    detailFields: [
      { key: '责任归属', value: '消费者原因无理由退货，退货运费由消费者承担' },
      { key: '平台建议', value: '维持商家拒绝退运费结论，同时向用户解释规则与举证依据' },
      { key: '安抚策略', value: '如用户强诉求，可建议客服发放小额优惠券作为体验补偿，不回退运费判责' },
      { key: '升级条件', value: '用户补充质量问题图片、平台承诺截图或商家包邮退货承诺后再升级复核' },
    ],
  },
  {
    title: '综合确认Agent',
    agentName: 'Ticko',
    agentFamilyAvatar: 'planner',
    timestamp: '2026-05-26 14:20:16',
    summary: 'Ticko 已完成最终综合确认',
    statusText: '待人工客服确认执行',
    statusTone: 'pending',
    detailFields: [
      ...DEFAULT_AGGREGATE_FIELDS,
    ],
    ...TICKO_FINAL_ACTIONS,
  },
];

/**
 * `cardType="form"` 默认表单数据：以「电商客服售后场景」为基线，承载多行多列的售后处理记录，
 * 让节点产出"按条目排成可查看 / 可比对的售后表单"。AI 在业务接入时可通过 `formColumns` /
 * `formDataSource` 覆盖列与行；`formPagination` 默认 false（节点内嵌不分页），有需要时可显式开启。
 */
const DEFAULT_FORM_COLUMNS = [
  { title: '订单号', dataIndex: 'orderNo', key: 'orderNo', type: 'text', width: 168 },
  { title: '商品名称', dataIndex: 'productName', key: 'productName', type: 'text', width: 200 },
  { title: '售后类型', dataIndex: 'afterSaleType', key: 'afterSaleType', type: 'tag', width: 120 },
  { title: '退款金额', dataIndex: 'refundAmount', key: 'refundAmount', type: 'text', width: 116 },
  { title: '处理状态', dataIndex: 'status', key: 'status', type: 'status', width: 132 },
];

const DEFAULT_FORM_DATA_SOURCE = [
  {
    id: 'aftersale-1',
    orderNo: '20260520-001',
    productName: '草莓气泡酒 礼盒装 6 瓶装',
    afterSaleType: { label: '规则外退款', tone: 'orange' },
    refundAmount: '¥128.00',
    status: { label: '退款成功', tone: 'success' },
  },
  {
    id: 'aftersale-2',
    orderNo: '20260518-204',
    productName: '小兔叽 玩偶毛绒抱枕',
    afterSaleType: { label: '仅退款', tone: 'blue' },
    refundAmount: '¥69.00',
    status: { label: '退款中', tone: 'pending' },
  },
  {
    id: 'aftersale-3',
    orderNo: '20260517-118',
    productName: '糯叽叽 桃酥礼盒 4 罐组合',
    afterSaleType: { label: '退货退款', tone: 'purple' },
    refundAmount: '¥218.00',
    status: { label: '待商家确认', tone: 'warning' },
  },
];

const DETAIL_FIELD_SELECT_OPTIONS = {
  退款状态: [
    { value: '退款成功', label: '退款成功' },
    { value: '退款中', label: '退款中' },
    { value: '退款失败', label: '退款失败' },
  ],
  预约状态: [
    { value: '已预约', label: '已预约' },
    { value: '未预约', label: '未预约' },
    { value: '预约中', label: '预约中' },
  ],
};

const CARD_TYPE_LABELS = {
  [FIELD_DESCRIPTION_CARD_TYPE]: '字段描述卡片',
  [PLAIN_TEXT_CARD_TYPE]: '纯文本',
  [CUSTOM_CARD_TYPE]: '自定义槽位',
  [FORM_CARD_TYPE]: '表单',
  [AGGREGATE_CARD_TYPE]: '聚合节点',
};

const STATUS_TONE_MAP = {
  success: {
    figmaIcon: 'complete',
  },
  pending: {
    iconLoadingRing: true,
  },
  warning: {
    figmaIcon: 'error',
  },
  error: {
    figmaIcon: 'error',
  },
  default: {
    iconName: 'message-check-circle-stroked',
    iconClassName: 'text-blueGrey-500',
  },
};

function AgentNodeStatusFigmaIcon({ type = 'complete' }) {
  if (type === 'error') {
    return (
      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true" focusable="false">
        <path
          fillRule="evenodd"
          clipRule="evenodd"
          d="M14 7C14 10.866 10.866 14 7 14C3.13401 14 0 10.866 0 7C0 3.13401 3.13401 0 7 0C10.866 0 14 3.13401 14 7ZM7.95455 10.5C7.95455 9.97282 7.52718 9.54545 7 9.54545C6.47282 9.54545 6.04545 9.97282 6.04545 10.5C6.04545 11.0272 6.47282 11.4545 7 11.4545C7.52718 11.4545 7.95455 11.0272 7.95455 10.5ZM7 2.54545C6.30881 2.54545 5.75953 3.1261 5.79787 3.81622L5.99251 7.31965C6.02221 7.85436 6.46446 8.27273 7 8.27273C7.53554 8.27273 7.97779 7.85436 8.00749 7.31965L8.20213 3.81622C8.24047 3.1261 7.69119 2.54545 7 2.54545Z"
          fill="#F2496F"
        />
      </svg>
    );
  }

  return (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true" focusable="false">
      <path
        d="M7 14C10.866 14 14 10.866 14 7C14 3.13401 10.866 0 7 0C3.13401 0 0 3.13401 0 7C0 10.866 3.13401 14 7 14ZM10.7438 5.61422L6.79979 10.4435C6.62003 10.6786 6.34139 10.817 6.04545 10.8182C5.74952 10.8194 5.46976 10.6833 5.28807 10.4497L3.06475 7.90423C2.7411 7.4881 2.81606 6.88838 3.23219 6.56472C3.64832 6.24106 4.24804 6.31603 4.5717 6.73216L6.03514 8.30064L9.22727 4.45455C9.54751 4.03578 10.1466 3.9559 10.5654 4.27613C10.9841 4.59637 11.064 5.19545 10.7438 5.61422Z"
        fill="#24CDA5"
      />
    </svg>
  );
}

function stopEvent(event) {
  event.stopPropagation();
}

function resolveDetailFieldType(field) {
  if (field?.type) return field.type;
  if (field?.key === '退款状态' || field?.key === '预约状态') return 'select';
  return 'input';
}

function normalizeDetailFields(fields) {
  if (!Array.isArray(fields)) return [];

  return fields
    .filter((item) => item?.key && item?.value !== undefined && item?.value !== null)
    .map((item, index) => {
      const type = resolveDetailFieldType(item);
      return {
        ...item,
        id: item.id || `agent-node-field-${index}`,
        key: String(item.key),
        value: item.value,
        type,
        options: item.options || DETAIL_FIELD_SELECT_OPTIONS[item.key] || undefined,
      };
    });
}

function normalizeAggregateSections(sections) {
  if (!Array.isArray(sections)) return [];

  return sections
    .filter((section) => section?.title && Array.isArray(section.items) && section.items.length > 0)
    .map((section, index) => ({
      ...section,
      id: section.id || `agent-aggregate-section-${index}`,
      title: String(section.title),
      items: section.items.map((item) => String(item)),
    }));
}

function AgentTeamAvatarStack({ avatars = ['analysis', 'outbound', 'execution', 'planner'] }) {
  return (
    <div className="flex shrink-0 items-center rounded-full bg-blueGrey-100 p-1" aria-hidden="true">
      {avatars.map((avatar, index) => (
        <AgentFamilyAvatar
          key={`${avatar}-${index}`}
          avatar={avatar}
          size={NODE_AVATAR_SIZE}
          className={index === 0 ? '' : '-ml-1.5'}
        />
      ))}
    </div>
  );
}

export default function AgentNodeCard({
  title = '规划Agent',
  agentName = '',
  timestamp = '2026-05-26 14:20:16',
  avatarSrc = plannerAgentAvatar,
  avatarAlt = '规划Agent头像',
  agentFamilyAvatar = null,
  summary = '我已经完成工单研判',
  mentionLabel = '@ 工单助手 Ticko',
  statusText = '已完成工单研判',
  statusTone = 'success',
  statusIconName = null,
  collapsed,
  defaultCollapsed = false,
  onCollapsedChange = null,
  collapsible = true,
  cardType = FIELD_DESCRIPTION_CARD_TYPE,
  detailFields = DEFAULT_DETAIL_FIELDS,
  textContent = DEFAULT_PLAIN_TEXT_CONTENT,
  /**
   * 自定义槽位内容：当 `cardType="custom"` 时启用，可传入任意 React 节点（图表、表格、
   * 卡片、表单、媒体卡、地图等任意 UI 组件）作为白卡槽位内容。槽位宽度跟随白卡容器自动
   * 撑满，内容容器最大高度为 500px，超出后在节点卡片内部纵向滚动。
   */
  customContent = null,
  /**
   * 表单类型节点（`cardType="form"`）的 Table 列配置：完全透传给业务组件 `Table` 的 `columns`，
   * 默认按"电商客服售后场景"提供 5 列基线（订单号 / 商品名称 / 售后类型 / 退款金额 / 处理状态），
   * 业务可按需覆盖。
   */
  formColumns = DEFAULT_FORM_COLUMNS,
  /**
   * 表单类型节点（`cardType="form"`）的 Table 行数据：完全透传给业务组件 `Table` 的 `dataSource`，
   * 默认按"电商客服售后场景"提供 3 条售后记录基线，业务可按需覆盖。
   */
  formDataSource = DEFAULT_FORM_DATA_SOURCE,
  /**
   * 表单类型节点（`cardType="form"`）的分页配置：节点内嵌默认 `false`（不分页），有需要时可显式
   * 传入业务组件 `Table` 的 `pagination` 对象。
   */
  formPagination = null,
  aggregateConclusion = DEFAULT_AGGREGATE_CONCLUSION,
  aggregateFields = DEFAULT_AGGREGATE_FIELDS,
  aggregateSections = DEFAULT_AGGREGATE_SECTIONS,
  aggregateNodes = DEFAULT_AGGREGATE_NODES,
  teamAvatars = ['analysis', 'outbound', 'execution', 'planner'],
  aggregateDetailActionLabel = '展开处理详情',
  aggregateCollapseActionLabel = '收起处理详情',
  showDetailAction = false,
  detailActionLabel = '查看详情',
  onDetailClick = null,
  editable = true,
  secondaryActionText = '修改',
  onSecondaryAction = null,
  primaryActionText = '确认执行',
  onPrimaryAction = null,
  onSave = null,
  onCancel = null,
  className = '',
  style = null,
}) {
  const isCollapsedControlled = collapsed !== undefined;
  const [innerCollapsed, setInnerCollapsed] = useState(defaultCollapsed);
  const [isEditing, setIsEditing] = useState(false);
  const [isAggregateDetailExpanded, setIsAggregateDetailExpanded] = useState(false);
  const normalizedDetailFields = useMemo(() => normalizeDetailFields(detailFields), [detailFields]);
  const normalizedAggregateFields = useMemo(() => normalizeDetailFields(aggregateFields), [aggregateFields]);
  const normalizedAggregateSections = useMemo(() => normalizeAggregateSections(aggregateSections), [aggregateSections]);
  const normalizedAggregateNodes = Array.isArray(aggregateNodes) ? aggregateNodes : DEFAULT_AGGREGATE_NODES;
  const [savedDetailFields, setSavedDetailFields] = useState(normalizedDetailFields);
  const [draftDetailFields, setDraftDetailFields] = useState(normalizedDetailFields);
  const normalizedTextContent =
    textContent === undefined || textContent === null
      ? DEFAULT_PLAIN_TEXT_CONTENT
      : String(textContent);
  const [savedTextContent, setSavedTextContent] = useState(normalizedTextContent);
  const [draftTextContent, setDraftTextContent] = useState(normalizedTextContent);

  useEffect(() => {
    if (!isCollapsedControlled) setInnerCollapsed(defaultCollapsed);
  }, [defaultCollapsed, isCollapsedControlled]);

  useEffect(() => {
    setSavedDetailFields(normalizedDetailFields);
    if (!isEditing) setDraftDetailFields(normalizedDetailFields);
  }, [normalizedDetailFields]);

  useEffect(() => {
    setSavedTextContent(normalizedTextContent);
    if (!isEditing) setDraftTextContent(normalizedTextContent);
  }, [normalizedTextContent]);

  const isCollapsed = isCollapsedControlled ? collapsed : innerCollapsed;
  const resolvedStatusTone = Object.prototype.hasOwnProperty.call(STATUS_TONE_MAP, statusTone)
    ? statusTone
    : 'default';
  const resolvedStatus = STATUS_TONE_MAP[resolvedStatusTone];
  const resolvedStatusIconName = statusIconName || resolvedStatus.iconName;
  const resolvedCardType = CARD_TYPE_LABELS[cardType] ? cardType : FIELD_DESCRIPTION_CARD_TYPE;
  const latestAggregateNode =
    resolvedCardType === AGGREGATE_CARD_TYPE && normalizedAggregateNodes.length > 0
      ? normalizedAggregateNodes[normalizedAggregateNodes.length - 1]
      : null;
  const effectiveTimestamp =
    resolvedCardType === AGGREGATE_CARD_TYPE
      ? (latestAggregateNode?.timestamp ?? timestamp)
      : timestamp;
  const effectiveAggregateConclusion = latestAggregateNode?.detailFields?.[0]?.value ?? aggregateConclusion;
  const effectiveAggregateFields = latestAggregateNode?.detailFields ?? aggregateFields;
  const effectiveAggregateDetailLabel = latestAggregateNode?.detailActionLabel ?? detailActionLabel;
  const effectiveSecondaryActionText =
    resolvedCardType === AGGREGATE_CARD_TYPE
      ? (latestAggregateNode?.secondaryActionText ?? secondaryActionText)
      : secondaryActionText;
  const effectivePrimaryActionText =
    resolvedCardType === AGGREGATE_CARD_TYPE
      ? (latestAggregateNode?.primaryActionText ?? primaryActionText)
      : primaryActionText;
  const isExpandedAggregate =
    resolvedCardType === AGGREGATE_CARD_TYPE && isAggregateDetailExpanded;
  const resolvedDetailFields = isEditing ? draftDetailFields : savedDetailFields;
  const resolvedTextContent = isEditing ? draftTextContent : savedTextContent;
  const showDetails =
    !isCollapsed &&
    (
      (resolvedCardType === FIELD_DESCRIPTION_CARD_TYPE && resolvedDetailFields.length > 0) ||
      (resolvedCardType === PLAIN_TEXT_CARD_TYPE && (isEditing || Boolean(resolvedTextContent))) ||
      (resolvedCardType === CUSTOM_CARD_TYPE && customContent !== null && customContent !== undefined) ||
      (resolvedCardType === FORM_CARD_TYPE && Array.isArray(formDataSource) && formDataSource.length > 0) ||
      (resolvedCardType === AGGREGATE_CARD_TYPE && (effectiveAggregateConclusion || normalizedAggregateFields.length > 0 || normalizedAggregateSections.length > 0))
    );
  const showFooter = !isCollapsed && (isEditing || effectiveSecondaryActionText || effectivePrimaryActionText);
  const resolvedTitle = [title, agentName].filter(Boolean).join(' | ');
  const shouldUseDefaultAgentFamilyAvatar = avatarSrc === plannerAgentAvatar;
  const resolvedAgentFamilyAvatar = agentFamilyAvatar
    ? agentFamilyAvatar
    : shouldUseDefaultAgentFamilyAvatar
      ? 'planner'
      : null;

  function updateCollapsed(nextCollapsed) {
    if (!isCollapsedControlled) setInnerCollapsed(nextCollapsed);
    onCollapsedChange?.(nextCollapsed);
  }

  function handleToggleClick(event) {
    stopEvent(event);
    if (!collapsible || isEditing) return;
    updateCollapsed(!isCollapsed);
  }

  function handleDetailClick(event) {
    stopEvent(event);
    onDetailClick?.();
  }

  function handleAggregateDetailToggle(event) {
    stopEvent(event);
    setIsAggregateDetailExpanded((current) => !current);
  }

  function handleSecondaryAction(event) {
    stopEvent(event);
    if (editable && !isEditing && resolvedCardType !== AGGREGATE_CARD_TYPE) {
      setDraftDetailFields(savedDetailFields);
      setDraftTextContent(savedTextContent);
      setIsEditing(true);
    }
    onSecondaryAction?.();
  }

  function handlePrimaryAction(event) {
    stopEvent(event);
    onPrimaryAction?.();
  }

  function handleCancelEdit(event) {
    stopEvent(event);
    setDraftDetailFields(savedDetailFields);
    setDraftTextContent(savedTextContent);
    setIsEditing(false);
    onCancel?.(resolvedCardType === PLAIN_TEXT_CARD_TYPE ? savedTextContent : savedDetailFields);
  }

  function handleSaveEdit(event) {
    stopEvent(event);
    if (resolvedCardType === PLAIN_TEXT_CARD_TYPE) {
      setSavedTextContent(draftTextContent);
    } else {
      setSavedDetailFields(draftDetailFields);
    }
    setIsEditing(false);
    onSave?.(resolvedCardType === PLAIN_TEXT_CARD_TYPE ? draftTextContent : draftDetailFields);
  }

  function updateDraftFieldValue(fieldId, nextValue) {
    setDraftDetailFields((current) =>
      current.map((item) => (item.id === fieldId ? { ...item, value: nextValue } : item))
    );
  }

  function renderFieldDescriptionCard() {
    if (isEditing) {
      const formItems = draftDetailFields.map((field) => ({
        id: field.id,
        label: field.key,
        type: field.type,
        value: field.value,
        options: field.options,
        placeholder: field.type === 'select' ? '请选择' : '请输入',
        onChange:
          field.type === 'select'
            ? (nextValue) => updateDraftFieldValue(field.id, nextValue ?? '')
            : (event) => updateDraftFieldValue(field.id, event?.target?.value ?? ''),
      }));

      return (
        <Form
          items={formItems}
          layout="vertical"
          labelPosition="left"
          labelWidth={112}
          size="md"
          debugLayout
          debugName="AgentNodeCardDetailForm"
          className={DETAIL_FORM}
          onSubmit={(event) => event.preventDefault()}
        />
      );
    }

    return (
      <div className={DETAIL_LIST}>
        {resolvedDetailFields.map((field) => (
          <div key={`${field.id}-${field.value}`} className={DETAIL_ROW}>
            <span className={DETAIL_KEY}>{field.key}</span>
            <span className={DETAIL_VALUE}>{field.value}</span>
          </div>
        ))}
      </div>
    );
  }

  function renderPlainTextCard() {
    if (isEditing) {
      return (
        <TextArea
          minRows={5}
          value={draftTextContent}
          placeholder="请输入节点说明"
          onChange={(event) => setDraftTextContent(event?.target?.value ?? '')}
          className="w-full"
        />
      );
    }

    return (
      <div className="min-w-0">
        <p className="m-0 whitespace-normal break-words text-sm leading-6 text-foreground [overflow-wrap:anywhere]">
          {resolvedTextContent}
        </p>
      </div>
    );
  }

  function renderFormCard() {
    return (
      <div className="flex w-full min-w-0 flex-col" data-tfds-region="agent-node-form-slot">
        <Table
          columns={formColumns}
          dataSource={formDataSource}
          rowKey="id"
          showSearchFilters={false}
          pagination={formPagination ?? false}
          emptyText="暂无售后记录"
        />
      </div>
    );
  }

  function renderAggregateCard() {
    const fields = normalizeDetailFields(effectiveAggregateFields);

    return (
      <div className="flex min-w-0 flex-col gap-4">
        <section className="flex min-w-0 flex-col gap-2">
          <h4 className="m-0 text-sm [font-weight:var(--font-semibold)] leading-5 text-foreground">Agent总结</h4>
          <p className="m-0 whitespace-normal break-words text-sm leading-5 text-foreground-secondary [overflow-wrap:anywhere]">
            {effectiveAggregateConclusion}
          </p>
          <div className={DETAIL_LIST}>
            {fields.map((field) => (
              <div key={`${field.id}-${field.value}`} className={DETAIL_ROW}>
                <span className={DETAIL_KEY}>{field.key}</span>
                <span className={DETAIL_VALUE}>{field.value}</span>
              </div>
            ))}
          </div>
        </section>

        {normalizedAggregateSections.map((section) => (
          <section key={section.id} className="flex min-w-0 flex-col gap-2">
            <h4 className="m-0 text-sm [font-weight:var(--font-semibold)] leading-5 text-foreground">{section.title}</h4>
            <ul className="m-0 flex min-w-0 list-disc flex-col gap-1 pl-5 text-sm leading-5 text-foreground-secondary">
              {section.items.map((item) => (
                <li key={item} className="whitespace-normal break-words [overflow-wrap:anywhere]">{item}</li>
              ))}
            </ul>
          </section>
        ))}
      </div>
    );
  }

  function renderAggregateDetailNodes() {
    return (
      <div className="flex min-w-0 flex-col gap-6" data-tfds-region="agent-aggregate-detail-nodes">
        {normalizedAggregateNodes.map((node, index) => {
          const isLatestNode = index === normalizedAggregateNodes.length - 1;

          return (
            <AgentNodeCard
              key={node.id || `${node.title}-${index}`}
              cardType={node.cardType || FIELD_DESCRIPTION_CARD_TYPE}
              title={node.title}
              agentName={node.agentName}
              timestamp={node.timestamp || effectiveTimestamp}
              avatarSrc={node.avatarSrc}
              avatarAlt={node.avatarAlt}
              agentFamilyAvatar={node.agentFamilyAvatar}
              summary={node.summary}
              mentionLabel={node.mentionLabel ?? mentionLabel}
              statusText={node.statusText}
              statusTone={node.statusTone || 'success'}
              statusIconName={node.statusIconName}
              defaultCollapsed={node.defaultCollapsed ?? false}
              detailFields={node.detailFields}
              textContent={node.textContent}
              customContent={node.customContent}
              formColumns={node.formColumns}
              formDataSource={node.formDataSource}
              formPagination={node.formPagination}
              showDetailAction={node.showDetailAction ?? true}
              detailActionLabel={node.detailActionLabel || (isLatestNode ? detailActionLabel : '查看详情')}
              secondaryActionText={node.secondaryActionText ?? (isLatestNode ? secondaryActionText : '')}
              primaryActionText={node.primaryActionText ?? (isLatestNode ? primaryActionText : '')}
              editable={node.editable ?? false}
              onDetailClick={node.onDetailClick}
              onSecondaryAction={node.onSecondaryAction}
              onPrimaryAction={node.onPrimaryAction}
            />
          );
        })}
      </div>
    );
  }

  return (
    <section
      className={[ROOT, className].filter(Boolean).join(' ')}
      style={style}
      data-tfds-component="AgentNodeCard"
      data-collapsed={isCollapsed ? 'true' : 'false'}
    >
      {resolvedCardType !== AGGREGATE_CARD_TYPE ? (
        resolvedAgentFamilyAvatar ? (
          <AgentFamilyAvatar avatar={resolvedAgentFamilyAvatar} size={NODE_AVATAR_SIZE} className="shrink-0" />
        ) : (
          <Avatar
            type="image"
            shape="round"
            size={NODE_AVATAR_SIZE}
            src={avatarSrc}
            alt={avatarAlt}
            className="shrink-0"
          />
        )
      ) : null}

      <div className={CONTENT}>
        {isExpandedAggregate ? (
          <div className={META_ROW}>
            <AgentTeamAvatarStack avatars={teamAvatars} />
            <p className={TITLE}>{resolvedTitle}</p>
            <p className={TIMESTAMP}>{effectiveTimestamp}</p>
            <button
              type="button"
              className={HEADER_DETAIL_ACTION}
              aria-expanded={isAggregateDetailExpanded}
              onClick={handleAggregateDetailToggle}
            >
              <Icon
                name={isAggregateDetailExpanded ? 'minimize-02-stroked' : 'maximize-02-stroked'}
                size={16}
                aria-hidden="true"
              />
              <span>{isAggregateDetailExpanded ? aggregateCollapseActionLabel : aggregateDetailActionLabel}</span>
            </button>
          </div>
        ) : (
          <>
            <div className={META_ROW}>
              {resolvedCardType === AGGREGATE_CARD_TYPE ? (
                <AgentTeamAvatarStack avatars={teamAvatars} />
              ) : null}
              <p className={TITLE}>{resolvedTitle}</p>
              <p className={TIMESTAMP}>{effectiveTimestamp}</p>
              {resolvedCardType === AGGREGATE_CARD_TYPE ? (
                <button
                  type="button"
                  className={HEADER_DETAIL_ACTION}
                  aria-expanded={isAggregateDetailExpanded}
                  onClick={handleAggregateDetailToggle}
                >
                  <Icon
                    name={isAggregateDetailExpanded ? 'minimize-02-stroked' : 'maximize-02-stroked'}
                    size={16}
                    aria-hidden="true"
                  />
                  <span>{isAggregateDetailExpanded ? aggregateCollapseActionLabel : aggregateDetailActionLabel}</span>
                </button>
              ) : null}
            </div>

            <div className={SUMMARY_ROW}>
              <p className={SUMMARY}>{summary}</p>
              {mentionLabel ? <span className={MENTION}>{mentionLabel}</span> : null}
            </div>
          </>
        )}

        {isExpandedAggregate ? renderAggregateDetailNodes() : (
        <div className={[SURFACE, !isCollapsed ? 'gap-4' : ''].filter(Boolean).join(' ')}>
          <div className={STATUS_ROW}>
            <div className={STATUS_MAIN}>
              {resolvedStatus.iconLoadingRing && !statusIconName ? (
                <IconLoading
                  size="sm"
                  ariaLabel={statusText || '加载中'}
                />
              ) : resolvedStatusIconName ? (
                <Icon
                  name={resolvedStatusIconName}
                  size={14}
                  className={resolvedStatus.iconClassName}
                  aria-hidden="true"
                />
              ) : (
                <AgentNodeStatusFigmaIcon type={resolvedStatus.figmaIcon} />
              )}
              <p className={STATUS_TEXT}>{statusText}</p>
            </div>

            <div className={INLINE_ACTIONS}>
              {!isCollapsed && showDetailAction ? (
                <button
                  type="button"
                  className={INLINE_ACTION}
                  onClick={handleDetailClick}
                >
                  <Icon name="file-05-stroked" size={14} aria-hidden="true" />
                  <span>{effectiveAggregateDetailLabel}</span>
                </button>
              ) : null}

              {collapsible ? (
                <button
                  type="button"
                  className={TOGGLE}
                  aria-expanded={!isCollapsed}
                  aria-label={isCollapsed ? '展开 Agent 节点卡片' : '收起 Agent 节点卡片'}
                  onClick={handleToggleClick}
                  disabled={isEditing}
                >
                  <Icon
                    name={isCollapsed ? 'chevron-down-stroked' : 'chevron-up-stroked'}
                    size={16}
                    aria-hidden="true"
                  />
                </button>
              ) : null}
            </div>
          </div>

          {showDetails ? (
            <div className={DETAILS_PANEL} data-card-type={resolvedCardType}>
              {resolvedCardType === FIELD_DESCRIPTION_CARD_TYPE ? renderFieldDescriptionCard() : null}
              {resolvedCardType === PLAIN_TEXT_CARD_TYPE ? renderPlainTextCard() : null}
              {resolvedCardType === CUSTOM_CARD_TYPE ? (
                <div className="flex w-full min-w-0 flex-col" data-tfds-region="agent-node-custom-slot">
                  {customContent}
                </div>
              ) : null}
              {resolvedCardType === FORM_CARD_TYPE ? renderFormCard() : null}
              {resolvedCardType === AGGREGATE_CARD_TYPE ? renderAggregateCard() : null}
            </div>
          ) : null}

          {showFooter ? (
            <div className={FOOTER}>
              {isEditing ? (
                <>
                  <Button
                    type="button"
                    variant="outline-black"
                    size="md"
                    onClick={handleCancelEdit}
                  >
                    取消
                  </Button>
                  <Button
                    type="button"
                    variant="primary"
                    size="md"
                    onClick={handleSaveEdit}
                  >
                    保存
                  </Button>
                </>
              ) : (
                <>
                  {effectiveSecondaryActionText ? (
                    <Button
                      type="button"
                      variant="outline-black"
                      size="md"
                      onClick={handleSecondaryAction}
                    >
                      {effectiveSecondaryActionText}
                    </Button>
                  ) : null}
                  {effectivePrimaryActionText ? (
                    <Button
                      type="button"
                      variant="primary"
                      size="md"
                      onClick={handlePrimaryAction}
                    >
                      {effectivePrimaryActionText}
                    </Button>
                  ) : null}
                </>
              )}
            </div>
          ) : null}
        </div>
        )}
      </div>
    </section>
  );
}

export { DEFAULT_DETAIL_FIELDS };
