import { Tag as Tag } from '../b-end.js';
import rank1Icon from './assets/rank-1.svg';
import rank2Icon from './assets/rank-2.svg';
import rank3Icon from './assets/rank-3.svg';

const TOP_RANK_ICONS = {
  1: rank1Icon,
  2: rank2Icon,
  3: rank3Icon,
};
const RATIO_COLOR = {
  up: '#F2496F',
  down: '#24CDA5',
  flat: 'var(--color-blueGrey-500)',
};

function RatioText({ ratio }) {
  const v = Number(ratio ?? 0);
  const up = v > 0;
  const down = v < 0;
  const color = up ? RATIO_COLOR.up : down ? RATIO_COLOR.down : RATIO_COLOR.flat;
  return (
    <span
      className="inline-flex items-center gap-0.5 text-[11px] font-normal leading-4"
      style={{ color, fontFamily: 'var(--font-number-medium, var(--font-sans))' }}
    >
      {(up || down) ? (
        <svg
          className={down ? 'rotate-180' : ''}
          viewBox="0 0 12 12"
          width="12"
          height="12"
          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>{Math.abs(v).toFixed(2)}%</span>
    </span>
  );
}

function RankingItemRow({ item, isLast = false }) {
  const topThree = item.rank <= 3;
  const topRankIcon = TOP_RANK_ICONS[item.rank];

  // 多指标横向排列模式（如：总计 / 待校准）。优先级高于 feedbackLabel + ratio 的"累计反馈量"模式。
  const hasMetrics = Array.isArray(item.metrics) && item.metrics.length > 0;

  const feedbackLabel = item.feedbackLabel || '累计反馈量';
  const feedbackValue = item.feedbackValue || '1,232';
  return (
    <div
      className={`flex items-center gap-3 rounded-md bg-blueGrey-100 px-4 py-3 ${isLast ? '' : 'mb-2'}`}
    >
      <div className="flex-shrink-0 self-start pt-0.5">
        {topThree && topRankIcon ? (
          <img src={topRankIcon} alt={`rank-${item.rank}`} className="block h-4 w-4" />
        ) : (
          <div
            className="flex h-4 w-4 items-center justify-center rounded-full bg-transparent text-xs font-semibold leading-3 text-blueGrey-500"
            style={{ fontFamily: 'var(--font-number, var(--font-sans))' }}
          >
            {item.rank}
          </div>
        )}
      </div>

      {hasMetrics ? (
        <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-2">
          <span
            className="whitespace-nowrap text-[14px] font-semibold leading-[22px] text-blueGrey-900"
            style={{ fontWeight: 'var(--font-weight-semibold, 600)' }}
          >
            {item.title}
          </span>
          <div className="ml-auto flex shrink-0 items-center gap-5">
            {item.metrics.map((m, i) => (
              <div key={`${m.label}-${i}`} className="flex items-baseline gap-1.5">
                <span className="text-[12px] leading-4 text-blueGrey-500">{m.label}：</span>
                <span
                  className="text-[14px] font-semibold leading-[18px]"
                  style={{
                    fontFamily: 'var(--font-number, var(--font-sans))',
                    color: m.valueColor || '#1C1C23',
                  }}
                >
                  {m.value}
                </span>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <>
          <div className="min-w-0 flex-1">
            <div className="mb-0.5 flex min-w-0 items-center gap-2">
              <span
                className="truncate text-[14px] font-semibold leading-[22px] text-blueGrey-900"
                style={{ fontWeight: 'var(--font-weight-semibold, 600)' }}
              >
                {item.title}
              </span>
              {item.tag || '标签' ? (
                <Tag
                  variant="grey"
                  size="s"
                  className="shrink-0 rounded-full border border-[rgba(34,39,39,0.09)] bg-white px-1 text-[11px] font-semibold leading-4 text-blueGrey-900"
                >
                  {item.tag || '标签'}
                </Tag>
              ) : null}
            </div>
            <div className="truncate text-[12px] leading-6 text-blueGrey-600">
              {item.summary}
            </div>
          </div>
          <div className="flex shrink-0 flex-col items-end justify-between self-stretch">
            <span
              className="text-[12px] leading-4 text-blueGrey-500"
              style={{ fontSize: 12, lineHeight: '16px' }}
            >
              {feedbackLabel}
            </span>
            <div className="inline-flex items-end gap-0.5">
              <span
                className="text-[14px] font-semibold leading-[18px] text-[#1C1C23]"
                style={{ fontFamily: 'var(--font-number, var(--font-sans))' }}
              >
                {feedbackValue}
              </span>
              <RatioText ratio={item.ratio} />
            </div>
          </div>
        </>
      )}
    </div>
  );
}

/**
 * Dashboard 业务组件：榜单卡片（含标题）
 *
 * - 默认渲染白卡 + 标题 + 列表（独立卡片用法）
 * - `embedded=true` 时仅渲染列表本身（嵌入到既有白卡内使用，外层卡片与标题由父级提供）
 */
export default function RankingCardPreview({
  title = '热门问题',
  subtitle = '32',
  titleIconSrc = '',
  items = [],
  embedded = false,
}) {
  const list = (
    <div className="min-h-0 w-full flex-1 overflow-auto dashboard-scrollbar-hide">
      {items.map((item, idx) => (
        <RankingItemRow key={`${item.title}-${item.rank}-${idx}`} item={item} isLast={idx === items.length - 1} />
      ))}
    </div>
  );

  if (embedded) return list;

  const countText = subtitle || String(items.length);
  return (
    <div className="min-h-0 flex flex-col" style={{ width: '100%', maxWidth: 588 }}>
      <div className="min-h-0 rounded-xl bg-white p-4">
        <div className="mb-4 flex min-w-0 items-center gap-2">
          <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 text-lg font-semibold leading-6 text-blueGrey-900"
              style={{ fontWeight: 'var(--font-weight-semibold, 600)' }}
            >
              {title}
            </h3>
          </div>
          <span
            className="truncate text-[12px] leading-4 text-blueGrey-500"
            style={{ fontFamily: 'var(--font-number, var(--font-sans))' }}
          >
            {countText}
          </span>
        </div>

        {list}
      </div>
    </div>
  );
}
