import { useMemo, useState } from 'react';
import { NavBar as NavBar } from '../b-end.js';
import { TagBar as TagBar } from '../b-end.js';
import { Filter as Filter } from '../b-end.js';
import { Tabs as Tabs } from '../b-end.js';
import { StrategyListPage } from '../b-end.js';
import SmartIndicator from '../../SmartIndicator.jsx';
import SmartRadarChart from '../../charts/SmartRadarChart';
import SmartGaugeChart from '../../charts/SmartGaugeChart';
import SmartPieChart from '../../charts/SmartPieChart';
import DashboardModuleTitle from '../components/DashboardModuleTitle';
import MultiMetricChartPreview from '../components/MultiMetricChartPreview';
import { DASHBOARD_CARD_PADDING_CLASS, DASHBOARD_PAGE_TITLE } from '../typography';
import bannerImage from '@/assets/customer-service-cockpit-banner.png';

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

const CHANNEL_OPTIONS = [
  { label: '全部渠道', value: 'all' },
  { label: '智能客服', value: 'bot' },
  { label: '人工坐席', value: 'human' },
  { label: '混合协同', value: 'hybrid' },
];

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

const CHANNEL_FACTOR = {
  all: 1,
  bot: 0.86,
  human: 0.71,
  hybrid: 1.08,
};

const TIME_POINT_COUNT = {
  '24h': 6,
  '7d': 7,
  custom: 14,
  '30d': 30,
};

/**
 * 主色策略：data-1 (#5DE4DD 青绿) 为驾驶舱主色（用户口中的 data3）；
 * 同色系搭配 data-0 (#24CDA5 深绿)、data-7 (#6EA1DA 蓝)、data-8 (#B399FE 紫蓝)、data-9 (#FC7E90 警示)。
 * 全部走 token 路径，禁止硬编码 hex；高位 (data-10+) 视场景使用，避免环境差异 fallback。
 */
const CATEGORY_META = [
  { id: 'consult', name: '咨询问答', colorToken: 'data-1', baseShare: 35, effectFactor: 1.08 },
  { id: 'refund', name: '退款售后', colorToken: 'data-0', baseShare: 23, effectFactor: 0.89 },
  { id: 'logistics', name: '物流履约', colorToken: 'data-7', baseShare: 18, effectFactor: 0.95 },
  { id: 'account', name: '账号权限', colorToken: 'data-8', baseShare: 14, effectFactor: 1.02 },
  { id: 'escalation', name: '升级投诉', colorToken: 'data-9', baseShare: 10, effectFactor: 0.82 },
];

/** 颜色优先序：Data 1 / 3 / 5 / 6 / 8（与看板色卡一致） */
const PREFERRED_DATA_COLORS = ['#70E5C0', '#5DE4DD', '#31CCFF', '#A399FE', '#91D6F7'];

/** 综合评分卡底部设备分布（标注4） */
const DEVICE_DISTRIBUTION = [
  { name: 'iOS', value: 42, color: PREFERRED_DATA_COLORS[0] },
  { name: '鸿蒙', value: 16, color: PREFERRED_DATA_COLORS[1] },
  { name: 'Android', value: 32, color: PREFERRED_DATA_COLORS[2] },
  { name: '其他', value: 10, color: PREFERRED_DATA_COLORS[3] },
];

const LEGEND_ITEM_CLASS = 'inline-flex items-center gap-1';
const LEGEND_DOT_CLASS = 'inline-block h-1.5 w-1.5 rounded-full';

/** 雷达系列：与下方 SmartRadarChart spec 共用，便于在卡片顶部展示同款图例 */
const RADAR_SERIES = [
  { dataKey: 'series_0', name: '当前表现', colorToken: 'data-1', color: '#5DE4DD' },
  { dataKey: 'series_1', name: '目标基线', colorToken: 'data-7', color: '#6EA1DA' },
];

const RADAR_DIMENSIONS = ['知识覆盖', '语义理解', '流程执行', '升级判定', '闭环追踪', '体验反馈'];

/** 与 SmartRadarChart / 预览注册表一致的六维不均衡 mock，避免围成「正六边形」 */
const COCKPIT_RADAR_DATA = RADAR_DIMENSIONS.map((name, idx) => ({
  name,
  series_0: [58, 64, 28, 66, 35, 52][idx],
  series_1: [72, 40, 45, 55, 78, 48][idx],
}));

function clamp(num, min, max) {
  return Math.min(max, Math.max(min, num));
}

function getDateLabels(count) {
  const now = new Date('2026-05-20T12:00:00');
  const labels = [];
  for (let i = count - 1; i >= 0; i -= 1) {
    const date = new Date(now);
    date.setDate(now.getDate() - i);
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    labels.push(`${month}.${day}`);
  }
  return labels;
}

