import { useState } from 'react';
import ChartTooltip from '../../charts/ChartTooltip';
/**
 * ProportionBarCard — Dashboard 业务组件：占比条指标卡 (Tailwind 内联)
 *
 * 横排 4 张卡片，每张包含：
 *   1. 标题（虚线下划线 + hover Tooltip 口径说明，样式复用智能指标卡）
 *   2. 主百分比数值 + 环比趋势
 *   3. 底部占比进度条
 *
 * 升降色与智能指标卡一致：仅 success（绿 #24CDA5）/ danger（红 #FC7E90），
 * 由 status 驱动环比与进度条，禁止 data-* 或其它色值。
 *
 * Props:
 *   items — MetricItem[]，含 status: 'success' | 'danger'
 */

/* ── 字体栈常量 ── */
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)';

/* ── 升降色：与 SmartIndicator / --status-success | --status-danger 一致 ── */
/** 固定色值，避免页面模板未挂 Dashboard 主题时 --color-success 解析失真 */
const STATUS_COLOR = {
  success: '#24CDA5',
  danger: '#FC7E90',
};

/* ── 进度条轨道底色：Figma #53608F Fill 7%（勿用 scope 内会被盖成卡身的 --semi-color-fill-0） ── */
const BAR_TRACK_BG = 'var(--color-fill, rgba(83, 96, 143, 0.07))';

/* ── Mock 数据 ── */
const DEFAULT_ITEMS = [
  {
    id: 'resolve-rate',
    title: '日均智能解决率',
    titleTooltip: '智能解决率 = 智能解决会话数 / 日均总会话数',
    value: '30.7%',
    trendLabel: '环比',
    trendValue: '11.12pp',
    trendDirection: 'down',
    barPercent: 61,
    status: 'success',
    lineColorToken: 'data-7',
    trendDataKey: 'resolveRate',
  },
  {
    id: 'transfer-rate',
    title: '日均智能转人工率',
    titleTooltip: '智能转人工率 = 转人工会话数 / 日均总会话数',
    value: '45.8%',
    trendLabel: '环比',
    trendValue: '11.12pp',
    trendDirection: 'down',
    barPercent: 70,
    status: 'success',
    lineColorToken: 'data-0',
    trendDataKey: 'transferRate',
  },
  {
    id: 'manual-resolve',
    title: '日均人工解决率',
    titleTooltip: '人工解决率 = 人工解决会话数 / 日均人工会话数',
    value: '28.6%',
    trendLabel: '环比',
    trendValue: '11.12pp',
    trendDirection: 'up',
    barPercent: 55,
    status: 'danger',
    lineColorToken: 'data-5',
    trendDataKey: 'manualResolve',
  },
  {
    id: 'manual-policy',
    title: '转人工策略率',
    titleTooltip: '转人工策略率 = 策略触发转人工数 / 日均转人工总数',
    value: '45.8%',
    trendLabel: '环比',
    trendValue: '11.12pp',
    trendDirection: 'down',
    barPercent: 70,
    status: 'success',
    lineColorToken: 'data-3',
    trendDataKey: 'manualPolicy',
  },
];

const SELECTED_BORDER_COLOR = '#24CDA5';

/** @param {'success'|'danger'|string|undefined} status */
function resolveStatusColor(status) {
  return status === 'danger' ? STATUS_COLOR.danger : STATUS_COLOR.success;
}

/** 兼容历史 tone / 未传 status */
function resolveItemStatus(item) {
  if (item.status === 'danger' || item.status === 'success') return item.status;
  if (item.tone === 'red') return 'danger';
  if (item.tone === 'green') return 'success';
  return 'success';
}

