import Sparkline from '../../charts/native/Sparkline';
import { INDICATOR_SPARKLINE_STROKE_WIDTH } from '../../SmartIndicator.jsx';
import ChartTooltip from '../../charts/ChartTooltip';

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)';

const PANEL_DATA = [
  {
    id: 'entry',
    tab: '入口',
    title: '日均入口会话量',
    value: '324.6 万',
    trendLabel: '环比',
    trendValue: '11.12%',
    trendDirection: 'down',
    chartData: [68, 74, 59, 62, 48, 66, 79, 56, 64, 64, 69, 55, 72, 66, 82, 70, 67],
    metrics: [
      { label: '有效会话占比', value: '32.4%', delta: '11.12pp', direction: 'down' },
      { label: '寒暄会话占比', value: '32.4%', delta: '11.12pp', direction: 'down' },
      { label: '无对话会话占比', value: '32.4%', delta: '11.12pp', direction: 'up' },
    ],
  },
  {
    id: 'service',
    tab: '诊断与服务',
    title: '日均服务会话量',
    value: '324.6 万',
    trendLabel: '环比',
    trendValue: '11.12%',
    trendDirection: 'down',
    chartData: [66, 73, 61, 64, 52, 70, 81, 58, 67, 61, 72, 58, 76, 69, 83, 71, 75],
    metrics: [
      { label: '智能完结率', value: '32.4%', delta: '11.12pp', direction: 'down' },
      { label: '智能转人工率', value: '32.4%', delta: '11.12pp', direction: 'down' },
      { label: '转其他业务线率', value: '32.4%', delta: '11.12pp', direction: 'up' },
    ],
  },
  {
    id: 'review',
    tab: '评价',
    title: '日均邀评会话量',
    value: '24.6 万',
    trendLabel: '环比',
    trendValue: '11.12%',
    trendDirection: 'up',
    chartData: [58, 66, 54, 60, 49, 67, 79, 55, 64, 58, 70, 57, 74, 66, 81, 68, 73],
    metrics: [
      { label: '参评率', value: '32.4%', delta: '11.12%', direction: 'up' },
      { label: '智能解决率', value: '32.4%', delta: '11.12%', direction: 'down' },
    ],
  },
];

function resolveTrendColor(direction) {
  if (direction === 'up') return '#F2496F';
  if (direction === 'down') return '#24CDA5';
  return '#98A2B3';
}

function formatChartTooltipValue(n) {
  return `${Number(n).toFixed(2)}%`;
}

function TrendDelta({ value, direction }) {
  const color = resolveTrendColor(direction);
  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>
  );
}

