import { useEffect, useMemo, useRef, useState } from 'react';
import { NavBar as NavBar } from '../b-end.js';
import { Filter as Filter } from '../b-end.js';
import { Tabs as Tabs } from '../b-end.js';
import { Button as Button } from '../b-end.js';
import { Icon as Icon } from '../b-end.js';
import CheckboxGroup, { Checkbox } from '@/data/systems/b-end/components/Checkbox';
import { StrategyListPage } from '../b-end.js';
import SmartIndicator from '../../SmartIndicator.jsx';
import SmartPieChart from '../../charts/SmartPieChart';
import SmartBarChart from '../../charts/SmartBarChart';
import SmartComposedChart from '../../charts/SmartComposedChart';
import DashboardModuleTitle from '../components/DashboardModuleTitle';
import AISummaryPreview from '../components/AISummaryPreview';
import FeatureCardGroup from '../components/FeatureCardGroup';
import { ChartWithRatio, MEMBER_LEVEL_RATIO, DEVICE_RATIO } from '../components/FeatureCardGroupPreview';
import { DASHBOARD_CARD_PADDING_CLASS } from '../typography';

/**
 * 用户画像看板（Persona Dashboard）
 *
 * 设计目标：示范"同一主题、不同维度的图表共享一张大白卡"的聚合卡组织方式，
 *           对比此前"每图一张白卡"的离散摆放，强化语义聚合、减少视觉碎片。
 *
 * 结构：
 *   1. 顶栏（跨整宽）：Tabs 切换（全网热点 / 站内反馈）+ 渠道 Filter + 媒体 Filter + 时间分段器
 *   2. 主区
 *      - 大白卡①「用户标签数据」：6 张带 sparkline 的 SmartIndicator，平铺在同一卡内
 *      - 大白卡②「核心反馈特征」：AI 摘要 + 一行三图（反馈情绪 / 会员情况 / 设备版本）
 *      - 大白卡③「策略管理」：复用 b-end StrategyListPage embedded 模式
 *
 * 严格复用：b-end NavBar/Filter/Tabs/Button/Checkbox；
 *           dashboard SmartIndicator/SmartPieChart/SmartBarChart/SmartComposedChart/AISummaryPreview/DashboardModuleTitle。
 */

const WHITE_CARD = `rounded-xl bg-white ${DASHBOARD_CARD_PADDING_CLASS}`;

const PAGE_TABS = [
  { label: '全网热点' },
  { label: '站内反馈' },
];

const CHANNEL_OPTIONS = [
  { label: '全部渠道', value: 'all' },
  { label: '抖音', value: 'douyin' },
  { label: '小红书', value: 'xhs' },
  { label: 'Bilibili', value: 'bili' },
];

const MEDIA_OPTIONS = [
  { label: 'App 端', value: 'app' },
  { label: 'Web 端', value: 'web' },
  { label: '小程序', value: 'mini' },
];

const TIME_TAB_ITEMS = [
  { label: '近 24 小时', value: '24h' },
  { label: '近 7 天', value: '7d' },
  { label: '近 30 天', value: '30d' },
  { label: '自定义', value: 'custom' },
];

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

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

/* ── 用户标签 KPI（4 张横向 KPI 卡：title 在上，value+trend 在下，sparkline 在右上；
       节省顶部空间，避免顶部一行占用过高） ──
   sparkline 使用与 SmartIndicatorPreview DEFAULT_CARD_ROWS 一致的 17 点预设波形，
   保证幅度/形态与组件默认形态对齐，禁止自造 sin 波形。 */
const SPARK_PRESETS = [
  [{ value: 68 }, { value: 74 }, { value: 59 }, { value: 62 }, { value: 48 }, { value: 66 }, { value: 79 }, { value: 56 }, { value: 64 }, { value: 64 }, { value: 69 }, { value: 55 }, { value: 72 }, { value: 66 }, { value: 82 }, { value: 70 }, { value: 67 }],
  [{ value: 66 }, { value: 73 }, { value: 61 }, { value: 64 }, { value: 52 }, { value: 70 }, { value: 81 }, { value: 58 }, { value: 67 }, { value: 61 }, { value: 72 }, { value: 58 }, { value: 76 }, { value: 69 }, { value: 83 }, { value: 71 }, { value: 75 }],
  [{ value: 58 }, { value: 66 }, { value: 54 }, { value: 60 }, { value: 49 }, { value: 67 }, { value: 79 }, { value: 55 }, { value: 64 }, { value: 58 }, { value: 70 }, { value: 57 }, { value: 74 }, { value: 66 }, { value: 81 }, { value: 68 }, { value: 73 }],
];

