import { useMemo, useState } from 'react';
import SmartComposedChart from '../../charts/SmartComposedChart';
import MetricLegendTablePreview from './MetricLegendTablePreview';

const DATE_LABELS = ['06.01', '06.02', '06.03', '06.04', '06.05', '06.06', '06.07', '06.08', '06.09'];

const CHART_DATA = [
  { name: DATE_LABELS[0], positive: 34, neutral: 14, negative: 7, engagement: 82 },
  { name: DATE_LABELS[1], positive: 41, neutral: 17, negative: 9, engagement: 72 },
  { name: DATE_LABELS[2], positive: 28, neutral: 11, negative: 4, engagement: 69 },
  { name: DATE_LABELS[3], positive: 16, neutral: 15, negative: 30, engagement: 98 },
  { name: DATE_LABELS[4], positive: 22, neutral: 8, negative: 7, engagement: 61 },
  { name: DATE_LABELS[5], positive: 50, neutral: 13, negative: 3, engagement: 108 },
  { name: DATE_LABELS[6], positive: 39, neutral: 15, negative: 10, engagement: 76 },
  { name: DATE_LABELS[7], positive: 35, neutral: 13, negative: 7, engagement: 83 },
  { name: DATE_LABELS[8], positive: 29, neutral: 8, negative: 4, engagement: 65 },
];

