import { Table as Table } from '../b-end.js';
import { Tooltip as Tooltip } from '../b-end.js';
import { Input as Input } from '../b-end.js';
import { Filter as Filter } from '../b-end.js';
import { Icon as Icon } from '../b-end.js';
import { TOKEN_DATA_COLORS } from '../tokens';

const TABLE_BORDER_COLOR = '#EBEBEB';
const BODY_TEXT_COLOR = '#1F1F1F';
/** 均值线与均值文案使用标准橙色（Data 11 / #FF803C） */
const MEAN_DATA_COLOR = TOKEN_DATA_COLORS[10] ?? '#FF803C';
const BULLET_TARGET = MEAN_DATA_COLOR;
/** Figma：#53608F Fill 7% + 右侧描边 25% 2px（非全包围） */
const BULLET_BLOCK_FILL = 'rgba(83, 96, 143, 0.07)';
const BULLET_BLOCK_EDGE = 'rgba(83, 96, 143, 0.25)';
const BULLET_EDGE_WIDTH = 2;

/**
 * 与 Table 的列轨道规则保持一致（minmax + fr），保证均值线与单元格 1:1 对齐。
 */
const GRID_TEMPLATE_COLUMNS = [
  'minmax(96px, 112fr)',
  'minmax(96px, 168fr)',
  'minmax(96px, 168fr)',
  'minmax(96px, 188fr)',
  'minmax(96px, 168fr)',
  'minmax(132px, 104fr)',
].join(' ');
const TABLE_HEADER_HEIGHT = 44;
const BULLET_BAR_HEIGHT = 22;

const CELL_PADDING_X = 12;

function getChartInnerWidth(columnWidth) {
  return Math.max(columnWidth - CELL_PADDING_X * 2, 80);
}

function getMeanLineLeft(columnWidth, meanPercent) {
  const target = clampPercent(meanPercent);
  const chartWidth = getChartInnerWidth(columnWidth);
  return CELL_PADDING_X + (chartWidth * target) / 100;
}

function resolveMeanPercent(column, meanRow) {
  const raw = meanRow?.[column.key];
  if (raw && typeof raw === 'object' && raw.value != null) {
    return clampPercent(raw.value);
  }
  return clampPercent(column.meanPercent);
}

const METRIC_COLUMNS = [
  { key: 'entrySessions', title: '入口会话量', width: 168, meanPercent: 62 },
  { key: 'validSessions', title: '有效会话量', width: 168, meanPercent: 54 },
  { key: 'diagnoseSessions', title: '诊断与服务会话量', width: 188, meanPercent: 61 },
  { key: 'transferRate', title: '转人工率', width: 168, meanPercent: 57 },
];

const DEFAULT_ROWS = [
  {
    id: 'douyin-community',
    level: '抖音社区',
    showCaret: false,
    expanded: true,
    actionLabel: '服务记录',
    entrySessions: { text: '23.2万', value: 72 },
    validSessions: { text: '23.2万', value: 71 },
    diagnoseSessions: { text: '23.2万', value: 69 },
    transferRate: { text: '23.2%', value: 70 },
  },
  {
    id: 'im',
    level: 'IM',
    actionLabel: '服务记录',
    entrySessions: { text: '23.2万', value: 70 },
    validSessions: { text: '23.2万', value: 69 },
    diagnoseSessions: { text: '23.2万', value: 68 },
    transferRate: { text: '23.2%', value: 69 },
  },
  {
    id: 'hotline',
    level: '热线',
    actionLabel: '服务记录',
    entrySessions: { text: '23.2万', value: 78 },
    validSessions: { text: '16.8%', value: 40 },
    diagnoseSessions: { text: '23.2万', value: 76 },
    transferRate: { text: '18.9%', value: 44 },
  },
  {
    id: 'faq',
    level: 'FAQ',
    actionLabel: '服务记录',
    entrySessions: { text: '23.2万', value: 26 },
    validSessions: { text: '23.2万', value: 34 },
    diagnoseSessions: { text: '23.2万', value: 31 },
    transferRate: { text: '18.9%', value: 43 },
  },
];

