import { useState } from 'react';
import { NavBar as NavBar } from '../b-end.js';
import { TagBar as TagBar } from '../b-end.js';
import { Input as Input } from '../b-end.js';
import { Icon as Icon } from '../b-end.js';
import { Tabs as Tabs } from '../b-end.js';
import { Table as Table } from '../b-end.js';
import { Filter as Filter } from '../b-end.js';
import SmartIndicator from '../../SmartIndicator.jsx';
import SmartPieChart from '../../charts/SmartPieChart';
import SmartBarChart from '../../charts/SmartBarChart';
import DashboardModuleTitle from '../components/DashboardModuleTitle';
import RankingCardPreview from '../components/RankingCardPreview';
import { DASHBOARD_CARD_PADDING_CLASS, DASHBOARD_PAGE_TITLE } from '../typography';

/**
 * AI 全功能链路看板（测试） — 监控 AI / 大模型对话 Case 健康度。
 * 顶部时间分段器 + 全局筛选（搜索 + Filter 下拉）+ 8 项 SmartIndicator（隐藏 sparkline）
 * + 三图表（图例统一下方）+ 问题聚类排行榜 + b-end Table 明细。
 *
 * 严格复用：b-end NavBar/TagBar/Input/Tabs/Filter/Tag/Table；
 *           dashboard SmartIndicator/SmartPieChart/SmartBarChart/DashboardModuleTitle。
 */

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

/* ── 筛选项 ── */
const ABNORMAL_OPTIONS = [
  { value: 'all', label: '全部' },
  { value: 'abnormal', label: '异常' },
  { value: 'normal', label: '正常' },
];
const PRIORITY_OPTIONS = [
  { value: 'all', label: '全部' },
  { value: 'p0', label: 'P0' },
  { value: 'p1', label: 'P1' },
  { value: 'p2', label: 'P2' },
];
const CALIBRATION_OPTIONS = [
  { value: 'all', label: '全部' },
  { value: 'pending', label: '待校准' },
  { value: 'done', label: '已校准' },
];
const ALIGNMENT_OPTIONS = [
  { value: 'all', label: '全部' },
  { value: 'consistent', label: '人机一致' },
  { value: 'inconsistent', label: '人机不一致' },
];

/* ── KPI 卡片 mock（无趋势数据） ── */
const KPI_CARDS = [
  { id: 'total',        title: '总 Case 数',    value: '738',   accentColorToken: 'blueGrey-700' },
  { id: 'normal',       title: '正常 Case 数',  value: '40',    status: 'success' },
  { id: 'abnormalRate', title: '异常率',        value: '94.6%', status: 'danger' },
  { id: 'abnormal',     title: '异常 Case 数',  value: '698',   status: 'danger' },
  { id: 'p0',           title: '严重告警 (P0)', value: '252',   status: 'danger' },
  { id: 'p1',           title: 'P1 告警',       value: '55',    accentColorToken: 'orange-500' },
  { id: 'p2',           title: 'P2 告警',       value: '391',   accentColorToken: 'orange-500' },
  { id: 'alignment',    title: '人工一致性',    value: '18',    accentColorToken: 'blueGrey-700' },
];

/* ── 一级维度分布（饼图） ── */
const DIMENSION_PIE = [
  { name: '安全性', value: 62, colorToken: 'data-0' },
  { name: '沟通',   value: 18, colorToken: 'data-1' },
  { name: '诊断',   value: 12, colorToken: 'data-7' },
  { name: '服务',   value: 6,  colorToken: 'data-8' },
  { name: '方案',   value: 2,  colorToken: 'data-9' },
];

/* ── 细分异常排行 Top 10（条形图） ── */
const TOP_REASONS = [
  { name: '回复不完整',     series_0: 99 },
  { name: '回复突兀',       series_0: 51 },
  { name: '参考过低',       series_0: 23 },
  { name: '查错信息',       series_0: 16 },
  { name: '幻觉信息',       series_0: 13 },
  { name: '解决方案缺失',   series_0: 9 },
  { name: '反馈拒识',       series_0: 7 },
  { name: '问题上报偏差',   series_0: 5 },
  { name: '消极人工',       series_0: 3 },
  { name: '未触发知识',     series_0: 2 },
];

/* ── 人群一致性（饼图） ── */
const ALIGNMENT_PIE = [
  { name: '待校准',    value: 38, colorToken: 'data-1' },
  { name: '模型判断',  value: 24, colorToken: 'data-0' },
  { name: '分类偏差',  value: 18, colorToken: 'data-7' },
  { name: '已校准',    value: 12, colorToken: 'data-8' },
  { name: '人机一致',  value: 8,  colorToken: 'data-9' },
];