const PERSONA_KPI_CARDS = [
  { id: 'commercial', title: '会员商业化 Commercial', value: '857', trend: '环比', trendValue: '11.12%', trendDirection: 'up',   status: 'success', sparkline: SPARK_PRESETS[1] },
  { id: 'legal',      title: '风险合规 Legal',        value: '857', trend: '环比', trendValue: '11.12%', trendDirection: 'up',   status: 'success', sparkline: SPARK_PRESETS[2] },
  { id: 'model',      title: '模型效果 Model',        value: '857', trend: '环比', trendValue: '11.12%', trendDirection: 'up',   status: 'success', sparkline: SPARK_PRESETS[0] },
  { id: 'safety',     title: '性能问题 Performance',  value: '432', trend: '环比', trendValue: '11.12%', trendDirection: 'down', status: 'danger',  sparkline: SPARK_PRESETS[1] },
];

/* ── 反馈情绪分布（5 段，颜色严格按情绪语义：正向→绿、中立→灰、负向→粉系渐深） ── */
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' },
];

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

/* ── 会员情况（堆叠柱：包月/包年 × 3 版本） ── */
const MEMBER_DATA = [
  { name: '标准版', monthly: 16, yearly: 6 },
  { name: '加强版', monthly: 14, yearly: 6 },
  { name: '专业版', monthly: 9,  yearly: 6 },
];

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

/* ── 设备版本分布（横向条形） ── */
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%' },
];