const DEFAULT_MEAN_ROW = {
  label: '均值',
  entrySessions: { text: '23.4万', value: 62 },
  // 百分比列：均值线位置与底部橙色文案保持一致，避免出现“文案在 22.x%，均值线却在中右部”的错位感。
  validSessions: { text: '22.8%', value: 22.8 },
  diagnoseSessions: { text: '22.3%', value: 22.3 },
  transferRate: { text: '24.8%', value: 24.8 },
};

function clampPercent(input) {
  const n = Number(input);
  if (!Number.isFinite(n)) return 0;
  return Math.max(0, Math.min(100, n));
}

function BulletCell({ metric, metricLabel, meanPercent, columnWidth }) {
  const displayText = metric?.text ?? '-';
  const value = clampPercent(metric?.value);
  const meanLine = clampPercent(meanPercent);
  const hasMeasure = displayText !== '-' && value > 0;
  const tooltipText = `${metricLabel}\n当前值：${displayText}\n均值线：${meanLine}%`;
  const chartWidth = getChartInnerWidth(columnWidth);
  const numberFont = 'var(--font-number, Inter, ui-sans-serif, system-ui, sans-serif)';

  if (!hasMeasure) {
    return (
      <span className="text-sm font-semibold leading-5" style={{ color: BODY_TEXT_COLOR, fontFamily: numberFont }}>
        {displayText}
      </span>
    );
  }

  const measureWidth = Math.max(value, 12);

  return (
    <Tooltip content={tooltipText} placement="top" triggerClassName="inline-flex max-w-full">
      <div
        className="relative flex shrink-0 items-center"
        style={{ width: chartWidth, height: BULLET_BAR_HEIGHT }}
      >
        <div
          className="relative box-border flex h-full w-max max-w-full items-center"
          style={{
            width: `${measureWidth}%`,
            minWidth: 'fit-content',
            backgroundColor: BULLET_BLOCK_FILL,
            borderRight: `${BULLET_EDGE_WIDTH}px solid ${BULLET_BLOCK_EDGE}`,
          }}
        >
          <span
            className="pointer-events-none whitespace-nowrap px-1.5 text-sm font-semibold leading-5"
            style={{
              color: BODY_TEXT_COLOR,
              fontFamily: numberFont,
            }}
          >
            {displayText}
          </span>
        </div>
      </div>
    </Tooltip>
  );
}

function ColumnMeanLines({ meanRow }) {
  return (
    <div
      className="pointer-events-none absolute inset-x-0 bottom-0 grid"
      style={{
        gridTemplateColumns: GRID_TEMPLATE_COLUMNS,
        top: TABLE_HEADER_HEIGHT,
      }}
      aria-hidden="true"
    >
      <div />
      {METRIC_COLUMNS.map((column) => {
        const meanPercent = resolveMeanPercent(column, meanRow);
        return (
        <div key={column.key} className="relative">
          <div
            className="absolute top-0 bottom-0"
            style={{
              left: getMeanLineLeft(column.width, meanPercent),
              borderLeft: `1px dashed ${BULLET_TARGET}`,
            }}
          />
        </div>
        );
      })}
      <div />
    </div>
  );
}

function ChannelCell({ level }) {
  return (
    <div className="bullet-chart-table__channel flex w-full min-w-0 items-center text-sm leading-5" style={{ color: BODY_TEXT_COLOR }}>
      <span className="truncate font-semibold">{level}</span>
    </div>
  );
}

function buildColumns(meanRow) {
  const columns = [
    {
      title: '渠道',
      key: 'level',
      dataIndex: 'level',
      width: 112,
      type: 'text',
      cellSize: 'default',
      render: (_value, record) => <ChannelCell level={record.level} />,
    },
    ...METRIC_COLUMNS.map((metricColumn) => ({
      title: metricColumn.title,
      key: metricColumn.key,
      dataIndex: metricColumn.key,
      width: metricColumn.width,
      type: 'text',
      cellSize: 'default',
      render: (value) => (
        <BulletCell
          metric={value}
          metricLabel={metricColumn.title}
          meanPercent={resolveMeanPercent(metricColumn, meanRow)}
          columnWidth={metricColumn.width}
        />
      ),
    })),
    {
      title: '操作',
      key: 'actions',
      dataIndex: 'actionLabel',
      width: 104,
      type: 'link',
      cellSize: 'default',
    },
  ];
  return columns;
}