const METRIC_ROWS = [
  { id: 'account', name: '账号', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
  { id: 'basic', name: '基础产品', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: 10.11 },
  { id: 'creation', name: '创作与投稿', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
  { id: 'social', name: '社交', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
  { id: 'incentive', name: '激励', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
  { id: 'ad', name: '推荐与广告', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
  { id: 'promote', name: '推荐与广告', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
  { id: 'content', name: '内容分发', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
  { id: 'growth', name: '成长变现', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
  { id: 'market', name: '营销与推广', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
  { id: 'rights', name: '权益保护', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12 },
];

const METRIC_CURVE_PROFILE = {
  account: {
    engagementScale: 1, positiveScale: 1, neutralScale: 1, negativeScale: 1, shift: 0,
    engagementOffsets: [0, 0, 0, 0, 0, 0, 0, 0, 0],
  },
  basic: {
    engagementScale: 0.93, positiveScale: 1.08, neutralScale: 0.98, negativeScale: 0.92, shift: 1,
    engagementOffsets: [2, -6, 8, -4, 5, -7, 4, -3, 6],
  },
  creation: {
    engagementScale: 1.06, positiveScale: 0.94, neutralScale: 1.1, negativeScale: 1.05, shift: -1,
    engagementOffsets: [-4, 5, -7, 10, -2, 6, -5, 7, -3],
  },
  social: {
    engagementScale: 0.88, positiveScale: 1.04, neutralScale: 0.92, negativeScale: 1.18, shift: 2,
    engagementOffsets: [6, -10, 4, -8, 9, -5, 7, -9, 3],
  },
  incentive: {
    engagementScale: 0.97, positiveScale: 1.15, neutralScale: 0.86, negativeScale: 0.95, shift: 0,
    engagementOffsets: [-3, 4, -2, 8, -6, 7, -4, 5, -1],
  },
  ad: {
    engagementScale: 1.1, positiveScale: 1.02, neutralScale: 1.03, negativeScale: 1.12, shift: -2,
    engagementOffsets: [8, -4, 10, -6, 2, -5, 9, -7, 3],
  },
  promote: {
    engagementScale: 1.03, positiveScale: 0.96, neutralScale: 1.08, negativeScale: 1.04, shift: 1,
    engagementOffsets: [1, 7, -5, 6, -8, 4, -2, 9, -6],
  },
  content: {
    engagementScale: 0.91, positiveScale: 1.11, neutralScale: 0.95, negativeScale: 0.9, shift: -1,
    engagementOffsets: [-6, 3, -4, 7, -9, 5, -3, 6, -2],
  },
  growth: {
    engagementScale: 1.08, positiveScale: 1.07, neutralScale: 0.89, negativeScale: 0.97, shift: 2,
    engagementOffsets: [5, -3, 7, -2, 10, -6, 4, -5, 8],
  },
  market: {
    engagementScale: 0.95, positiveScale: 0.92, neutralScale: 1.14, negativeScale: 1.08, shift: 0,
    engagementOffsets: [3, -5, 6, -4, 8, -7, 5, -2, 4],
  },
  rights: {
    engagementScale: 0.9, positiveScale: 0.88, neutralScale: 1.05, negativeScale: 1.2, shift: -2,
    engagementOffsets: [-5, 8, -6, 4, -7, 9, -4, 6, -3],
  },
};
const NUMBER_FONT_STACK = 'var(--font-number, Inter, ui-sans-serif, system-ui, sans-serif)';
// 固定为对应色，避免不同页面 token root 解析差异导致偏色（图例与图表必须完全一致）。
const POSITIVE_EMOTION_COLOR = '#5DE4DD';
const NEUTRAL_EMOTION_COLOR = '#E4E7EC';
const NEGATIVE_EMOTION_COLOR = '#FC7E90';
const ENGAGEMENT_COLOR = '#24CDA5';

function HeaderLegend() {
  return (
    <div className="inline-flex w-max items-center gap-1.5 whitespace-nowrap text-xs font-normal leading-4 text-blueGrey-600">
      <span className="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap">
        <span className="inline-block h-2 w-2 rounded-full" style={{ background: ENGAGEMENT_COLOR }} />
        互动量
      </span>
      <span className="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap">
        <span className="relative inline-block h-3 w-3 overflow-hidden rounded-[2px]">
          <span className="absolute inset-x-0 bottom-0 h-1" style={{ background: POSITIVE_EMOTION_COLOR }} />
          <span className="absolute inset-x-0 top-1 h-1" style={{ background: NEUTRAL_EMOTION_COLOR }} />
          <span className="absolute inset-x-0 top-0 h-1" style={{ background: NEGATIVE_EMOTION_COLOR }} />
        </span>
        发文量
      </span>
      <span className="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap">
        <span className="inline-block h-2 w-2 rounded-full" style={{ background: POSITIVE_EMOTION_COLOR }} />
        正向情绪
      </span>
      <span className="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap">
        <span className="inline-block h-2 w-2 rounded-full" style={{ background: NEUTRAL_EMOTION_COLOR }} />
        中立情绪
      </span>
      <span className="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap">
        <span className="inline-block h-2 w-2 rounded-full" style={{ background: NEGATIVE_EMOTION_COLOR }} />
        负向情绪
      </span>
    </div>
  );
}

/**
 * Dashboard 业务组件：多指标 + 图表（堆叠柱状 + 折线 + 指标联动表）
 *
 * Props:
 *   title — 卡片标题
 *   periodText — 周期说明
 *   totalPosts — 总发文量
 *   avgPosts — 日均发文量
 *   metrics — 右侧指标列表
 */
export default function MultiMetricChartPreview({
  title = '作品及发文',
  periodText = '统计周期：2024-01-02 ~ 2024-01-08',
  totalPosts = '2.36亿',
  metrics = METRIC_ROWS,
  tablePanelWidth = 320,
  tableGridColsClass,
  fillHeight = false,
}) {
  const [selectedMetricId, setSelectedMetricId] = useState(metrics[0]?.id || '');
  const chartData = useMemo(() => {
    const profile = METRIC_CURVE_PROFILE[selectedMetricId] || METRIC_CURVE_PROFILE.account;
    return CHART_DATA.map((item, idx) => {
      const wave = ((idx % 3) - 1) * 2;
      const engagementOffset = profile.engagementOffsets?.[idx] || 0;
      return {
        ...item,
        positive: Math.max(4, Math.round(item.positive * profile.positiveScale + wave + profile.shift)),
        neutral: Math.max(3, Math.round(item.neutral * profile.neutralScale + wave * 0.5)),
        negative: Math.max(2, Math.round(item.negative * profile.negativeScale - wave * 0.4 - profile.shift * 0.3)),
        // Per-point offsets reshape curve peaks/valleys per primary category.
        engagement: Math.max(
          30,
          Math.round(item.engagement * profile.engagementScale + wave * 4 + profile.shift * 3 + engagementOffset),
        ),
      };
    });
  }, [selectedMetricId]);
  const chartSpec = useMemo(
    () => ({
      data: chartData,
      series: [
        { type: 'bar', dataKey: 'positive', name: '正向情绪', colorToken: POSITIVE_EMOTION_COLOR, stackId: 'emotion' },
        { type: 'bar', dataKey: 'neutral', name: '中立情绪', colorToken: NEUTRAL_EMOTION_COLOR, stackId: 'emotion' },
        { type: 'bar', dataKey: 'negative', name: '负向情绪', colorToken: NEGATIVE_EMOTION_COLOR, stackId: 'emotion' },
        { type: 'line', dataKey: 'engagement', name: '互动量', colorToken: ENGAGEMENT_COLOR },
      ],
      config: {
        showLegend: false,
        showXAxis: true,
        showYAxis: true,
        height: 308,
        margin: { top: 24, right: 24, bottom: 0, left: 0 },
        tightMargin: true,
        yAxisWidth: 28,
        bar: { stack: true, cornerMode: 'rounded' },
        line: { showGrid: true, showDots: false, curveType: 'linear', yAxisTickCount: 7 },
      },
    }),
    [chartData],
  );
  // 自适应规则（卡片内边距固定为 上16 / 下左右20，内容不允许超出）：
  // - 双列布局：表格按自身最大宽度占位（不超出 tablePanelWidth），图表占用剩余空间
  // - 图表与表格中间距：默认 8px（小屏），≥1024px 起 12px
  // - 容器极窄时降级为单列，仍不会溢出
  const tableMaxWidth = tablePanelWidth >= 340 ? 340 : 320;
  const tableContainerClass = '';

  return (
    <section className={`w-full min-w-0 rounded-xl bg-white px-5 pb-5 pt-4 ${fillHeight ? 'h-full' : ''}`}>
      {/* 标题/图例 行 */}
      <header className="mb-2 flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-1">
        <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
          <h3
            className="text-lg font-semibold leading-6 text-blueGrey-900"
            style={{ fontWeight: 'var(--font-weight-semibold, 600)' }}
          >
            {title}
          </h3>
          <span className="text-xs leading-4 text-blueGrey-500">{periodText}</span>
          <div className="dashboard-scrollbar-hide min-w-0 overflow-x-auto">
            <HeaderLegend />
          </div>
        </div>
        <span className="shrink-0 whitespace-nowrap text-right text-sm leading-5 text-blueGrey-600">
          总发文量：
          <strong
            className="text-base font-semibold text-blueGrey-800"
            style={{ fontFamily: NUMBER_FONT_STACK }}
          >
            {totalPosts}
          </strong>
        </span>
      </header>

      {/* 图表 + 指标表：
           - 双列时图表 flex-1 撑满左侧剩余空间，表格按自身最大宽度占位
           - 中间间距：默认 8px（小屏），≥1024px 起 12px */}
      <div
        className={`flex min-w-0 flex-col gap-2 sm:flex-row lg:gap-3 ${fillHeight ? 'h-full' : ''}`}
      >
        {/* 图表区：吃掉所有剩余水平空间 */}
        <div className="min-w-0 w-full flex-1">
          <SmartComposedChart spec={chartSpec} />
        </div>

        {/* 指标表：固定最大宽度（tablePanelWidth），不抢图表的空间 */}
        <aside
          className="min-w-0 w-full sm:w-auto sm:shrink-0"
          style={{ maxWidth: tableMaxWidth }}
        >
          <div className="w-full">
            <MetricLegendTablePreview
              variant="without-legend"
              rows={metrics}
              selectedId={selectedMetricId}
              onSelect={setSelectedMetricId}
              gridColsClass={tableGridColsClass}
              containerClassName={tableContainerClass}
            />
          </div>
        </aside>
      </div>
    </section>
  );
}