function buildTrendData({ timeKey, channelKey, categoryId }) {
  const pointCount = TIME_POINT_COUNT[timeKey] || 7;
  const labels = getDateLabels(pointCount);
  const timeBoost = timeKey === '30d' ? 1.11 : timeKey === 'custom' ? 1.05 : timeKey === '24h' ? 0.84 : 1;
  const channelBoost = CHANNEL_FACTOR[channelKey] || 1;
  const selectedCategories = categoryId
    ? CATEGORY_META.filter((item) => item.id === categoryId)
    : CATEGORY_META;

  return labels.map((label, index) => {
    let sessionsTotal = 0;
    let resolvedSessions = 0;
    let transferSessions = 0;
    let pendingSessions = 0;
    let weightedFcr = 0;

    selectedCategories.forEach((cat, catIndex) => {
      const wave = 0.8 + Math.sin((index + 1 + catIndex * 1.5) / 1.9) * 0.2;
      const spike = index % 7 === 2 ? 1.18 : index % 7 === 5 ? 0.86 : 1;
      const categorySessions = 450 * (cat.baseShare / 10) * wave * spike * timeBoost * channelBoost;
      const categoryFcr = 67 + cat.effectFactor * 10 + Math.cos((index + catIndex * 1.1) / 1.8) * 4.2;
      const categoryTransferRate = clamp(0.13 + (1 - cat.effectFactor) * 0.16, 0.08, 0.28);
      const categoryPendingRate = clamp(0.09 + (1 - cat.effectFactor) * 0.1, 0.06, 0.2);
      const categoryResolved = categorySessions * clamp(categoryFcr / 100, 0.45, 0.93);
      const categoryTransfer = categorySessions * categoryTransferRate;
      const categoryPending = categorySessions * categoryPendingRate;

      sessionsTotal += categorySessions;
      resolvedSessions += categoryResolved;
      transferSessions += categoryTransfer;
      pendingSessions += categoryPending;
      weightedFcr += categorySessions * categoryFcr;
    });

    const resolvedFcr = sessionsTotal > 0 ? weightedFcr / sessionsTotal : 0;
    const unresolvedRate = sessionsTotal > 0 ? (pendingSessions / sessionsTotal) * 100 : 0;
    return {
      name: label,
      sessions: Math.round(sessionsTotal),
      resolvedSessions: Math.round(resolvedSessions),
      transferSessions: Math.round(transferSessions),
      pendingSessions: Math.round(pendingSessions),
      fcr: Number(clamp(resolvedFcr, 52, 92).toFixed(1)),
      unresolvedRate: Number(clamp(unresolvedRate, 4, 36).toFixed(1)),
    };
  });
}

