import { useEffect, useMemo, useRef, useState } from 'react';
import SmartLineChart from '../../charts/SmartLineChart';
import { CHART_SERIES_LINE_STROKE_WIDTH } from '../../charts/chart-line-primitives';
import { tokenNameToCssVar } from '../../utils/token-resolver.js';

const TIME_LABELS = ['18:10', '18:30', '18:50', '19:10', '20:30', '20:55', '21:10', '21:30', '21:50', '22:10'];

const TOPIC_ROWS = [
  { id: 'all', code: '全部议题', title: '', value: 837 },
  { id: 't1', code: '议题 01', title: '电子签高利贷：砍头息与“数字人放贷”', value: 76 },
  { id: 't2', code: '议题 02', title: '信息黑洞：爬虫技术窃取隐私', value: 128 },
  { id: 't3', code: '议题 03', title: '手机抽奖陷阱：日流水20亿元的“沉默收割”', value: 98 },
  { id: 't4', code: '议题 04', title: '“保水虾仁”增重骗局：1斤虾仁7两冰', value: 12 },
  { id: 't5', code: '议题 05', title: '非标电线电缆：火灾隐患的“隐形杀手”', value: 19 },
  { id: 't6', code: '议题 06', title: 'AI客服转人工难问题', value: 68 },
  { id: 't7', code: '议题 07', title: '待开启', value: '-' },
];

const CHART_SERIES = [
  { dataKey: 'all', name: '全部', colorToken: 'data-18', strokeDasharray: '4 3' },
  { dataKey: 't1', name: '议题 1', colorToken: 'data-9' },
  { dataKey: 't2', name: '议题 2', colorToken: 'data-2' },
  { dataKey: 't3', name: '议题 3', colorToken: 'data-1' },
  { dataKey: 't4', name: '议题 4', colorToken: 'data-4' },
  { dataKey: 't5', name: '议题 5', colorToken: 'data-8' },
  { dataKey: 't6', name: '议题 6', colorToken: 'data-0' },
  { dataKey: 't7', name: '议题 7', colorToken: 'data-10' },
];

const CHART_DATA = [
  { name: TIME_LABELS[0], all: 220, t1: 90, t2: 84, t3: 88, t4: 56, t5: 42, t6: 36, t7: 28 },
  { name: TIME_LABELS[1], all: 196, t1: 114, t2: 92, t3: 85, t4: 60, t5: 40, t6: 34, t7: 24 },
  { name: TIME_LABELS[2], all: 194, t1: 101, t2: 106, t3: 95, t4: 58, t5: 38, t6: 33, t7: 26 },
  { name: TIME_LABELS[3], all: 180, t1: 92, t2: 112, t3: 88, t4: 54, t5: 35, t6: 29, t7: 22 },
  { name: TIME_LABELS[4], all: 192, t1: 84, t2: 106, t3: 82, t4: 61, t5: 33, t6: 27, t7: 21 },
  { name: TIME_LABELS[5], all: 199, t1: 108, t2: 102, t3: 90, t4: 56, t5: 41, t6: 30, t7: 20 },
  { name: TIME_LABELS[6], all: 195, t1: 98, t2: 101, t3: 93, t4: 66, t5: 39, t6: 35, t7: 24 },
  { name: TIME_LABELS[7], all: 170, t1: 85, t2: 120, t3: 78, t4: 61, t5: 37, t6: 31, t7: 23 },
  { name: TIME_LABELS[8], all: 178, t1: 94, t2: 128, t3: 86, t4: 57, t5: 35, t6: 30, t7: 21 },
  { name: TIME_LABELS[9], all: 168, t1: 90, t2: 112, t3: 95, t4: 58, t5: 38, t6: 34, t7: 25 },
];

