import { useEffect, useMemo, useRef, useState } from 'react';
import { Button as Button } from '../b-end.js';
import CheckboxGroup, { Checkbox } from '@/data/systems/b-end/components/Checkbox';
import { Icon as Icon } from '../b-end.js';
import SmartPieChart from '../../charts/SmartPieChart';
import SmartBarChart from '../../charts/SmartBarChart';
import SmartComposedChart from '../../charts/SmartComposedChart';
import { tokenNameToCssVar } from '../../utils/token-resolver.js';
import DashboardModuleTitle from './DashboardModuleTitle';
import AISummaryPreview from './AISummaryPreview';
import FeatureCardGroup from './FeatureCardGroup';
import { DASHBOARD_CARD_PADDING_CLASS } from '../typography';

/**
 * FeatureCardGroupPreview — 业务组件「特征卡片组」预览
 *
 * 示范"同一主题、不同维度的图表共享一张大白卡"的聚合卡组织方式：
 *   - 默认 3 列横排，子卡 chart slot 分别承载：
 *     1) SmartPieChart（donut）—— 反馈情绪分布
 *     2) 上图 SmartComposedChart（堆叠柱） + 下方"会员等级"占比条 —— 会员情况
 *     3) 上图 SmartBarChart（horizontal） + 下方"设备分布"占比条 —— 设备版本分布
 *
 * 与业务侧使用方式一致：仅作为聚合容器，图表全部走 dashboard Smart* 组件，
 * 严禁在内部 hardcode 颜色 / 自实现图表壳。
 */

/**
 * StackedRatioBar — 子卡底部"100% 占比条"装饰
 * 上方为小标题 + 图例（小圆点 + 名称），下方为按 value 拼接的横条。
 * 颜色统一从 dashboard data-* token 解析，禁止 hardcode。
 *
 * @param {{ title?: string, segments: Array<{ name: string, value: number, colorToken: string }> }} props
 */
/**
 * 解析 colorToken：支持 dashboard data-* token，也支持 #RGB / #RRGGBB / #RRGGBBAA hex
 * （8 位 hex 用于在不引入新 token 的前提下表达透明度变体）
 */
function resolveColor(colorToken) {
  const v = String(colorToken || '').trim();
  if (/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(v)) return v;
  return `var(${tokenNameToCssVar(v)})`;
}

export function StackedRatioBar({ title = '', segments = [] }) {
  const total = segments.reduce((sum, s) => sum + (Number(s.value) || 0), 0) || 1;
  return (
    <div className="flex w-full min-w-0 flex-col gap-2">
      {title ? (
        <span className="text-sm font-semibold leading-5 text-blueGrey-900">{title}</span>
      ) : null}
      <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
        {segments.map((s) => (
          <span key={s.name} className="inline-flex items-center gap-1 text-xs leading-4 text-blueGrey-700">
            <span
              className="inline-block h-1.5 w-1.5 shrink-0 rounded-full"
              style={{ background: resolveColor(s.colorToken) }}
            />
            {s.name}
          </span>
        ))}
      </div>
      <div className="flex h-2 w-full overflow-hidden rounded-full">
        {segments.map((s) => {
          const pct = ((Number(s.value) || 0) / total) * 100;
          return (
            <span
              key={s.name}
              style={{ width: `${pct}%`, background: resolveColor(s.colorToken) }}
              aria-label={`${s.name} ${pct.toFixed(1)}%`}
            />
          );
        })}
      </div>
    </div>
  );
}

/** chart slot 内的"图表 + 占比条"上下结构包装；图表整体 wrapper 固定 310，扣掉
 *  legend (~52) + 顶/底 margin (~24) + X 轴 (~32) 后，plot 实际绘图区 ≈ 210；占比条 hug。 */
export function ChartWithRatio({ chart, ratioTitle, ratioSegments }) {
  return (
    <div className="flex min-w-0 flex-col" style={{ gap: 12 }}>
      <div className="min-w-0" style={{ height: 310, flexShrink: 0 }}>{chart}</div>
      <div className="shrink-0">
        <StackedRatioBar title={ratioTitle} segments={ratioSegments} />
      </div>
    </div>
  );
}