function MeanRow({ meanRow }) {
  return (
    <div
      className="grid w-full items-center border-b bg-white"
      style={{
        gridTemplateColumns: GRID_TEMPLATE_COLUMNS,
        borderColor: TABLE_BORDER_COLOR,
      }}
    >
      <span
        className="px-3 py-1 text-left text-sm font-semibold leading-5"
        style={{ color: MEAN_DATA_COLOR }}
      >
        {meanRow.label || '均值'}
      </span>
      {METRIC_COLUMNS.map((column) => {
        const meanPercent = resolveMeanPercent(column, meanRow);
        const raw = meanRow[column.key];
        const label = typeof raw === 'object' ? raw.text : raw;
        return (
          <div key={column.key} className="relative px-3 py-1">
            <span
              className="absolute top-1/2 -translate-x-1/2 -translate-y-1/2 whitespace-nowrap text-xs font-semibold leading-4"
              style={{
                left: getMeanLineLeft(column.width, meanPercent),
                color: MEAN_DATA_COLOR,
                fontFamily: 'var(--font-number, Inter, ui-sans-serif, system-ui, sans-serif)',
              }}
            >
              {label || ''}
            </span>
          </div>
        );
      })}
      <span className="px-3 py-1" />
    </div>
  );
}

/**
 * Dashboard 业务组件：子弹图 Table
 *
 * Props:
 *   rows — 表格行数据
 *   meanRow — 底部均值行
 */
export default function BulletChartTablePreview({
  variant = 'default',
  rows = DEFAULT_ROWS,
  meanRow = DEFAULT_MEAN_ROW,
}) {
  void variant;
  const columns = buildColumns(meanRow);

  // 顶部筛选区由本组件自管控（外置于均值线容器，避免橙色虚线越界穿过筛选条）；
  // 默认 3 个筛选器，避免在常规宽度下换行。
  const filterItems = [
    { id: 'channel', label: '渠道', options: ['全部', '抖音社区', 'IM', '热线', 'FAQ'] },
    { id: 'entrySessions', label: '入口会话量', options: ['全部', '> 20万', '10-20万', '< 10万'] },
    { id: 'validSessions', label: '有效会话量', options: ['全部', '> 20万', '10-20万', '< 10万'] },
  ];

  return (
    <section className="bullet-chart-table relative w-full overflow-hidden bg-white">
      <div className="flex shrink-0 flex-wrap items-center gap-2 pb-3" data-tfds-component="BulletChartTable.SearchFilterBar">
        <Input
          placeholder="搜索表格内容"
          allowClear
          prefix={<Icon name="search-md-stroked" size="sm" aria-hidden="true" />}
          style={{ '--size-input-width': 'min(240px,100%)' }}
        />
        {filterItems.map((item) => (
          <Filter
            key={item.id}
            label={item.label}
            options={item.options}
          />
        ))}
      </div>
      <div className="relative">
        <div
          className={[
            '[&_[role=gridcell]]:border-b',
            '[&_[role=gridcell]]:border-border-default',
            '[&_[role=gridcell]]:border-l-0',
            '[&_[role=gridcell]]:border-r-0',
            '[&_[role=gridcell]]:border-t-0',
            '[&_[role=gridcell]]:bg-white',
            '[&_[role=gridcell]]:text-left',
            '[&_[role=gridcell]]:text-sm',
            '[&_[role=gridcell]]:leading-5',
            '[&_[role=gridcell]]:min-h-[48px]',
            '[&_[role=gridcell]]:overflow-visible',
            '[&_[role=row]>[role=gridcell]:first-child]:font-semibold',
          ].join(' ')}
        >
          <Table
            columns={columns}
            dataSource={rows}
            rowKey="id"
            showSearchFilters={false}
            className="[&_.table__body]:overflow-y-visible"
          />
        </div>
        <ColumnMeanLines meanRow={meanRow} />
      </div>
      <MeanRow meanRow={meanRow} />
    </section>
  );
}
