import { useEffect, useMemo, useState } from 'react';

const DEFAULT_ROWS = [
  { id: 'account', name: '账号', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12, color: '#2ECAB4' },
  { id: 'basic', name: '基础产品', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: 10.11, color: '#FC7E90' },
  { id: 'creation', name: '创作与投稿', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12, color: '#E4E7EC' },
  { id: 'social', name: '社交', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12, color: '#3CCBFF' },
  { id: 'incentive', name: '激励', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12, color: '#B0BEFF' },
  { id: 'recommend', name: '推荐与广告', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12, color: '#FFDE70' },
  { id: 'search', name: '搜索', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12, color: '#12CC91' },
  { id: 'growth', name: '成长变现', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12, color: '#B399FE' },
  { id: 'market', name: '营销与推广', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12, color: '#FF803C' },
  { id: 'rights', name: '权益保护', posts: '23,321', postsRatio: -10.12, interactions: '23,321', interactionsRatio: -10.12, color: '#FC7E90' },
];
const NUMBER_FONT_STACK = 'var(--font-number, Inter, ui-sans-serif, system-ui, sans-serif)';
const RATIO_FONT_STACK = 'var(--font-number-medium, Inter, ui-sans-serif, system-ui, sans-serif)';

function TrendValue({ value }) {
  const numeric = Number(value || 0);
  const isUp = numeric > 0;
  const isDown = numeric < 0;
  const textColor = isUp ? '#FC7E90' : isDown ? '#07B3A7' : '#98A2B3';
  const rotateClass = isUp ? '' : 'rotate-180';
  return (
    <span className="inline-flex w-full min-w-0 items-center justify-end gap-1 text-[11px] leading-[14px]" style={{ color: textColor, fontFamily: RATIO_FONT_STACK }}>
      {(isUp || isDown) ? (
        <svg className={`h-3 w-3 ${rotateClass}`} viewBox="0 0 12 12" fill="none" aria-hidden="true">
          <path
            d="M8.5417 8.16062H3.47596C3.27628 8.16062 3.15719 7.93808 3.26794 7.77194L5.80082 3.97264C5.89977 3.8242 6.11788 3.8242 6.21684 3.97264L8.74971 7.77194C8.86047 7.93808 8.74137 8.16062 8.5417 8.16062Z"
            fill="currentColor"
          />
        </svg>
      ) : (
        <span>—</span>
      )}
      <span className="truncate">{Math.abs(numeric).toFixed(2)}%</span>
    </span>
  );
}

/**
 * Dashboard 业务组件：指标&图例表（无图例 / 有图例）
 *
 * Props:
 *   variant — 'without-legend' | 'with-legend'
 *   rows — 行数据
 */
export default function MetricLegendTablePreview({
  variant = 'without-legend',
  rows = DEFAULT_ROWS,
  selectedId,
  onSelect,
  gridColsClass,
  containerClassName = 'xl:w-[320px]',
}) {
  const [innerSelectedId, setInnerSelectedId] = useState(rows[0]?.id || '');
  const [hoverId, setHoverId] = useState('');
  const withLegend = variant === 'with-legend';
  const activeSelectedId = typeof selectedId === 'string' ? selectedId : innerSelectedId;

  useEffect(() => {
    if (!Array.isArray(rows) || rows.length === 0) return;
    if (!rows.some((row) => row.id === activeSelectedId)) {
      setInnerSelectedId(rows[0].id);
    }
  }, [rows, activeSelectedId]);

  const handleSelect = (rowId) => {
    if (typeof selectedId !== 'string') setInnerSelectedId(rowId);
    if (typeof onSelect === 'function') onSelect(rowId);
  };

  // 自适应规则：
  // - 一级列：最小 6 个字宽（约 6em），多余 truncate + title tooltip
  // - 数字列：固定宽度
  // - 容器层不再 overflow-hidden，由父级 aside 的横滑兜底处理过窄场景
  const gridCols = useMemo(
    () => (gridColsClass || (withLegend
      ? 'grid-cols-[minmax(6em,1fr)_60px_64px_60px]'
      : 'grid-cols-[minmax(6em,1fr)_60px_64px_60px]')),
    [withLegend, gridColsClass],
  );

  return (
    <section className={`w-full max-w-full rounded-[3px] ${containerClassName}`}>
      <div className={`grid w-full ${gridCols} items-center gap-x-2 rounded-[3px] bg-blueGrey-200 px-3 py-1 text-xs font-semibold leading-4 text-[rgba(34,39,39,0.6)]`}>
        <span className="whitespace-nowrap">一级</span>
        <span className="whitespace-nowrap text-right">发文量</span>
        <span className="whitespace-nowrap text-right">环比</span>
        <span className="whitespace-nowrap text-right">互动量</span>
      </div>

      <div className="py-1">
        {rows.map((row) => {
          const selected = row.id === activeSelectedId;
          const hovered = row.id === hoverId;
          const rowClass = selected
            ? 'bg-blueGrey-200'
            : hovered
              ? 'bg-blueGrey-100'
              : 'bg-transparent';

          return (
            <button
              key={row.id}
              type="button"
              className={`grid w-full min-w-0 ${gridCols} items-center gap-x-2 rounded-[3px] px-3 py-1 text-left text-xs leading-[14px] ${rowClass} ${selected ? 'font-semibold' : 'font-normal'}`}
              style={{ fontWeight: selected ? 'var(--font-weight-semibold, 600)' : 'var(--font-weight-normal, 400)' }}
              onMouseEnter={() => setHoverId(row.id)}
              onMouseLeave={() => setHoverId('')}
              onClick={() => handleSelect(row.id)}
            >
              <span
                className={`relative inline-flex min-w-0 items-center gap-1 ${selected ? 'font-semibold text-blueGrey-900' : 'text-blueGrey-700'}`}
                style={{ fontWeight: selected ? 'var(--font-weight-semibold, 600)' : 'var(--font-weight-normal, 400)' }}
              >
                {withLegend ? (
                  <span className="h-3 w-3 shrink-0 rounded-[3px]" style={{ backgroundColor: row.color }} />
                ) : null}
                {!withLegend && selected ? (
                  <svg
                    className="absolute -left-[8px] top-1/2 h-[5.57px] w-[4.3px] -translate-y-1/2"
                    viewBox="0 0 4.3 5.57"
                    fill="none"
                    aria-hidden="true"
                  >
                    <path d="M4.3 0L0 2.785L4.3 5.57V0Z" fill="rgba(34,39,39,0.35)" />
                  </svg>
                ) : null}
                <span className="truncate" title={row.name}>{row.name}</span>
              </span>
              <span
                className={`overflow-hidden whitespace-nowrap text-right text-blueGrey-700 ${selected ? 'font-semibold' : ''}`}
                style={{
                  fontFamily: NUMBER_FONT_STACK,
                  fontWeight: selected ? 'var(--font-weight-semibold, 600)' : 'var(--font-weight-normal, 400)',
                }}
              >
                {row.posts}
              </span>
              <span className="min-w-0 w-full justify-self-stretch"><TrendValue value={row.postsRatio} /></span>
              <span
                className={`overflow-hidden whitespace-nowrap text-right text-blueGrey-700 ${selected ? 'font-semibold' : ''}`}
                style={{
                  fontFamily: NUMBER_FONT_STACK,
                  fontWeight: selected ? 'var(--font-weight-semibold, 600)' : 'var(--font-weight-normal, 400)',
                }}
              >
                {row.interactions}
              </span>
            </button>
          );
        })}
      </div>
    </section>
  );
}