const SENTIMENT_DATA = [
  { name: '正向', value: 12.5, colorToken: 'data-8' },
  { name: '中立', value: 12.5, colorToken: 'data-20' },
  { name: '轻微负向', value: 12.5, colorToken: '#FC7E9059' },
  { name: '中度负向', value: 25, colorToken: '#FC7E9099' },
  { name: '强烈负向', value: 25, colorToken: 'data-6' },
];

/** 反馈情绪 legend 仅显示三档主类别（正/中/负） */
const SENTIMENT_LEGEND = [
  { name: '正向', colorToken: 'data-8' },
  { name: '中立', colorToken: 'data-20' },
  { name: '负向', colorToken: 'data-6' },
];

/** 负向程度占比（与饼图三档负向色值一致） */
export const NEGATIVE_LEVEL_RATIO = [
  { name: '轻微负向', value: 12.5, colorToken: '#FC7E9059' },
  { name: '中度负向', value: 25, colorToken: '#FC7E9099' },
  { name: '强烈负向', value: 25, colorToken: 'data-6' },
];

const MEMBER_DATA = [
  { name: '标准版', monthly: 16, yearly: 6 },
  { name: '加强版', monthly: 14, yearly: 6 },
  { name: '专业版', monthly: 9, yearly: 6 },
];

const MEMBER_SERIES = [
  { type: 'bar', dataKey: 'monthly', name: '包月', colorToken: 'data-1', stackId: 'm' },
  { type: 'bar', dataKey: 'yearly', name: '包年', colorToken: 'data-4', stackId: 'm' },
];

/** 会员等级占比（页面 pattern 与 preview 共享） */
export const MEMBER_LEVEL_RATIO = [
  { name: 'L1', value: 22, colorToken: 'data-10' },
  { name: 'L2', value: 56, colorToken: 'data-13' },
  { name: 'L3', value: 22, colorToken: 'data-8' },
];

const DEVICE_DATA = [
  { name: 'iOS 13', value: 41, displayValue: '41%' },
  { name: 'Android 14', value: 26, displayValue: '26%' },
  { name: '鸿蒙 6.0', value: 15, displayValue: '15%' },
  { name: 'iOS 16.6', value: 7, displayValue: '7%' },
  { name: 'Android 16', value: 5, displayValue: '5%' },
];

/** 设备分布占比（页面 pattern 与 preview 共享） */
export const DEVICE_RATIO = [
  { name: 'iOS', value: 48, colorToken: 'data-8' },
  { name: '鸿蒙', value: 15, colorToken: 'data-3' },
  { name: 'Android', value: 31, colorToken: 'data-1' },
  { name: '其他', value: 6, colorToken: 'data-20' },
];

const WHITE_CARD = `rounded-xl bg-white ${DASHBOARD_CARD_PADDING_CLASS}`;
const SUMMARY_TEXT = '智能整体本周新增（约 3.32万），但互动率呈现明显"涨跌分化"；头部热点集中在智能体基础与逻辑实测，重复负反馈占比已超过 50%，建议优先治理高频问题。';

const FEATURE_OPTIONS = [
  { label: '反馈情绪分布', value: 'sentiment' },
  { label: '会员情况', value: 'member' },
  { label: '设备版本分布', value: 'device' },
];

const DEFAULT_FEATURE_IDS = FEATURE_OPTIONS.map((item) => item.value);