/* ── 趋势箭头 + 数值 ── */
function TrendDelta({ value, direction, status }) {
  const color = resolveStatusColor(status);
  const showArrow = direction === 'up' || direction === 'down';
  return (
    <span
      className="inline-flex items-center gap-1 text-[11px] leading-4"
      style={{ color, fontFamily: RATIO_FONT_STACK }}
    >
      {showArrow ? (
        <svg
          className={`h-3 w-3 ${direction === 'down' ? 'rotate-180' : ''}`}
          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>{value}</span>
    </span>
  );
}

/* ── 指标标题（虚线 + hover Tooltip，复用智能指标卡样式） ── */
function IndicatorTitle({ title, titleTooltip = '指标口径解释文案占位' }) {
  return (
    <span className="group relative inline-flex min-w-0 max-w-full overflow-visible">
      <p
        className="m-0 inline-block min-w-0 max-w-full truncate border-b border-dashed pb-0 text-sm leading-5 text-[var(--semi-color-text-1,rgba(34,39,39,0.8))]"
        style={{
          borderBottomColor: 'var(--color-blueGrey-400, #D0D5DD)',
          fontWeight: 'var(--font-weight-semibold, 600)',
        }}
      >
        {title}
      </p>
      {titleTooltip ? (
        <span className="pointer-events-none absolute bottom-full left-0 z-50 mb-1.5 hidden group-hover:block">
          <ChartTooltip variant="caption">{titleTooltip}</ChartTooltip>
        </span>
      ) : null}
    </span>
  );
}

/* ── 占比进度条（统一绿色，不承载升降语义） ── */
function ProportionBar({ percent = 0 }) {
  const fillColor = STATUS_COLOR.success;
  const clampedPercent = Math.max(0, Math.min(100, percent));
  return (
    <div className="h-2 w-full rounded-full" style={{ background: BAR_TRACK_BG }}>
      <div
        className="h-full rounded-full transition-all duration-300"
        style={{ width: `${clampedPercent}%`, background: fillColor }}
      />
    </div>
  );
}

/* ── 主组件 ── */
export default function ProportionBarCardPreview({
  items = DEFAULT_ITEMS,
  itemSurface = 'muted',
  selectedId = null,
  onSelect = null,
}) {
  const [localSelectedId, setLocalSelectedId] = useState(null);
  const itemBg =
    itemSurface === 'plain'
      ? '#FFFFFF'
      : '#F9FAFB';
  const isControlled = selectedId !== null && selectedId !== undefined;
  const activeSelectedId = isControlled ? selectedId : localSelectedId;

  return (
    <div className="smart-indicator-preview-scope flex w-full min-w-0 flex-wrap gap-3 overflow-visible">
      {items.map((item, idx) => {
        const status = resolveItemStatus(item);
        const itemId = item.id ?? String(idx);
        const isSelected = activeSelectedId != null && itemId === activeSelectedId;
        const isInteractive = true;
        const handleSelect = () => {
          if (typeof onSelect === 'function') {
            onSelect(itemId);
            return;
          }
          setLocalSelectedId((prev) => (prev === itemId ? null : itemId));
        };
        return (
          <div
            key={itemId}
            role={isInteractive ? 'button' : undefined}
            tabIndex={isInteractive ? 0 : undefined}
            aria-pressed={isInteractive ? isSelected : undefined}
            onClick={isInteractive ? handleSelect : undefined}
            onKeyDown={
              isInteractive
                ? (event) => {
                    if (event.key === 'Enter' || event.key === ' ') {
                      event.preventDefault();
                      handleSelect();
                    }
                  }
                : undefined
            }
            className={[
              'flex min-w-[270px] flex-[1_1_270px] flex-col gap-1 overflow-visible rounded-lg px-4 py-3',
              isInteractive ? 'cursor-pointer' : '',
            ].filter(Boolean).join(' ')}
            style={{
              background: itemBg,
              minWidth: 0,
              boxSizing: 'border-box',
              border: `1px solid ${isSelected ? SELECTED_BORDER_COLOR : 'transparent'}`,
            }}
          >
            <IndicatorTitle title={item.title} titleTooltip={item.titleTooltip} />

            <div className="flex items-baseline gap-3">
              <span
                className="text-lg font-semibold leading-6 tracking-[-0.03em] text-[var(--semi-color-text-0,#222727)]"
                style={{ fontFamily: NUMBER_FONT_STACK }}
              >
                {item.value}
              </span>
              <div className="flex items-center gap-1">
                <span className="text-xs leading-4 text-[rgba(28,28,35,0.6)]">
                  {item.trendLabel || '环比'}
                </span>
                <TrendDelta
                  value={item.trendValue}
                  direction={item.trendDirection}
                  status={status}
                />
              </div>
            </div>

            <ProportionBar percent={item.barPercent} />
          </div>
        );
      })}
    </div>
  );
}
