import { useMemo, useState } from 'react';
import { Button as Button } from '../b-end.js';
import { Filter as Filter } from '../b-end.js';
import { Icon as Icon } from '../b-end.js';
import { NavBar as NavBar } from '../b-end.js';
import { TagBar as TagBar } from '../b-end.js';
import ProportionBarCardPreview from '../components/ProportionBarCardPreview';
import BulletChartTablePreview from '../components/BulletChartTablePreview';
import ProgressIndicatorCardPreview from '../components/ProgressIndicatorCardPreview';
import DashboardModuleTitle from '../components/DashboardModuleTitle';
import ServiceDataTrendChart from '../components/ServiceDataTrendChart';
import { DASHBOARD_CARD_PADDING_CLASS, DASHBOARD_PAGE_TITLE } from '../typography';

const MAIN_DATA_CARD = `rounded-xl bg-surface ${DASHBOARD_CARD_PADDING_CLASS}`;

const CORE_METRIC_ITEMS = [
  {
    id: 'resolve-rate',
    title: '日均智能解决率',
    titleTooltip: '智能解决率 = 智能解决会话数 / 日均总会话数',
    value: '30.7%',
    trendLabel: '环比',
    trendValue: '11.12pp',
    trendDirection: 'down',
    barPercent: 61,
    status: 'success',
    lineColorToken: 'data-0',
    trendDataKey: 'resolveRate',
  },
  {
    id: 'transfer-rate',
    title: '日均智能转人工率',
    titleTooltip: '智能转人工率 = 转人工会话数 / 日均总会话数',
    value: '45.8%',
    trendLabel: '环比',
    trendValue: '11.12pp',
    trendDirection: 'down',
    barPercent: 70,
    status: 'success',
    lineColorToken: 'data-2',
    trendDataKey: 'transferRate',
  },
  {
    id: 'manual-resolve',
    title: '日均人工解决率',
    titleTooltip: '人工解决率 = 人工解决会话数 / 日均人工会话数',
    value: '28.6%',
    trendLabel: '环比',
    trendValue: '11.12pp',
    trendDirection: 'up',
    barPercent: 55,
    status: 'danger',
    lineColorToken: 'data-3',
    trendDataKey: 'manualResolve',
  },
  {
    id: 'manual-policy',
    title: '转人工策略率',
    titleTooltip: '转人工策略率 = 策略触发转人工数 / 日均转人工总数',
    value: '33.6%',
    trendLabel: '环比',
    trendValue: '11.12pp',
    trendDirection: 'down',
    barPercent: 52,
    status: 'success',
    lineColorToken: 'data-4',
    trendDataKey: 'manualPolicy',
  },
];

/** 转人工策略率（manualPolicy）与智能转人工率（transferRate）数值拉开，避免折线叠在一起 */
const TREND_DATA = [
  { name: '0501', resolveRate: 28.4, transferRate: 42.6, manualResolve: 25.2, manualPolicy: 31.2 },
  { name: '0502', resolveRate: 24.7, transferRate: 38.8, manualResolve: 22.6, manualPolicy: 28.4 },
  { name: '0503', resolveRate: 32.1, transferRate: 45.9, manualResolve: 27.3, manualPolicy: 33.6 },
  { name: '0504', resolveRate: 23.8, transferRate: 39.9, manualResolve: 21.9, manualPolicy: 29.1 },
  { name: '0505', resolveRate: 31.2, transferRate: 46.3, manualResolve: 26.9, manualPolicy: 34.8 },
  { name: '0506', resolveRate: 33.6, transferRate: 48.2, manualResolve: 29.7, manualPolicy: 36.2 },
  { name: '0507', resolveRate: 30.8, transferRate: 45.8, manualResolve: 28.6, manualPolicy: 33.5 },
];

/** 与热点监控大屏模块标题右侧说明占位一致 */
const MODULE_SUBTITLE_PLACEHOLDER = '说明文字占位说明文字占位说明文字占位';