export default function UserPersonaDashboardPattern() {
  const [activeTopTab, setActiveTopTab] = useState(1); // 站内反馈
  const [channel, setChannel] = useState('all');
  const [media, setMedia] = useState('app');
  const [timeRange, setTimeRange] = useState('7d');
  const [selectedKpi, setSelectedKpi] = useState('commercial');
  const [visibleFeatureIds, setVisibleFeatureIds] = useState(DEFAULT_FEATURE_IDS);
  const [featureDropdownOpen, setFeatureDropdownOpen] = useState(false);
  const featureDropdownRef = useRef(null);

  const activeTimeTabIndex = useMemo(
    () => TIME_TAB_ITEMS.findIndex((it) => it.value === timeRange),
    [timeRange],
  );

  const featureCards = useMemo(() => [
    {
      id: 'sentiment',
      title: '反馈情绪分布',
      subtitle: '用户情绪倾向与负面原因拆解',
      chart: (
        <ChartWithRatio
          ratioTitle="负向程度"
          ratioSegments={NEGATIVE_LEVEL_RATIO}
          chart={
            <SmartPieChart
              spec={{
                data: SENTIMENT_DATA,
                config: {
                  donut: true,
                  showLabel: true,
                  labelLayoutMode: 'legacy',
                  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 },
                },
              }}
            />
          }
        />
      ),
    },
  ], []);

  const visibleFeatureCards = useMemo(
    () => featureCards.filter((card) => visibleFeatureIds.includes(card.id)),
    [featureCards, 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]);

  return (
    <div className="dashboard-shell flex h-full min-h-0 min-w-0 w-full self-stretch flex-col overflow-hidden bg-blueGrey-200" data-system="dashboard">
      <div className="flex h-full min-h-0 flex-1 overflow-hidden">
        <NavBar />

        <div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden py-3 pr-3">
          {/* ── 顶栏：跨 TagBar + main 整宽，含 Tabs + 渠道/媒体筛选 + 时间分段器（LAYOUT_RULES §6.2） ── */}
          <header className="flex shrink-0 flex-wrap items-center justify-between gap-3 px-1 pb-3">
            <div className="flex min-w-0 flex-wrap items-center gap-3">
              <Tabs
                variant="pill"
                size="sm"
                items={PAGE_TABS}
                activeIndex={activeTopTab}
                onChange={(idx) => setActiveTopTab(idx)}
              />
              <Filter
                value={channel}
                onChange={(next) => setChannel(String(next))}
                options={CHANNEL_OPTIONS}
                label="渠道来源"
              />
              <Filter
                value={media}
                onChange={(next) => setMedia(String(next))}
                options={MEDIA_OPTIONS}
                label="媒体类型"
              />
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <Tabs
                variant="segment"
                size="sm"
                items={TIME_TAB_ITEMS}
                activeIndex={activeTimeTabIndex}
                onChange={(index) => setTimeRange(TIME_TAB_ITEMS[index]?.value || '7d')}
              />
            </div>
          </header>

          <div className="flex min-h-0 min-w-0 flex-1 gap-3 overflow-hidden">
            <main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
              <div className="dashboard-scrollbar-hide flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">

                {/* 大白卡①：用户标签数据 — 4 张横向 KPI 卡平铺一行（节省顶部空间）
                    指标卡使用 SmartIndicator vertical 默认形态：自带 #F9FAFB 浅灰底 + 12px 圆角，与外层白卡形成层级；
                    卡间距走 dashboard 默认 gap-3 (12px)；卡片宽度由 grid 列宽决定（style.width 强制 100% 覆盖默认 206px hug）。 */}
                <section className={`${WHITE_CARD} min-w-0`}>
                  <DashboardModuleTitle title="用户标签数据" subtitle="统计周期：2024-01-02 - 2024-01-08" />
                  <div className="mt-4 grid min-w-0 grid-cols-2 gap-3 min-[720px]:grid-cols-4">
                    {PERSONA_KPI_CARDS.map((kpi) => (
                      <SmartIndicator
                        key={kpi.id}
                        title={kpi.title}
                        value={kpi.value}
                        trend={kpi.trend}
                        trendValue={kpi.trendValue}
                        trendDirection={kpi.trendDirection}
                        layout="horizontal"
                        status={kpi.status || 'success'}
                        data={kpi.sparkline}
                        selected={selectedKpi === kpi.id}
                        onClick={() => setSelectedKpi(kpi.id)}
                        style={{ width: '100%', minWidth: 0 }}
                      />
                    ))}
                  </div>
                </section>

                {/* 大白卡②：核心反馈特征 — AI 摘要 + 一行三图（反馈情绪 / 会员情况 / 设备版本）共享一卡 */}
                <section className={`${WHITE_CARD} min-w-0`}>
                  <div className="flex flex-wrap items-center justify-between gap-2">
                    <DashboardModuleTitle title="核心反馈特征" 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>

                  {/* AI 摘要条 — 图表级 chart-summary（页面级 page-summary 仅用于"整页一张白卡"的 A 型布局） */}
                  <div className="mt-3">
                    <AISummaryPreview
                      variant="chart-summary"
                      title=""
                      summaryText='智能整体本周新增（约 3.32万），但互动率呈现明显"涨跌分化"；头部热点集中在智能体基础与逻辑实测，重复负反馈占比已超过 50%，建议优先治理高频问题。'
                      showActions={false}
                      expandable={false}
                    />
                  </div>

                  {/* 一行三图：图表语义同属"反馈特征"，统一由 FeatureCardGroup（bare）承载，
                      子卡视觉契约（#FCFCFD 底 + 0.4px 边 + 24px 上下内距 + min-h 240）由组件内部保证。 */}
                  {visibleFeatureCards.length > 0 ? (
                    <FeatureCardGroup
                      bare
                      columns={Math.min(visibleFeatureCards.length, 3)}
                      className="mt-3"
                      cards={visibleFeatureCards}
                    />
                  ) : null}
                </section>

                {/* 大白卡③：策略管理 — 复用 b-end StrategyListPage embedded 模式；
                    该区块跟随主内容宽度自适应，不恢复旧版"三级问题标签"绿色占比条。 */}
                <section className="min-w-0">
                  <StrategyListPage embedded headerVariant="dashboard" />
                </section>

              </div>
            </main>
          </div>
        </div>
      </div>
    </div>
  );
}
