import FormTitle from '../../components/FormTitle';
import Table from '../../components/Table';
import TextArea from '../../components/TextArea';

/** 产物详情正文槽位默认占位文案（无 children / 无匹配演示内容时） */
export const ARTIFACT_DETAIL_PLACEHOLDER = '业务内容区域';

/**
 * 产物详情正文槽位 · 内容类型选型（设计规范事实源）
 * 右侧 `CopilotArtifactDetailPanel` 的 Body 是通用 UI 槽，按 artifact.type 映射 TFDS 组件。
 */
export const ARTIFACT_DETAIL_CONTENT_BY_TYPE = {
  web: { label: '网页预览', components: ['FormTitle', 'TextArea readOnly / 富文本', 'Empty'] },
  webpage: { label: '网页预览', components: ['FormTitle', 'TextArea readOnly / 富文本', 'Empty'] },
  code: { label: '代码 / Prompt', components: ['TextArea variant=code fillHeight readOnly', 'Button 复制'] },
  table: { label: '表格数据', components: ['Table', 'Filter（可选）'] },
  document: { label: '文档预览', components: ['FormTitle', 'TextArea readOnly / 文档预览占位'] },
  pdf: { label: 'PDF 预览', components: ['Empty type=document', '下载 Button'] },
  strategy: { label: '策略说明', components: ['Card type=info3', 'Form 字段描述'] },
  'batch-report': { label: '批测报告', components: ['Table', 'Tag 指标', 'FormTitle 小节'] },
  knowledge: { label: '知识条目', components: ['Card type=info3 列表', 'Tag'] },
  image: { label: '图片预览', components: ['媒体预览区', 'FormTitle 元信息'] },
  conversation: { label: '会话摘录', components: ['ChatMessage 只读列表（禁止可编辑输入）'] },
  feishu: { label: '飞书文档', components: ['外链占位 + Button', 'FormTitle'] },
  'feishu-sheet': { label: '飞书多维表', components: ['Table', 'Filter'] },
  default: { label: '通用业务区', components: ['FormTitle + 正文', 'Empty', 'Card / Table / Form 按语义择一'] },
};

const DEMO_TABLE_COLUMNS = [
  { title: '场景', dataIndex: 'scene', key: 'scene', width: 140 },
  { title: '责任方', dataIndex: 'owner', key: 'owner', width: 120 },
  { title: '运费承担', dataIndex: 'freight', key: 'freight', width: 120 },
  { title: '备注', dataIndex: 'note', key: 'note' },
];

const DEMO_TABLE_ROWS = [
  { id: '1', scene: '七天无理由', owner: '消费者', freight: '消费者承担', note: '未命中质量问题' },
  { id: '2', scene: '质量问题', owner: '商家', freight: '商家承担', note: '需有效凭证' },
  { id: '3', scene: '商家承诺包邮退', owner: '商家', freight: '商家承担', note: '以页面承诺为准' },
];

const DEMO_CODE_SNIPPET = `// 售后规则解析 — 退货运费判责
export function resolveFreightOwner(order, evidence) {
  if (order.promiseFreeReturn) return 'merchant';
  if (evidence.qualityIssue) return 'merchant';
  if (order.reason === 'no-reason') return 'consumer';
  return 'manual-review';
}`;

const DEMO_WEB_COPY = [
  '## 统一答复口径（摘要）',
  '1. 七天无理由退货：非质量问题退货运费默认由消费者承担。',
  '2. 商品质量问题：商家承担退货运费，需用户提供有效凭证。',
  '3. 商家页面承诺包邮退换：以商家承诺为准，平台协助核验。',
].join('\n');

function normalizeArtifactType(artifact) {
  const raw = String(artifact?.type || '').trim().toLowerCase();
  if (!raw) return 'default';
  if (raw === 'web') return 'webpage';
  return raw;
}

/** 预览态 TextArea：只读但保持正常字色与背景，禁止 disabled（会灰显） */
const PREVIEW_TEXTAREA = { readOnly: true, resize: 'none' };

function WebpageDetailDemo({ artifact }) {
  return (
    <div className="flex w-full min-w-0 flex-col gap-4">
      <FormTitle variant="level-3" title={artifact?.title || '网页产物预览'} />
      <TextArea
        value={DEMO_WEB_COPY}
        minRows={8}
        className="w-full"
        {...PREVIEW_TEXTAREA}
      />
    </div>
  );
}

function CodeDetailDemo() {
  return (
    <div className="flex h-full min-h-0 w-full min-w-0 flex-col">
      <TextArea
        variant="code"
        value={DEMO_CODE_SNIPPET}
        fillHeight
        className="flex-1 min-h-0 w-full"
        {...PREVIEW_TEXTAREA}
      />
    </div>
  );
}

function TableDetailDemo() {
  return (
    <div className="flex w-full min-w-0 flex-col gap-4">
      <FormTitle variant="level-3" title="判责对照表" />
      <Table
        columns={DEMO_TABLE_COLUMNS}
        dataSource={DEMO_TABLE_ROWS}
        rowKey="id"
        showSearchFilters={false}
        pagination={false}
      />
    </div>
  );
}

function GenericDetailDemo({ artifact }) {
  return (
    <div className="flex w-full min-w-0 flex-col gap-3">
      <FormTitle variant="level-3" title={artifact?.title || '产物详情'} />
      <p className="m-0 text-sm leading-6 text-foreground-secondary">
        此处为产物详情正文槽位，业务侧请按
        {' '}
        <code className="text-xs">artifact.type</code>
        {' '}
        映射 Table / TextArea / Card / Form 等 TFDS 组件，或传入自定义
        {' '}
        <code className="text-xs">children</code>
        。
      </p>
    </div>
  );
}

/**
 * 模板预览用：按产物 type 渲染差异化演示正文（业务接入应传 children 覆盖）。
 */
export function resolveArtifactDetailDemoContent(artifact) {
  if (!artifact) return null;
  const type = normalizeArtifactType(artifact);
  if (type === 'webpage') return <WebpageDetailDemo artifact={artifact} />;
  if (type === 'code') return <CodeDetailDemo />;
  if (type === 'table' || type === 'feishu-sheet') return <TableDetailDemo />;
  return <GenericDetailDemo artifact={artifact} />;
}

export function getArtifactDetailContentSpec(type) {
  const normalized = normalizeArtifactType({ type });
  return ARTIFACT_DETAIL_CONTENT_BY_TYPE[normalized] || ARTIFACT_DETAIL_CONTENT_BY_TYPE.default;
}
