import { useMemo } from 'react';
import { resolveColorToken, tokenNameToCssVar } from '../utils/token-resolver.js';
import {
  resolveChartCategoryBaselineStroke,
  getChartFilledLegendTextStyleProps,
  getChartFilledLegendRechartsProps,
} from './chart-common';

const FALLBACK_TEXT = '#475467';
const FALLBACK_AXIS_TEXT = '#667085';
const FALLBACK_BORDER = '#E5E6EB';
const FALLBACK_HOVER = '#F9FAFB';

export const CHART_TOOLTIP_PANEL_PROPS = {
  wrapperStyle: { outline: 'none' },
  contentStyle: {
    background: 'transparent',
    border: 'none',
    boxShadow: 'none',
    padding: 0,
  },
};

/** 统一图表 Tooltip：外层透明，内层 `.chart-tooltip` 与 Recharts 一致 */
export const CHART_G2_TOOLTIP_CSS = {
  '.g2-tooltip': {
    background: 'transparent',
    boxShadow: 'none',
    border: 'none',
    padding: '0',
  },
};

export function escapeChartTooltipHtml(raw) {
  return String(raw ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

export function formatChartTooltipValue(value) {
  const n = Number(value);
  if (Number.isFinite(n)) return n.toLocaleString('en-US');
  if (value == null || value === '') return '—';
  return String(value);
}

/**
 * 生成与 ChartTooltip variant="chart" 相同 DOM 结构的 HTML（供 G2 interaction.tooltip.render 使用）。
 * @param {{ title?: string, rows?: Array<{ label: string, value: unknown, color?: string }> }} payload
 */
export function buildSmartChartTooltipHtml({ title, rows = [] }) {
  const titleSafe = title ? escapeChartTooltipHtml(title) : '';
  const rowHtml = rows
    .map((row) => {
      const label = escapeChartTooltipHtml(row.label);
      const value = escapeChartTooltipHtml(formatChartTooltipValue(row.value));
      const color = escapeChartTooltipHtml(row.color || '');
      return [
        '<div class="chart-tooltip__row">',
        '  <div class="chart-tooltip__left">',
        color
          ? `    <span class="chart-tooltip__dot" style="background-color:${color}"></span>`
          : '    <span class="chart-tooltip__dot"></span>',
        `    <span class="chart-tooltip__name">${label}</span>`,
        '  </div>',
        `  <span class="chart-tooltip__value">${value}</span>`,
        '</div>',
      ].join('');
    })
    .join('');

  return [
    '<div class="chart-tooltip chart-tooltip--chart">',
    titleSafe ? `<div class="chart-tooltip__label">${titleSafe}</div>` : '',
    `<div class="chart-tooltip__rows">${rowHtml}</div>`,
    '</div>',
  ].join('');
}

export function useChartChrome(resolveOpts) {
  return useMemo(() => {
    const textSecondary = resolveColorToken('text-secondary', resolveOpts) ?? FALLBACK_TEXT;
    const axisText = resolveColorToken('text-tertiary', resolveOpts) ?? FALLBACK_AXIS_TEXT;
    const borderDivider = resolveColorToken('border-divider', resolveOpts) ?? FALLBACK_BORDER;
    const gridVarName = tokenNameToCssVar('border-chart-grid');
    const gridStroke = gridVarName?.startsWith('--')
      ? `var(${gridVarName}, #E4E7EC)`
      : (resolveColorToken('border-chart-grid', resolveOpts) ?? borderDivider);
    const baselineStroke = resolveChartCategoryBaselineStroke(resolveOpts);
    const hoverFill =
      resolveColorToken('bg-page', resolveOpts) ??
      resolveColorToken('fill-default', resolveOpts) ??
      FALLBACK_HOVER;
    const borderVarName = tokenNameToCssVar('border-divider');
    const cursorStroke = borderVarName?.startsWith('--')
      ? `var(${borderVarName})`
      : borderDivider;
    return {
      textSecondary,
      axisText,
      borderDivider,
      gridStroke,
      baselineStroke,
      hoverFill,
      tooltipCursorLine: { stroke: cursorStroke, strokeWidth: 1, strokeDasharray: '3 3' },
      tooltipCursorFill: { fill: hoverFill },
      legendTextProps: getChartFilledLegendTextStyleProps(textSecondary),
      legendRechartsProps: getChartFilledLegendRechartsProps(textSecondary),
    };
  }, [resolveOpts]);
}

export function buildChartChromeGuide(tokenMap) {
  const sections = [
    {
      title: '统一外壳',
      lines: [
        '坐标轴、网格线、Tooltip 与 Hover 区统一走 `useChartChrome()`；图表仅负责数据与几何。',
        '禁止在图表组件内硬编码 Hex/RGBA，统一使用 Token 解析（`border-chart-grid` / `border-divider` / `bg-page`）。',
      ],
    },
    {
      title: '接入规范',
      lines: [
        '网格线：`<CartesianGrid stroke={gridStroke} />`',
        '轴线与刻度：`axisLine={baselineStroke}` + `tick={textSecondary}`',
        'Tooltip：复用 `ChartTooltip variant="chart"` + `CHART_TOOLTIP_PANEL_PROPS`',
        'Cursor：折线/面积/散点用 `tooltipCursorLine`；柱图类可用 `tooltipCursorFill`。',
      ],
    },
  ];

  if (tokenMap && typeof tokenMap === 'object') {
    const tokenRows = Object.entries(tokenMap)
      .flatMap(([, rows]) => (Array.isArray(rows) ? rows : []))
      .filter((row) => row && row.token)
      .map((row) => `- ${row.label || row.token}：\`${row.token}\``);
    if (tokenRows.length) {
      sections.push({
        title: '当前组件使用的外壳 Token',
        lines: tokenRows,
      });
    }
  }

  return sections
    .map((sec, idx) => `${idx + 1}. ${sec.title}\n${sec.lines.map((l) => `   ${l}`).join('\n')}`)
    .join('\n\n');
}