const CHART_TOP_PADDING_PX = 24;
const CHART_RIGHT_PADDING_PX = 0;
const CHART_LEFT_PADDING_PX = 0;
const LEGEND_CHART_GAP_PX = 4;
const LEFT_PANEL_RADIUS_PX = 16;
const LEFT_PANEL_PADDING_TOP_PX = 12;
const LEFT_PANEL_PADDING_SIDE_PX = 10;
const LEFT_PANEL_PADDING_BOTTOM_PX = 10;
const NUMBER_FONT_STACK = 'var(--font-number, Inter, ui-sans-serif, system-ui, sans-serif)';
function SolidTriangleRightIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path d="M5 3.5L11.5 8L5 12.5V3.5Z" fill="#222727" fillOpacity="0.85" />
    </svg>
  );
}

function ChartLegendRow({ series }) {
  return (
    <div className="flex flex-none flex-wrap items-center justify-center gap-x-2 gap-y-1 px-1 py-1">
      {series.map((s) => (
        <span key={s.dataKey} className="inline-flex items-center gap-1 text-[12px] font-semibold leading-4 text-blueGrey-700">
          <span
            className="inline-block w-3 rounded-full"
            style={{
              height: s.strokeDasharray ? 0 : CHART_SERIES_LINE_STROKE_WIDTH,
              background: s.strokeDasharray
                ? 'transparent'
                : `var(${tokenNameToCssVar(s.colorToken) || '--color-blueGrey-500'})`,
              borderTop: s.strokeDasharray
                ? `1px dashed var(${tokenNameToCssVar(s.colorToken) || '--color-blueGrey-500'})`
                : 'none',
              opacity: 0.95,
            }}
          />
          {s.name}
        </span>
      ))}
    </div>
  );
}

function TopicRow({ row, selected, onSelect }) {
  return (
    <button
      type="button"
      onClick={() => onSelect(row.id)}
      className={`w-full rounded-md px-4 py-2 text-left ${selected ? 'bg-white border border-[rgba(34,39,39,0.07)]' : 'border border-transparent bg-transparent'}`}
      style={{ cursor: 'pointer' }}
    >
      <div className="flex items-center gap-3">
        <div className="min-w-0 flex-1 overflow-hidden">
          {row.id === 'all' ? (
            <div
              className="truncate whitespace-nowrap text-sm font-semibold leading-5 text-blueGrey-800"
              style={{ fontWeight: 'var(--font-weight-semibold, 600)' }}
            >
              {row.code}
            </div>
          ) : (
            <>
              <div className="truncate whitespace-nowrap text-sm leading-5 text-blueGrey-500">{row.code}</div>
              <div
                className={`truncate whitespace-nowrap text-sm leading-5 text-blueGrey-800 ${selected ? 'font-semibold' : 'font-normal'}`}
                style={{ fontWeight: selected ? 'var(--font-weight-semibold, 600)' : 'var(--font-weight-normal, 400)' }}
              >
                {row.title}
              </div>
            </>
          )}
        </div>
        <div className="flex shrink-0 items-center gap-2">
          <span className="text-[20px] font-semibold leading-7 tracking-[-0.6px] text-blueGrey-900" style={{ fontFamily: NUMBER_FONT_STACK }}>
            {row.value}
          </span>
          <span className={`${selected ? 'opacity-100' : 'opacity-0'} transition-opacity`}>
            <SolidTriangleRightIcon />
          </span>
        </div>
      </div>
    </button>
  );
}

/**
 * Dashboard 业务组件：多Tab + 图表（议题列表 + 反馈量折线）
 */