/* ── 问题聚类排行榜 ── */
const PROBLEM_CLUSTERS = [
  { id: 'c1', rank: 1, title: '正常',          total: 344, pending: 344 },
  { id: 'c2', rank: 2, title: '不回复 / 回复不完整', total: 92,  pending: 64 },
  { id: 'c3', rank: 3, title: '回复突兀',      total: 70,  pending: 30 },
  { id: 'c4', rank: 4, title: '运行日志缺失',  total: 41,  pending: 18 },
  { id: 'c5', rank: 5, title: '查错信息',      total: 22,  pending: 9 },
  { id: 'c6', rank: 6, title: '参考过低',      total: 16,  pending: 6 },
  { id: 'c7', rank: 7, title: '幻觉信息',      total: 13,  pending: 5 },
  { id: 'c8', rank: 8, title: '解决方案缺失',  total: 9,   pending: 4 },
];

const PROBLEM_CLUSTER_ITEMS = PROBLEM_CLUSTERS.map((c) => ({
  rank: c.rank,
  title: c.title,
  metrics: [
    { label: '总计', value: String(c.total) },
    { label: '待校准', value: String(c.pending), valueColor: '#F2496F' },
  ],
}));

/* ── 明细表 mock（字段结构对齐 B 端 Table 列 type） ── */
const CASE_TABLE_SOURCE = [
  { id: '4858676825', priority: 'None', abnormalType: '正常', firstQuery: '主播直播时打开关闭麦克风/静音', calibrationStatus: '待校准' },
  { id: '4858157252', priority: 'None', abnormalType: '正常', firstQuery: '怎么发出直播',                       calibrationStatus: '待校准' },
  { id: '4858182708', priority: 'None', abnormalType: '正常', firstQuery: '怎么直播直播间可见范围',             calibrationStatus: '待校准' },
  { id: '4858094828', priority: 'None', abnormalType: '正常', firstQuery: '怎么试播',                           calibrationStatus: '待校准' },
  { id: '4858023491', priority: 'P1',   abnormalType: '回复突兀', firstQuery: '直播被限流是什么原因',           calibrationStatus: '待校准' },
  { id: '4857991201', priority: 'P0',   abnormalType: '不回复',   firstQuery: '直播间无法进入怎么办',           calibrationStatus: '已校准' },
  { id: '4857880513', priority: 'P2',   abnormalType: '查错信息', firstQuery: '认证失败如何重新提交资料',       calibrationStatus: '待校准' },
];

const PRIORITY_TAG_VARIANT = {
  P0: 'red',
  P1: 'orange',
  P2: 'yellow',
  None: 'grey',
};

const ABNORMAL_TAG_VARIANT = {
  正常: 'green',
  '不回复': 'red',
  '回复突兀': 'orange',
  '查错信息': 'yellow',
};

function toTagCell(label, variant) {
  return [{ label, variant }];
}

const CASE_TABLE_ROWS = CASE_TABLE_SOURCE.map((row) => ({
  ...row,
  priority: toTagCell(row.priority, PRIORITY_TAG_VARIANT[row.priority] || 'grey'),
  abnormalType: toTagCell(row.abnormalType, ABNORMAL_TAG_VARIANT[row.abnormalType] || 'grey'),
  actions: [{ key: 'detail', label: '查看详情', onClick: () => {} }],
}));

const CASE_TABLE_COLUMNS = [
  { key: 'id', dataIndex: 'id', title: 'CaseID', type: 'text', width: 140 },
  { key: 'priority', dataIndex: 'priority', title: '优先级', type: 'tag', width: 100 },
  { key: 'abnormalType', dataIndex: 'abnormalType', title: '异常表现型', type: 'tag', width: 140 },
  { key: 'firstQuery', dataIndex: 'firstQuery', title: '首句用户问题', type: 'text', minWidth: 240 },
  {
    key: 'calibrationStatus',
    dataIndex: 'calibrationStatus',
    title: '校准状态',
    type: 'text',
    width: 120,
    render: (val) => (
      <span className={val === '待校准' ? 'text-orange-500' : 'text-green-500'}>{val}</span>
    ),
  },
  { key: 'actions', dataIndex: 'actions', title: '操作', type: 'actions', width: 120 },
];

