import { Descriptions, Empty, Table, Tag, Typography } from 'antd';

function scalar(value: unknown) {
  if (value === null || value === undefined) return '-';
  if (typeof value === 'boolean') return value ? <Tag color="green">是</Tag> : <Tag>否</Tag>;
  if (typeof value === 'object') return <Typography.Text code>{JSON.stringify(value)}</Typography.Text>;
  return String(value);
}

function rowsFrom(payload: unknown): Record<string, unknown>[] | null {
  if (Array.isArray(payload)) return payload.filter((item) => item && typeof item === 'object') as Record<string, unknown>[];
  if (!payload || typeof payload !== 'object') return null;
  const object = payload as Record<string, unknown>;
  for (const key of ['items', 'data', 'results']) {
    if (Array.isArray(object[key])) return object[key] as Record<string, unknown>[];
  }
  return null;
}

export function ResponseView({ payload }: { payload: unknown }) {
  if (payload === undefined) return <Empty description="填写查询条件后执行接口" />;
  if (payload === null) return <Empty description="操作已完成，后端未返回响应体" />;
  const rows = rowsFrom(payload);
  if (rows) {
    if (!rows.length) return <Empty description="暂无数据" />;
    const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))].slice(0, 8);
    return (
      <Table
        size="small"
        rowKey={(row, index) => String(row.id ?? row.code ?? row.userId ?? index)}
        dataSource={rows}
        scroll={{ x: 'max-content' }}
        pagination={{ pageSize: 20, showSizeChanger: true }}
        columns={keys.map((key) => ({
          title: key,
          dataIndex: key,
          key,
          ellipsis: true,
          render: scalar,
        }))}
      />
    );
  }
  if (typeof payload === 'object') {
    return (
      <Descriptions bordered size="small" column={{ xs: 1, sm: 1, md: 2 }}>
        {Object.entries(payload as Record<string, unknown>).map(([key, value]) => (
          <Descriptions.Item key={key} label={key}>{scalar(value)}</Descriptions.Item>
        ))}
      </Descriptions>
    );
  }
  return <Typography.Text>{String(payload)}</Typography.Text>;
}