export default function MultiTabChartPreview({
  title = '议题用户反馈分布',
  subtitle = '说明文字占位说明文字占位说明文字占位',
  titleIconSrc = '',
  topics = TOPIC_ROWS,
  containerMaxWidth = 1268,
}) {
  const [selectedId, setSelectedId] = useState(topics[0]?.id || 'all');
  const leftPanelRef = useRef(null);
  const legendRef = useRef(null);
  const [chartHeight, setChartHeight] = useState(420);
  const visibleSeries = useMemo(() => {
    if (selectedId === 'all') return CHART_SERIES;
    return CHART_SERIES.filter((item) => item.dataKey === selectedId);
  }, [selectedId]);

  useEffect(() => {
    const leftEl = leftPanelRef.current;
    const legendEl = legendRef.current;
    if (!leftEl) return undefined;

    const updateHeight = () => {
      const leftHeight = Math.floor(leftEl.clientHeight || 0);
      const legendHeight = Math.ceil(legendEl?.clientHeight || 0);
      // Keep the chart area aligned with the topic list bottom edge.
      const next = Math.max(120, leftHeight - legendHeight - LEGEND_CHART_GAP_PX);
      setChartHeight((prev) => (prev === next ? prev : next));
    };

    updateHeight();
    const observer = new ResizeObserver(updateHeight);
    observer.observe(leftEl);
    if (legendEl) observer.observe(legendEl);
    return () => observer.disconnect();
  }, []);

  const chartSpec = useMemo(
    () => ({
      data: CHART_DATA,
      series: visibleSeries,
      config: {
        showLegend: false,
        legendPosition: 'top',
        showGrid: true,
        showDots: false,
        curveType: 'linear',
        showXAxis: true,
        showYAxis: true,
        yAxisTickCount: 7,
        yAxisDomainMode: selectedId === 'all' ? 'zero-or-min' : 'data-range',
        height: chartHeight,
        margin: {
          top: CHART_TOP_PADDING_PX,
          right: CHART_RIGHT_PADDING_PX,
          // Keep x-axis baseline close to the panel bottom for visual alignment.
          bottom: 0,
          // The lane gap is controlled by layout `gap`; avoid extra visual blank area here.
          left: CHART_LEFT_PADDING_PX,
        },
      },
    }),
    [chartHeight, selectedId, visibleSeries],
  );

  return (
    <div className="min-h-0 flex min-w-0 flex-col overflow-hidden rounded-xl bg-white px-6 pb-6 pt-4" style={{ width: '100%', maxWidth: containerMaxWidth }}>
      <div className="mb-6 flex min-w-0 items-center gap-3">
        <div className="inline-flex min-w-0 shrink-0 items-center gap-2">
          {titleIconSrc ? (
            <img src={titleIconSrc} alt="" aria-hidden="true" className="h-6 w-6 shrink-0" />
          ) : null}
          <h3
            className="shrink-0 whitespace-nowrap text-lg font-semibold leading-6 text-blueGrey-900"
            style={{ fontWeight: 'var(--font-weight-semibold, 600)' }}
          >
            {title}
          </h3>
        </div>
        <span className="truncate whitespace-nowrap text-xs leading-4 text-blueGrey-500">{subtitle}</span>
      </div>

      <div className="flex h-full min-h-[440px] min-w-0 items-stretch gap-4 overflow-hidden">
        <div
          ref={leftPanelRef}
          className="h-full w-[280px] shrink-0 self-stretch bg-blueGrey-100"
          style={{
            borderRadius: LEFT_PANEL_RADIUS_PX,
            paddingTop: LEFT_PANEL_PADDING_TOP_PX,
            paddingRight: LEFT_PANEL_PADDING_SIDE_PX,
            paddingBottom: LEFT_PANEL_PADDING_BOTTOM_PX,
            paddingLeft: LEFT_PANEL_PADDING_SIDE_PX,
          }}
        >
          <div className="h-full min-h-0 overflow-auto dashboard-scrollbar-hide">
            {topics.map((row, idx) => (
              <div key={row.id} className={idx === topics.length - 1 ? '' : 'mb-1'}>
                <TopicRow row={row} selected={row.id === selectedId} onSelect={setSelectedId} />
              </div>
            ))}
          </div>
        </div>

        <div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
          <div ref={legendRef}>
            <ChartLegendRow series={visibleSeries} />
          </div>
          <div className="min-h-0 min-w-0 overflow-hidden" style={{ height: chartHeight, marginTop: LEGEND_CHART_GAP_PX }}>
            <div className="h-full w-full min-w-0 overflow-hidden">
              <SmartLineChart spec={chartSpec} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