export default function ServiceDataScreenPattern() {
  const [selectedMetricId, setSelectedMetricId] = useState('resolve-rate');
  const [tagBarCollapsed, setTagBarCollapsed] = useState(false);

  const handleMetricSelect = (id) => {
    setSelectedMetricId(id);
  };

  const chartSeries = useMemo(() => {
    const toSeries = (item) => ({
      dataKey: item.trendDataKey,
      name: item.title,
      colorToken: item.lineColorToken,
    });
    const focused = CORE_METRIC_ITEMS.find((item) => item.id === selectedMetricId);
    return [toSeries(focused || CORE_METRIC_ITEMS[0])];
  }, [selectedMetricId]);

  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-2 pr-2">
          {/* ── 顶栏：标题 + 筛选/操作，跨 TagBar 与主区整宽，确保 TagBar 顶部与右侧内容顶部对齐 ── */}
          <header className="flex h-14 shrink-0 items-center justify-between gap-3 px-1">
            <div className={`inline-flex min-w-0 items-center gap-1 ${DASHBOARD_PAGE_TITLE}`}>
              <span className="truncate">服务数据</span>
            </div>
            <div className="flex shrink-0 items-center gap-3">
              <Button variant="outline-black" size="md">
                关联分析
              </Button>
              <Filter
                label="筛选"
                options={['全部', '本周', '本月', '本季度', '本年']}
                defaultValue={'全部'}
              />
              <Button
                variant="outline-black"
                size="md"
                iconOnly
                icon={<Icon name="dots-horizontal-stroked" size="sm" />}
                aria-label="更多"
              />
              <Button variant="outline-black" size="md">
                <span className="inline-flex items-center gap-1 truncate">
                  最近 14 天（2023-03-01 ~ 2023-03-24）
                  <Icon name="chevron-down-stroked" size="sm" className="shrink-0" />
                </span>
              </Button>
            </div>
          </header>

          <div className="flex min-h-0 min-w-0 flex-1 gap-2 overflow-hidden">
            <aside
              className="dashboard-scrollbar-hide flex h-full shrink-0 flex-col overflow-hidden rounded-xl bg-surface 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-4">
                <section className={`flex min-w-0 flex-col gap-4 ${MAIN_DATA_CARD}`}>
                  <div className="flex min-w-0 flex-col gap-4">
                    <DashboardModuleTitle title="核心指标" subtitle={MODULE_SUBTITLE_PLACEHOLDER} />
                    <ProportionBarCardPreview
                      items={CORE_METRIC_ITEMS}
                      selectedId={selectedMetricId}
                      onSelect={handleMetricSelect}
                    />
                  </div>

                  <div className="flex min-w-0 flex-col gap-4">
                    {/*
                      与上方标题、指标卡同列对齐：不再使用负 margin 外扩，避免纵轴刻度相对内容区「顶出去」。
                    */}
                    <div className="min-w-0">
                      <ServiceDataTrendChart data={TREND_DATA} series={chartSeries} />
                    </div>
                    <div className="min-w-0 [&>section]:!w-full [&>section]:!min-w-0">
                      <ProgressIndicatorCardPreview />
                    </div>
                  </div>
                </section>

                <section className={`flex min-w-0 flex-col gap-4 ${MAIN_DATA_CARD}`}>
                  <header className="flex min-w-0 flex-wrap items-center justify-between gap-3">
                    <DashboardModuleTitle title="渠道指标分析" subtitle={MODULE_SUBTITLE_PLACEHOLDER} />
                    <div className="flex flex-wrap items-center gap-3">
                      <Button type="button" variant="outline-black" size="md">
                        自定义列表
                      </Button>
                      <Button type="button" variant="outline-black" size="md">
                        导出
                      </Button>
                    </div>
                  </header>
                  <div className="min-w-0 overflow-x-auto">
                    <BulletChartTablePreview />
                  </div>
                </section>
              </div>
            </div>
            </main>
          </div>
        </div>
      </div>
    </div>
  );
}
