import { useMemo, useState } from 'react';
import { Tabs as Tabs } from '../b-end.js';
import AreaChartPreview from './AreaChartPreview';
import LineChartPreview from './LineChartPreview';
import MetricLegendTablePreview from './MetricLegendTablePreview';

const DEFAULT_TAB_ITEMS = [
  { label: '行业' },
  { label: '一级问题' },
];

const DEFAULT_CPO_STATS = [
  { label: '近7天', value: '2,987' },
  { label: '近30天', value: '13,093' },
  { label: '近3个月', value: '13,621' },
];

const DEFAULT_CHART_DATA = [
  { name: '10-10', overall: 135, catering: 148, hotel: 137, mixed: 122, trendy: 108, none: 114 },
  { name: '10-12', overall: 102, catering: 118, hotel: 110, mixed: 96, trendy: 82, none: 83 },
  { name: '10-14', overall: 141, catering: 156, hotel: 144, mixed: 130, trendy: 116, none: 118 },
  { name: '10-16', overall: 126, catering: 142, hotel: 136, mixed: 121, trendy: 104, none: 109 },
  { name: '10-18', overall: 132, catering: 150, hotel: 141, mixed: 127, trendy: 113, none: 115 },
  { name: '10-20', overall: 120, catering: 138, hotel: 130, mixed: 116, trendy: 99, none: 103 },
  { name: '10-22', overall: 146, catering: 161, hotel: 152, mixed: 139, trendy: 121, none: 126 },
  { name: '10-24', overall: 154, catering: 170, hotel: 160, mixed: 147, trendy: 127, none: 131 },
  { name: '10-26', overall: 126, catering: 141, hotel: 132, mixed: 119, trendy: 102, none: 106 },
  { name: '10-28', overall: 149, catering: 165, hotel: 156, mixed: 143, trendy: 124, none: 129 },
  { name: '10-30', overall: 130, catering: 146, hotel: 138, mixed: 123, trendy: 107, none: 111 },
  { name: '11-01', overall: 136, catering: 153, hotel: 144, mixed: 129, trendy: 114, none: 118 },
  { name: '11-03', overall: 118, catering: 135, hotel: 128, mixed: 113, trendy: 95, none: 101 },
  { name: '11-05', overall: 143, catering: 159, hotel: 150, mixed: 136, trendy: 119, none: 124 },
];

const DEFAULT_LEGEND_ROWS = [
  { id: 'overall', name: '大交通', posts: '7,322', postsRatio: 12.11, interactions: '7,322', interactionsRatio: 12.11, color: '#55C5FD' },
  { id: 'catering', name: '餐饮', posts: '7,322', postsRatio: 12.11, interactions: '7,322', interactionsRatio: 12.11, color: '#2FC6AA' },
  { id: 'hotel', name: '酒旅行业', posts: '13,358', postsRatio: 10.11, interactions: '13,358', interactionsRatio: 10.11, color: '#FADC6D' },
  { id: 'mixed', name: '综合行业', posts: '12,335', postsRatio: -10.11, interactions: '12,335', interactionsRatio: -10.11, color: '#DDBEF6' },
  { id: 'trendy', name: '潮玩', posts: '8,924', postsRatio: 6.21, interactions: '8,924', interactionsRatio: 6.21, color: '#FC7E90' },
  { id: 'none', name: '无行业', posts: '7,322', postsRatio: 12.11, interactions: '7,322', interactionsRatio: 12.11, color: '#A871E3' },
];

const STACKED_SERIES = [
  { key: 'overall', label: '大交通', colorToken: 'data-1' },
  { key: 'catering', label: '餐饮', colorToken: 'data-0' },
  { key: 'hotel', label: '酒旅行业', colorToken: 'data-5' },
  { key: 'mixed', label: '综合行业', colorToken: 'data-8' },
  { key: 'trendy', label: '潮玩', colorToken: 'data-9' },
  { key: 'none', label: '无行业', colorToken: 'data-7' },
];