function IndicatorTitle({
  title,
  titleTooltip = '指标口径解释文案占位',
  textClassName = 'text-sm font-semibold leading-6',
  titleFontWeight = 'var(--font-weight-semibold, 600)',
}) {
  return (
    <span className="group relative inline-flex min-w-0 max-w-full overflow-hidden">
      <p
        className={`m-0 inline-block min-w-0 max-w-full truncate border-b border-dashed pb-0 text-[var(--semi-color-text-0)] ${textClassName}`}
        style={{
          borderBottomColor: 'var(--color-blueGrey-400, #D0D5DD)',
          fontWeight: titleFontWeight,
        }}
      >
        {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>
  );
}

const TAB_BG = '#F7F8FA';
const CARD_BORDER = 'rgba(45,66,107,0.12)';

function MicroAreaChart({ data, trendDirection }) {
  const chartColor = resolveTrendColor(trendDirection);
  const sparkData = data.map((point, i) => {
    if (typeof point === 'number') {
      return { value: point, at: `2024-01-${String(i + 1).padStart(2, '0')}` };
    }
    return {
      value: Number(point?.value || 0),
      at: point?.at || `2024-01-${String(i + 1).padStart(2, '0')}`,
    };
  });
  return (
    <div className="h-[72px] flex-1 min-w-0">
      <Sparkline
        data={sparkData}
        color={chartColor}
        strokeWidth={INDICATOR_SPARKLINE_STROKE_WIDTH}
        showMeanLine
        margin={{ top: 4, right: 0, bottom: 0, left: 0 }}
        tooltipEnabled
        formatTooltipValue={formatChartTooltipValue}
        fillStops={[
          { offset: '0%', opacity: 0.34 },
          { offset: '72%', opacity: 0.12 },
          { offset: '100%', opacity: 0.02 },
        ]}
      />
    </div>
  );
}

/**
 * Dashboard 业务组件：进度指标卡
 *
 * Props:
 *  - panels: 自定义三列数据（默认入口 / 诊断与服务 / 评价）
 */
export default function ProgressIndicatorCardPreview({
  panels = PANEL_DATA,
  borderless = false,
}) {
  return (
    <section
      className={[
        'w-full min-w-0 overflow-hidden rounded-[8px] bg-white',
        borderless ? '' : 'border border-[rgba(45,66,107,0.12)]',
      ].filter(Boolean).join(' ')}
    >
      <style>
        {`
          .pic-step-item {
            background-color: ${TAB_BG};
            border: none;
            outline: none;
            box-shadow: none;
            overflow: visible;
          }

          .pic-step-item.has-arrow::after,
          .pic-step-item.has-arrow::before {
            content: '';
            position: absolute;
            top: 50%;
            width: 0;
            height: 0;
            transform: translateY(-50%);
            border-style: solid;
          }

          /* 顶层灰色箭头：上下必须是 transparent */
          .pic-step-item.has-arrow::after {
            right: -10px;
            border-width: 16px 0 16px 10px;
            border-color: transparent transparent transparent ${TAB_BG};
            z-index: 30;
          }

          /* 底层描边色箭头：漏出 2px 形成和卡片一致的分割线 */
          .pic-step-item.has-arrow::before {
            right: -12px;
            border-width: 18px 0 18px 12px;
            border-color: transparent transparent transparent ${CARD_BORDER};
            z-index: 20;
          }

          @media (max-width: 1199px) {
            .pic-step-item.has-arrow::after,
            .pic-step-item.has-arrow::before {
              display: none;
            }
          }
        `}
      </style>

      {/* ── Tab 条：独立行，无列分隔线，仅靠箭头分隔 ── */}
      <div className="grid grid-cols-1 border-b border-[rgba(45,66,107,0.12)] min-[1200px]:grid-cols-3">
        {panels.map((panel, index) => (
          <div
            key={panel.id || panel.tab}
            className={[
              'pic-step-item relative flex h-8 items-center justify-center px-3',
              index < panels.length - 1 ? 'has-arrow' : '',
              index > 0 ? 'min-[1200px]:pl-6' : 'min-[1200px]:px-3',
            ].filter(Boolean).join(' ')}
          >
            <span
              className="relative z-40 text-sm font-semibold leading-5 text-[#222727]"
              style={{ fontWeight: 'var(--font-weight-semibold, 600)' }}
            >
              {panel.tab}
            </span>
          </div>
        ))}
      </div>

      {/* ── 内容列：border-r 只在此区域生效 ── */}
      <div className="grid grid-cols-1 min-[1200px]:grid-cols-3">
        {panels.map((panel, index) => (
          <div
            key={panel.id || panel.tab}
            className={[
              'px-4 pb-4 overflow-hidden',
              index < panels.length - 1 ? 'border-b border-[rgba(45,66,107,0.12)] min-[1200px]:border-b-0 min-[1200px]:border-r' : '',
            ].filter(Boolean).join(' ')}
          >
            <div className="flex min-w-0 flex-wrap items-center gap-3 py-4 min-[1200px]:flex-nowrap min-[1200px]:gap-6">
              <div className="flex min-w-0 flex-1 flex-col gap-1 overflow-hidden">
                <IndicatorTitle
                  title={panel.title}
                  textClassName="text-sm font-semibold leading-5 text-[var(--semi-color-text-1,rgba(34,39,39,0.8))]"
                />
                <p
                  className="text-lg font-semibold leading-6 tracking-[-0.03em] text-[var(--semi-color-text-0,#222727)]"
                  style={{ fontFamily: NUMBER_FONT_STACK }}
                >
                  {panel.value}
                </p>
                <div className="flex items-center gap-1">
                  <span className="text-xs leading-4 text-[rgba(28,28,35,0.6)]">{panel.trendLabel}</span>
                  <TrendDelta value={panel.trendValue} direction={panel.trendDirection} />
                </div>
              </div>
              <MicroAreaChart
                data={panel.chartData}
                chartId={panel.id || index}
                trendDirection={panel.trendDirection}
              />
            </div>

            <div
              className={[
                'grid gap-2 rounded-lg bg-blueGrey-100 p-3',
                panel.metrics.length === 2
                  ? 'grid-cols-1 min-[860px]:grid-cols-2'
                  : 'grid-cols-1 min-[860px]:grid-cols-2 min-[1380px]:grid-cols-3',
              ].join(' ')}
            >
              {panel.metrics.map((metric) => (
                <div key={metric.label} className="flex min-w-0 flex-col gap-1 overflow-hidden">
                  <IndicatorTitle
                    title={metric.label}
                    textClassName="text-xs font-normal leading-4 text-[rgba(34,39,39,0.8)]"
                  titleFontWeight="var(--font-weight-normal, 400)"
                  />
                  <div className="flex items-center gap-1">
                    <span className="text-xs font-semibold leading-4 text-[#222727]" style={{ fontFamily: NUMBER_FONT_STACK }}>
                      {metric.value}
                    </span>
                    <TrendDelta value={metric.delta} direction={metric.direction} />
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}