export default function AIFullLinkDashboardTestPattern() {
  const [keyword, setKeyword] = useState('');
  const [abnormal, setAbnormal] = useState('all');
  const [priority, setPriority] = useState('all');
  const [calibration, setCalibration] = useState('pending');
  const [alignment, setAlignment] = useState('inconsistent');
  const [selectedKpi, setSelectedKpi] = useState('abnormalRate');
  const [tagBarCollapsed, setTagBarCollapsed] = useState(false);

  return (
    <div className="h-full w-full min-w-0 overflow-hidden bg-blueGrey-200">
      <div className="flex h-full min-h-0">
        <div className="h-full shrink-0">
          <NavBar platform="ola" showUtilityActions />
        </div>

        <div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden py-3 pr-3">
          {/* ── 顶栏：标题 + 全局时间分段器，跨 TagBar 与主区整宽，确保 TagBar 顶部与右侧内容顶部对齐 ── */}
          <header className="flex h-14 shrink-0 flex-nowrap items-center justify-between gap-3 px-1">
            <h2 className={`min-w-0 flex-1 truncate ${DASHBOARD_PAGE_TITLE}`}>
              AI 全功能链路看板（测试）
            </h2>
            <Tabs
              className="shrink-0"
              variant="segment"
              size="sm"
              items={[
                { label: '近 24 小时' },
                { label: '近 7 天' },
                { label: '近 30 天' },
              ]}
              defaultIndex={1}
            />
          </header>

          <div className="flex min-h-0 min-w-0 flex-1 gap-3 overflow-hidden">
            <aside
              className="dashboard-scrollbar-hide flex h-full shrink-0 flex-col overflow-hidden rounded-xl bg-white transition-[width] duration-200 ease-out"
              style={{ width: tagBarCollapsed ? 72 : 250 }}
            >
              <TagBar
                tone="transparent"
                resizable={false}
                collapsed={tagBarCollapsed}
                onCollapsedChange={setTagBarCollapsed}
                className="!h-full min-h-0 flex-1 !border-r-0"
                style={{ width: '100%', background: 'transparent' }}
              />
            </aside>

            <main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
            <div className="dashboard-scrollbar-hide min-h-0 flex-1 overflow-y-auto">
              <div className="flex min-w-0 flex-col gap-3 pb-1">
                {/* 第一部分：核心指标 8 卡（SmartIndicator hideSparkline） */}
                <section className={`${WHITE_CARD} min-w-0`}>
                  <header className="flex min-w-0 flex-wrap items-start justify-between gap-3">
                    <DashboardModuleTitle title="核心指标" subtitle="平台 AI 对话健康度大盘" className="shrink-0" />
                    <div className="flex min-w-0 flex-1 flex-wrap items-center justify-end gap-2">
                      <Input
                        value={keyword}
                        onChange={(e) => setKeyword(e.target.value)}
                        placeholder="搜索 CaseID / 用户首句 / 异常原因"
                        prefix={<Icon name="search-md-stroked" />}
                        allowClear
                        style={{ flex: '0 1 320px', width: '320px', minWidth: '240px', '--size-input-width': '100%' }}
                      />
                      <Filter
                        label="是否异常"
                        value={abnormal}
                        onChange={(next) => setAbnormal(String(next))}
                        options={ABNORMAL_OPTIONS}
                      />
                      <Filter
                        label="优先级"
                        value={priority}
                        onChange={(next) => setPriority(String(next))}
                        options={PRIORITY_OPTIONS}
                      />
                      <Filter
                        label="人工校准"
                        value={calibration}
                        onChange={(next) => setCalibration(String(next))}
                        options={CALIBRATION_OPTIONS}
                      />
                      <Filter
                        label="人机一致"
                        value={alignment}
                        onChange={(next) => setAlignment(String(next))}
                        options={ALIGNMENT_OPTIONS}
                      />
                    </div>
                  </header>
                  <div className="mt-4 grid min-w-0 grid-cols-2 gap-3 min-[920px]:grid-cols-4 min-[1280px]:grid-cols-8">
                    {KPI_CARDS.map((kpi) => (
                      <SmartIndicator
                        key={kpi.id}
                        title={kpi.title}
                        value={kpi.value}
                        layout="vertical"
                        hideSparkline
                        status={kpi.status}
                        accentColorToken={kpi.accentColorToken}
                        selected={selectedKpi === kpi.id}
                        onClick={() => setSelectedKpi(kpi.id)}
                        titleTooltip=""
                      />
                    ))}
                  </div>
                </section>

                {/* 第二部分：图表分析 一行三块；环图显示外部扇形标签，三图都保留底部图例 */}
                <section className="grid min-w-0 grid-cols-1 items-stretch gap-3 min-[1200px]:grid-cols-3">
                  {/* 一级维度分布 — 环形图 */}
                  <div className={`${WHITE_CARD} flex h-full min-w-0 flex-col`}>
                    <DashboardModuleTitle title="一级维度分布" subtitle="顶层业务维度占比" />
                    <div className="mt-4 min-h-[420px] min-w-0 flex-1">
                      <SmartPieChart
                        spec={{
                          data: DIMENSION_PIE,
                          config: {
                            donut: true,
                            showLegend: true,
                            showLabel: true,
                            labelLayoutMode: 'smart',
                            compactSmallSlices: false,
                            hideOverflowLabels: false,
                            balanceLabelSides: true,
                            labelSideOverrides: { 方案: 'right' },
                            labelBendOffset: 10,
                            labelEndOffset: 26,
                            labelMinGap: 6,
                            labelBandPadding: 14,
                            legendPosition: 'bottom',
                            fillContainer: true,
                            height: 360,
                          },
                        }}
                      />
                    </div>
                  </div>

                  {/* 细分异常排行 Top 10 — 横向条形图 */}
                  <div className={`${WHITE_CARD} flex h-full min-w-0 flex-col`}>
                    <DashboardModuleTitle title="细分异常排行 Top 10" subtitle="异常原因触发频次降序" />
                    <div className="mt-4 min-h-[420px] min-w-0 flex-1">
                      <SmartBarChart
                        spec={{
                          data: TOP_REASONS,
                          series: [
                            { dataKey: 'series_0', name: '触发次数', colorToken: 'data-0' },
                          ],
                          config: {
                            layout: 'horizontal',
                            stack: false,
                            showLegend: true,
                            legendPosition: 'bottom',
                            showLabel: true,
                            showXAxis: true,
                            showYAxis: true,
                            fillContainer: true,
                            cornerMode: 'rounded',
                            height: 360,
                            margin: { top: 8, right: 16, bottom: 8, left: 0 },
                            yAxisWidth: 84,
                            yAxisCategoryPadding: { top: 0, bottom: 0 },
                          },
                        }}
                      />
                    </div>
                  </div>

                  {/* 人群一致性 — 环形图 */}
                  <div className={`${WHITE_CARD} flex h-full min-w-0 flex-col`}>
                    <DashboardModuleTitle title="人群一致性" subtitle="校准动作与状态比例" />
                    <div className="mt-4 min-h-[420px] min-w-0 flex-1">
                      <SmartPieChart
                        spec={{
                          data: ALIGNMENT_PIE,
                          config: {
                            donut: true,
                            showLegend: true,
                            showLabel: true,
                            labelLayoutMode: 'smart',
                            compactSmallSlices: false,
                            hideOverflowLabels: false,
                            balanceLabelSides: true,
                            labelBendOffset: 10,
                            labelEndOffset: 26,
                            labelMinGap: 6,
                            labelBandPadding: 14,
                            legendPosition: 'bottom',
                            fillContainer: true,
                            height: 360,
                          },
                        }}
                      />
                    </div>
                  </div>
                </section>

                {/* 第三部分：下钻排查 — 左列与「一级维度分布」同宽（1/3），右表 2/3 */}
                <section className="grid min-w-0 grid-cols-1 items-stretch gap-3 min-[1200px]:grid-cols-3">
                  {/* 问题聚类排行榜 — 复用榜单卡片 RankingCardPreview（embedded） */}
                  <div className={`${WHITE_CARD} flex h-full min-w-0 flex-col min-[1200px]:col-span-1`}>
                    <DashboardModuleTitle title="问题聚类排行榜" subtitle="按问题类别聚类" />
                    <div className="mt-4 min-w-0 flex-1">
                      <RankingCardPreview embedded items={PROBLEM_CLUSTER_ITEMS} />
                    </div>
                  </div>

                  {/* 渠道指标分析明细 — b-end Table */}
                  <div className={`${WHITE_CARD} flex h-full min-w-0 flex-col min-[1200px]:col-span-2`}>
                    <DashboardModuleTitle title="渠道指标分析" subtitle="Case 下钻排查明细" />
                    <div className="b-end-table-embed mt-4 min-h-[360px] min-w-0 flex-1">
                      <Table
                        className="h-full"
                        columns={CASE_TABLE_COLUMNS}
                        dataSource={CASE_TABLE_ROWS}
                        rowKey="id"
                        pagination={{
                          current: 1,
                          pageSize: 10,
                          total: 698,
                          pageSizeOptions: [10, 20, 50],
                        }}
                      />
                    </div>
                  </div>
                </section>
              </div>
            </div>
            </main>
          </div>
        </div>
      </div>
    </div>
  );
}