const TOKEN_COLOR_MAP = {
  'data-0': 'var(--color-data-0)',
  'data-1': 'var(--color-data-1)',
  'data-5': 'var(--color-data-5)',
  'data-7': 'var(--color-data-7)',
  'data-8': 'var(--color-data-8)',
  'data-9': 'var(--color-data-9)',
};

const NUMBER_FONT_STACK = 'var(--font-number, Inter, ui-sans-serif, system-ui, sans-serif)';

export default function VoiceFeedbackTrendSection({
  tabItems = DEFAULT_TAB_ITEMS,
  cpoStats = DEFAULT_CPO_STATS,
  chartData = DEFAULT_CHART_DATA,
  legendRows = DEFAULT_LEGEND_ROWS,
  embedded = false,
}) {
  const [activeTab, setActiveTab] = useState(0);
  const [activePrimaryId, setActivePrimaryId] = useState('');
  const legendRowsResolved = useMemo(() => {
    const seriesColorByKey = new Map(STACKED_SERIES.map((item) => [item.key, TOKEN_COLOR_MAP[item.colorToken]]));
    return (Array.isArray(legendRows) ? legendRows : []).map((row) => ({
      ...row,
      color: seriesColorByKey.get(row.id) || row.color,
    }));
  }, [legendRows]);
  const legendItems = useMemo(
    () => STACKED_SERIES.map((item) => ({ key: item.key, label: item.label, colorToken: item.colorToken })),
    [],
  );
  const focusedLegendItems = useMemo(
    () => legendItems.filter((item) => item.key === activePrimaryId),
    [legendItems, activePrimaryId],
  );
  const showFocusedLineChart = focusedLegendItems.length === 1;

  return (
    <section className={embedded ? 'overflow-hidden py-1' : 'overflow-hidden rounded-lg border border-border-default bg-surface p-4'}>
      <div className="grid min-w-0 grid-cols-1 gap-3 overflow-hidden min-[1200px]:grid-cols-[minmax(0,1fr)_374px]">
        <div className="min-w-0 overflow-hidden">
          <div className="mb-3 inline-flex min-w-0 flex-wrap items-center gap-3 overflow-hidden">
            <span className="truncate text-xs font-semibold text-foreground">CPO日均</span>
            {cpoStats.map((item) => (
              <span key={item.label} className="inline-flex min-w-0 items-center gap-2 overflow-hidden">
                <span className="truncate text-xs text-foreground-muted">{item.label}</span>
                <span className="truncate text-lg font-semibold leading-6 text-foreground" style={{ fontFamily: NUMBER_FONT_STACK }}>{item.value}</span>
              </span>
            ))}
          </div>
          {showFocusedLineChart ? (
            <LineChartPreview
              data={chartData}
              legendItems={focusedLegendItems}
              showLegend={false}
              showXAxis
              showYAxis
              showGrid
              showDots={false}
              curve="linear"
              height={210}
              margin={{ top: 20, right: 0, left: 0, bottom: 10 }}
              yAxisWidth={36}
            />
          ) : (
            <AreaChartPreview
              data={chartData}
              legendItems={legendItems}
              stack
              showLegend={false}
              showXAxis
              showYAxis
              showGrid
              curve="linear"
              height={210}
              margin={{ top: 20, right: 0, left: 0, bottom: 10 }}
              yAxisWidth={36}
            />
          )}
        </div>
        <aside className="flex w-full min-w-0 flex-col overflow-hidden min-[1200px]:w-[374px] min-[1200px]:min-w-[374px] min-[1200px]:shrink-0">
          <div className="mb-3 flex w-full justify-end">
            <Tabs className="shrink-0" variant="segment" size="sm" items={tabItems} activeIndex={activeTab} onChange={setActiveTab} />
          </div>
          <MetricLegendTablePreview
            variant="with-legend"
            rows={legendRowsResolved}
            selectedId={activePrimaryId}
            onSelect={(rowId) => setActivePrimaryId((prev) => (prev === rowId ? '' : rowId))}
            containerClassName="w-full max-w-full"
          />
        </aside>
      </div>
    </section>
  );
}