const PREVIEW_CARDS = [
  {
    id: 'sentiment',
    title: '反馈情绪分布',
    subtitle: '用户情绪倾向与负面原因拆解',
    chart: (
      <ChartWithRatio
        ratioTitle="负向程度"
        ratioSegments={NEGATIVE_LEVEL_RATIO}
        chart={
          <SmartPieChart
            spec={{
              data: SENTIMENT_DATA,
              config: {
                donut: true,
                showLabel: true,
                showLegend: true,
                legendPosition: 'top',
                fillContainer: true,
                legendItems: SENTIMENT_LEGEND,
              },
            }}
          />
        }
      />
    ),
  },
  {
    id: 'member',
    title: '会员情况',
    subtitle: '对于当前特征的解释说明对于当前特征的解释说明',
    chart: (
      <ChartWithRatio
        ratioTitle="会员等级"
        ratioSegments={MEMBER_LEVEL_RATIO}
        chart={
          <SmartComposedChart
            spec={{
              data: MEMBER_DATA,
              xAxisKey: 'name',
              series: MEMBER_SERIES,
              config: {
                showLegend: true,
                legendPosition: 'top',
                fillContainer: true,
                yAxisWidth: 36,
                margin: { left: 0, right: 0 },
              },
            }}
          />
        }
      />
    ),
  },
  {
    id: 'device',
    title: '设备版本分布',
    subtitle: '反馈来源的系统版本与机型占比',
    chart: (
      <ChartWithRatio
        ratioTitle="设备分布"
        ratioSegments={DEVICE_RATIO}
        chart={
          <SmartBarChart
            spec={{
              data: DEVICE_DATA,
              series: [{ dataKey: 'value', name: '反馈量', colorToken: 'data-8' }],
              config: {
                layout: 'horizontal',
                showLegend: true,
                legendPosition: 'top',
                showValueLabel: true,
                fillContainer: true,
                yAxisWidth: 64,
                margin: { left: 0, right: 0 },
              },
            }}
          />
        }
      />
    ),
  },
];

export default function FeatureCardGroupPreview({
  title = '核心反馈特征',
  subtitle = '围绕核心反馈，定位问题趋势',
  columns = 3,
  bare = false,
  cards = PREVIEW_CARDS,
  className = '',
}) {
  const [visibleFeatureIds, setVisibleFeatureIds] = useState(DEFAULT_FEATURE_IDS);
  const [featureDropdownOpen, setFeatureDropdownOpen] = useState(false);
  const featureDropdownRef = useRef(null);
  const visibleCards = useMemo(
    () => cards.filter((card) => !card.id || visibleFeatureIds.includes(card.id)),
    [cards, visibleFeatureIds],
  );

  useEffect(() => {
    if (!featureDropdownOpen) return undefined;

    const handlePointerDown = (event) => {
      if (featureDropdownRef.current?.contains(event.target)) return;
      setFeatureDropdownOpen(false);
    };
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') {
        setFeatureDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handlePointerDown);
    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('mousedown', handlePointerDown);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [featureDropdownOpen]);

  if (bare) {
    return (
      <FeatureCardGroup
        columns={columns}
        bare
        cards={visibleCards}
        className={className}
      />
    );
  }

  return (
    <section className={[WHITE_CARD, 'min-w-0', className].filter(Boolean).join(' ')}>
      <div className="flex flex-wrap items-center justify-between gap-2">
        <DashboardModuleTitle title={title} subtitle={subtitle} />
        <div ref={featureDropdownRef} className="relative">
          <Button
            variant="outline-black"
            size="md"
            icon={<Icon name="settings-04-stroked" size="sm" />}
            aria-haspopup="listbox"
            aria-expanded={featureDropdownOpen}
            onClick={() => setFeatureDropdownOpen((open) => !open)}
          >
            自定义特征
          </Button>
          {featureDropdownOpen ? (
            <div className="absolute right-0 top-full z-50 mt-1.5 w-[208px] overflow-hidden rounded-xl border border-border-default bg-white py-1 shadow-lg">
              <CheckboxGroup
                variant="black"
                size="md"
                value={visibleFeatureIds}
                onChange={(next) => setVisibleFeatureIds(next)}
                className="gap-0"
              >
                {FEATURE_OPTIONS.map((option) => (
                  <Checkbox
                    key={option.value}
                    value={option.value}
                    className="flex w-full items-center px-3 py-2 hover:bg-blueGrey-50 [&>span:last-child]:text-sm [&>span:last-child]:leading-5"
                  >
                    {option.label}
                  </Checkbox>
                ))}
              </CheckboxGroup>
            </div>
          ) : null}
        </div>
      </div>

      <div className="mt-3">
        <AISummaryPreview
          variant="chart-summary"
          title=""
          summaryText={SUMMARY_TEXT}
          showActions={false}
          expandable={false}
        />
      </div>

      <FeatureCardGroup
        columns={columns}
        bare
        cards={visibleCards}
        className="mt-3"
      />
    </section>
  );
}