export default function CustomerServiceOpsCockpitTestPattern() {
  const [channel, setChannel] = useState('all');
  const [timeRange, setTimeRange] = useState('7d');
  const [tagBarCollapsed, setTagBarCollapsed] = useState(false);
  const [expandedStrategyId, setExpandedStrategyId] = useState('s1');

  const trendData = useMemo(
    () => buildTrendData({ timeKey: timeRange, channelKey: channel }),
    [timeRange, channel],
  );

  const globalFactor = useMemo(() => {
    const channelBoost = CHANNEL_FACTOR[channel] || 1;
    const timeBoost = timeRange === '30d' ? 1.12 : timeRange === 'custom' ? 1.05 : timeRange === '24h' ? 0.84 : 1;
    return channelBoost * timeBoost;
  }, [channel, timeRange]);

  const totalSessions = useMemo(
    () => trendData.reduce((sum, item) => sum + item.sessions, 0),
    [trendData],
  );

  const avgFcr = useMemo(() => {
    if (trendData.length === 0) return 0;
    return trendData.reduce((sum, item) => sum + item.fcr, 0) / trendData.length;
  }, [trendData]);

  const kpiCards = useMemo(
    () => [
      {
        id: 'sessions',
        title: '总会话量',
        value: totalSessions.toLocaleString('en-US'),
        trendValue: `${(3.2 * globalFactor).toFixed(1)}%`,
        trendDirection: 'up',
        status: 'success',
        series: trendData.map((item) => ({ value: item.sessions / 100, at: item.name })),
      },
      {
        id: 'fcr',
        title: '一次解决率',
        value: `${avgFcr.toFixed(1)}%`,
        trendValue: `-${(1.1 * globalFactor).toFixed(1)}pp`,
        trendDirection: 'down',
        status: 'danger',
        series: trendData.map((item) => ({ value: item.fcr, at: item.name })),
      },
    ],
    [totalSessions, avgFcr, globalFactor, trendData],
  );

  const pieData = useMemo(() => {
    const boost = globalFactor;
    return CATEGORY_META.map((cat, index) => {
      const dynamic = 0.92 + Math.sin(index + totalSessions / 10000) * 0.07;
      return {
        name: cat.name,
        value: Math.round(cat.baseShare * 22 * boost * dynamic),
        colorToken: PREFERRED_DATA_COLORS[index % PREFERRED_DATA_COLORS.length],
      };
    });
  }, [globalFactor, totalSessions]);

  const gaugeScore = useMemo(
    () => Number(clamp(3.45 + globalFactor * 0.62 + (avgFcr - 70) * 0.012, 3.0, 5.0).toFixed(1)),
    [globalFactor, avgFcr],
  );

  const periodText = useMemo(() => {
    if (trendData.length === 0) return '统计周期：--';
    return `统计周期：${trendData[0].name} ~ ${trendData[trendData.length - 1].name}`;
  }, [trendData]);

  const activeTimeTabIndex = Math.max(
    0,
    TIME_TAB_ITEMS.findIndex((item) => item.value === timeRange),
  );

  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 顶部与右侧 Banner 顶部对齐 ── */}
          <header className="flex h-14 shrink-0 flex-nowrap items-center justify-between gap-3 px-1">
            <div className="flex min-w-0 items-center gap-3">
              <h2 className={`truncate ${DASHBOARD_PAGE_TITLE}`}>智能客服运营驾驶舱</h2>
              <Filter
                value={channel}
                onChange={(next) => setChannel(String(next))}
                options={CHANNEL_OPTIONS}
                label="渠道来源"
              />
            </div>
            <div className="flex shrink-0 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">
            <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">
                {/* 三列分组（核心指标 / 雷达 / 评分）属于同一语义层级：必须等高、底部对齐。
                    其余空间由内部图表通过 flex-1 + 自适应 SVG 吃掉，不允许卡片底部出现"硬空白"。 */}
                <section className="grid min-w-0 grid-cols-1 items-stretch gap-3 min-[1360px]:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)]">
                  {/* 标注1：第一列内 banner（背景 svg/png）与 KPI 拆为两张完全独立卡片 */}
                  <div className="flex h-full min-w-0 flex-col gap-3">
                    <article
                      className="relative overflow-hidden rounded-xl"
                      style={{ aspectRatio: '1024 / 230' }}
                    >
                      <img
                        src={bannerImage}
                        alt=""
                        aria-hidden="true"
                        className="absolute inset-0 h-full w-full object-cover"
                      />
                    </article>
                    <div className={`${WHITE_CARD} flex min-w-0 flex-1 flex-col overflow-hidden`}>
                      <DashboardModuleTitle title="核心指标" subtitle="平台核心 KPI 指标" />
                      <div
                        className="mt-3 grid min-w-0 flex-1 gap-3 content-stretch"
                        style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gridAutoRows: '1fr' }}
                      >
                        {kpiCards.map((item) => (
                          <SmartIndicator
                            key={item.id}
                            title={item.title}
                            value={item.value}
                            trend="较上周期"
                            trendValue={item.trendValue}
                            trendDirection={item.trendDirection}
                            status={item.status}
                            data={item.series}
                            layout="horizontal"
                            valueFontSize={22}
                            sparklineHeight={48}
                            style={{ width: '100%', minWidth: 0, maxWidth: '100%', overflow: 'hidden' }}
                          />
                        ))}
                      </div>
                    </div>
                  </div>

                  {/* 标注2：雷达图去图例 + 撑大；卡片上下空间富裕时，标题下方展示图例（与反馈情绪卡片一致） */}
                  <section className={`${WHITE_CARD} flex h-full min-w-0 flex-col overflow-hidden`}>
                    <DashboardModuleTitle title="服务能力雷达" subtitle="知识、流程、体验六维评估" />
                    <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-foreground-secondary">
                      {RADAR_SERIES.map((item) => (
                        <span key={item.name} className={LEGEND_ITEM_CLASS}>
                          <span
                            className={LEGEND_DOT_CLASS}
                            style={{ background: item.color }}
                          />
                          {item.name}
                        </span>
                      ))}
                    </div>
                    <div className="mt-1 min-w-0 flex-1">
                      <SmartRadarChart
                        spec={{
                          data: COCKPIT_RADAR_DATA,
                          series: RADAR_SERIES,
                          config: { height: 268, showLegend: false, maxValue: 90 },
                        }}
                      />
                    </div>
                  </section>

                  {/* 标注3 & 4：综合评分主色 data-1 (#5DE4DD) + 底部设备分布堆叠条
                      结构：标题 -> 仪表盘(flex-1, 居中, 自适应缩放) -> 设备分布(自然占位)
                      与同行其它卡等高时，由仪表盘吃掉多余高度（轻微等比放大），不会有硬空白 */}
                  <section className={`${WHITE_CARD} flex h-full min-w-0 flex-col overflow-hidden`}>
                    <DashboardModuleTitle title="综合评分" subtitle="按会话质量与策略效果加权" />
                    <div className="mt-1 flex min-h-0 min-w-0 flex-1 items-center justify-center">
                      <SmartGaugeChart
                        spec={{
                          value: gaugeScore,
                          min: 3,
                          max: 5,
                          tickValues: [3, 3.5, 4, 4.5, 5],
                          config: {
                            title: '服务评分',
                            progressColorToken: 'data-1',
                            trackColorToken: 'blueGrey-300',
                            animate: true,
                          },
                        }}
                      />
                    </div>
                    {/* 设备分布：自然贴在仪表盘下方 */}
                    <div className="mt-3 min-w-0">
                      <div className="mb-2 text-xs text-foreground-secondary">设备分布</div>
                      <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-foreground-secondary">
                        {DEVICE_DISTRIBUTION.map((item) => (
                          <span key={item.name} className={LEGEND_ITEM_CLASS}>
                            <span
                              className={LEGEND_DOT_CLASS}
                              style={{ background: item.color }}
                            />
                            {item.name}
                          </span>
                        ))}
                      </div>
                      <div className="mt-2 flex h-1.5 w-full overflow-hidden rounded-full">
                        {DEVICE_DISTRIBUTION.map((item) => (
                          <span
                            key={item.name}
                            style={{
                              width: `${item.value}%`,
                              background: item.color,
                            }}
                          />
                        ))}
                      </div>
                    </div>
                  </section>
                </section>

                {/* 第二行：以「会话趋势」卡片为高度基准等高对齐
                    - 会话趋势卡：内部含图表(308) + 表格 + 标题，自然高度作为基准
                    - 反馈情绪卡：环图通过 SmartPieChart 自适应缩放吃掉多余高度，可缩小 */}
                <section className="grid min-w-0 grid-cols-1 items-stretch gap-3 min-[1360px]:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)]">
                  <section className="min-w-0 h-full min-[1360px]:col-span-2">
                    <MultiMetricChartPreview
                      title="会话趋势与解决效率"
                      periodText={periodText}
                      totalPosts={`${(totalSessions / 10000).toFixed(2)}万`}
                      avgPosts={`${(totalSessions / Math.max(trendData.length, 1) / 10000).toFixed(2)}万`}
                      tablePanelWidth={340}
                      fillHeight
                    />
                  </section>

                  <section className={`${WHITE_CARD} flex min-w-0 h-full flex-col`}>
                    <header className="flex min-w-0 items-center justify-between gap-2">
                      <DashboardModuleTitle title="反馈情绪分布" subtitle="用户对话情绪结构" />
                    </header>
                    <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-foreground-secondary">
                      {pieData.map((item) => (
                        <span key={item.name} className={LEGEND_ITEM_CLASS}>
                          <span
                            className={LEGEND_DOT_CLASS}
                            style={{ background: item.colorToken }}
                          />
                          {item.name}
                        </span>
                      ))}
                    </div>
                    <div className="mt-1 flex min-h-0 min-w-0 flex-1 items-center justify-center overflow-hidden">
                      <SmartPieChart
                        spec={{
                          data: pieData,
                          config: {
                            donut: true,
                            showLegend: false,
                            showLabel: false,
                            legendPosition: 'top',
                            // 跟随父容器高度自适应（与"会话趋势卡"等高对齐时，环图自动放大/缩小）
                            fillContainer: true,
                            margin: { top: 10, right: 10, bottom: 10, left: 10 },
                          },
                        }}
                      />
                    </div>
                  </section>
                </section>

                {/* 策略管理：直接复用 b 端 StrategyListPage，自带标题/筛选/列表/分页；
                    dashboard 中作为一个区块直接放置在灰底上：
                    - 用 embedded 模式去掉 b 端基础页面框架自带的 16/16/16/0 外边距
                    - 与上方卡片之间靠外层 grid `gap-3` 统一控制，与页面右边距完全对齐 */}
                <section className="min-w-0">
                  <StrategyListPage embedded headerVariant="dashboard" />
                </section>
              </div>
              </div>
            </main>
          </div>
        </div>
      </div>
    </div>
  );
}
