import { useCallback, useMemo, useRef, useState } from 'react';
import Button from '../components/Button';
import Icon from '../components/Icon';
import Sheet from '../components/Sheet';
import Table from '../components/Table';
import TagBar from '../components/TagBar';
import {
  LIST_COLUMNS,
  PAGE_FRAME_CONTENT_MARGIN,
  PAGE_FRAME_PANEL_GAP,
  PageHeader,
  WHITE_CARD_STYLE,
  buildListDataSource,
  useListInitialLoading,
} from './pageListShared';
import { TFDS_RESIZE_HANDLE_LINE_TRANSITION, TFDS_RESIZE_LINE_WIDTH_CLASS } from '../shared/resize-handle';

/**
 * McpManagementPage — B 端"MCP 工具管理"列表页模板（双白卡 + TagBar 版）
 *
 * 模板结构（横向两个白卡）：
 *   · 左侧白卡：可拖拽调宽的辅助大卡，内部承载 TagBar 标签树（业务切换 + 多级标签）
 *   · 右侧白卡：主工作区白卡，承载标题栏 + Table，并弹性占满剩余空间
 *   · Table 自身提供搜索筛选栏，页面级不再额外重复渲染 FilterBar
 *   · 选中标签节点 → 右侧列表自动按 tagIds 过滤
 *
 * 规则语义：
 *   · 该页是“横向大卡工作区默认支持宽度拖拽”的标准示例
 *   · 主卡始终 `flex-1 min-w-0`，左侧辅助白卡容器负责拖拽调宽
 *   · TagBar 自身只负责标签导航与底部展开/收起按钮，收起/展开联动整个白卡容器
 *   · 左卡外层保持 `overflow-visible`，确保容器级拖拽把手不会被裁切
 *
 * 业务接入：
 *   · MCP_TAG_TREE 替换为业务真实分类树
 *   · MCP_DATA 每条增加 tagIds 关联
 *   · 其他文案（标题/Table 筛选项/创建按钮）按业务调整
 */

const PAGE_TITLE = 'MCP 工具管理';
const MCP_TAGBAR_WIDTH_LIMITS = {
  initial: 260,
  min: 200,
  max: 360,
  collapsed: 72,
};
const TAGBAR_PANEL_RESIZE_HANDLE = 'absolute top-0 bottom-0 -right-[6px] z-20 w-3 cursor-col-resize touch-none select-none focus-visible:outline-none';
const TAGBAR_PANEL_RESIZE_BAR = `absolute right-[5px] top-0 bottom-0 ${TFDS_RESIZE_LINE_WIDTH_CLASS} ${TFDS_RESIZE_HANDLE_LINE_TRANSITION}`;

function clampTagBarPanelWidth(value) {
  return Math.min(
    Math.max(value, MCP_TAGBAR_WIDTH_LIMITS.min),
    MCP_TAGBAR_WIDTH_LIMITS.max,
  );
}

/* ── 左侧 TagBar：业务切换 ── */
const MCP_BUSINESSES = [
  { id: 'douyin-local-services', label: '抖音生活服务', iconSrc: '抖音' },
  { id: 'douyin-community', label: '抖音社区', iconSrc: '抖音' },
  { id: 'douyin-ecommerce', label: '抖音电商', iconSrc: '抖音' },
];

/* ── 左侧 TagBar：标签树（决定 MCP 列表的筛选维度） ── */
const MCP_TAG_TREE = [
  {
    id: 'data',
    label: '数据中台',
    iconName: 'database-01-stroked',
    iconBgToken: 'blue-50',
    children: [
      {
        id: 'data-poi',
        label: 'POI 数据',
        children: [
          { id: 'data-poi-basic', label: '门店基础信息' },
          { id: 'data-poi-geo', label: '门店地理位置' },
        ],
      },
      {
        id: 'data-user',
        label: '用户数据',
        children: [
          { id: 'data-user-profile', label: '用户画像标签' },
          { id: 'data-user-behavior', label: '用户行为聚合' },
        ],
      },
      {
        id: 'data-order',
        label: '订单数据',
        children: [
          { id: 'data-order-query', label: '订单查询服务' },
          { id: 'data-order-fulfillment', label: '履约状态识别' },
        ],
      },
    ],
  },
  {
    id: 'marketing',
    label: '营销中台',
    iconName: 'gift-01-stroked',
    iconBgToken: 'orange-50',
    children: [
      {
        id: 'marketing-coupon',
        label: '券与活动',
        children: [
          { id: 'marketing-coupon-center', label: '营销活动配置' },
          { id: 'marketing-coupon-verify', label: '优惠券核销' },
        ],
      },
      {
        id: 'marketing-content',
        label: '内容审核',
        children: [
          { id: 'marketing-content-text', label: '文本内容审核' },
          { id: 'marketing-content-material', label: '达人素材复审' },
        ],
      },
    ],
  },
  {
    id: 'algo',
    label: '算法服务',
    iconName: 'cpu-chip-01-stroked',
    iconBgToken: 'purple-50',
    children: [
      {
        id: 'algo-recommend',
        label: '推荐召回',
        children: [
          { id: 'algo-recommend-engine', label: '推荐引擎调用' },
          { id: 'algo-recommend-recall', label: '多路召回服务' },
        ],
      },
      {
        id: 'algo-rank',
        label: '排序与策略',
        children: [
          { id: 'algo-rank-strategy', label: '排序策略配置' },
          { id: 'algo-rank-experiment', label: 'AB 实验查询' },
        ],
      },
    ],
  },
];

const MCP_DEFAULT_TAG_ID = 'data-order-query';
const MCP_DEFAULT_EXPANDED_IDS = ['data', 'data-order', 'marketing', 'marketing-coupon', 'algo', 'algo-recommend'];

const MCP_DATA = [
  { name: 'POI 数据 MCP', tag: '数据接入', desc: '统一调用 POI 基础信息、坐标、营业时间等字段。', tagIds: ['data', 'data-poi', 'data-poi-basic'] },
  { name: '门店地理 MCP', tag: '数据接入', desc: '门店所在城市、商圈、行政区编码的批量查询能力。', tagIds: ['data', 'data-poi', 'data-poi-geo'] },
  { name: '用户画像 MCP', tag: '画像服务', desc: '封装画像中台的标签查询、人群圈选能力。', tagIds: ['data', 'data-user', 'data-user-profile'] },
  { name: '用户行为 MCP', tag: '行为分析', desc: '近 30 天浏览、点击、下单等行为聚合查询。', tagIds: ['data', 'data-user', 'data-user-behavior'] },
  { name: '订单查询 MCP', tag: '订单服务', desc: '聚合主站、本地推、抖音生服等多端订单数据。', tagIds: ['data', 'data-order', 'data-order-query'] },
  { name: '履约状态 MCP', tag: '订单服务', desc: '物流节点、配送进度与异常订单的实时识别。', tagIds: ['data', 'data-order', 'data-order-fulfillment'] },
  { name: '营销中台 MCP', tag: '营销服务', desc: '券、活动、补贴等核心营销动作的统一入口。', tagIds: ['marketing', 'marketing-coupon', 'marketing-coupon-center'] },
  { name: '优惠券核销 MCP', tag: '营销服务', desc: '券码核销、回写与异常订单的自动回收处理。', tagIds: ['marketing', 'marketing-coupon', 'marketing-coupon-verify'] },
  { name: '内容审核 MCP', tag: '内容安全', desc: '文本 / 图片 / 视频审核能力，支持送审与复审。', tagIds: ['marketing', 'marketing-content', 'marketing-content-text'] },
  { name: '素材审核 MCP', tag: '内容安全', desc: '达人投稿物料的风险识别与一键复检流程。', tagIds: ['marketing', 'marketing-content', 'marketing-content-material'] },
  { name: '推荐引擎 MCP', tag: '推荐服务', desc: '在线召回、排序与多场景策略调用接口。', tagIds: ['algo', 'algo-recommend', 'algo-recommend-engine'] },
  { name: '召回服务 MCP', tag: '推荐服务', desc: '兴趣 / 协同 / 热度多路召回的统一封装。', tagIds: ['algo', 'algo-recommend', 'algo-recommend-recall'] },
  { name: '排序策略 MCP', tag: '策略服务', desc: '提供多目标排序、人群定向与冷启动策略。', tagIds: ['algo', 'algo-rank', 'algo-rank-strategy'] },
  { name: 'AB 实验 MCP', tag: '策略服务', desc: '实验创建、分流、效果指标的统一查询入口。', tagIds: ['algo', 'algo-rank', 'algo-rank-experiment'] },
];

/* MCP_TAG_TREE 中所有合法 tag id 的扁平集合，用于过滤判定（业务 id 不参与筛选） */
const MCP_TAG_ID_SET = (function collectIds(items) {
  const bucket = new Set();
  function walk(list) {
    list.forEach((item) => {
      bucket.add(item.id);
      if (Array.isArray(item.children)) walk(item.children);
    });
  }
  walk(items);
  return bucket;
})(MCP_TAG_TREE);

function filterMcpByTag(list, selectedTagId) {
  if (!selectedTagId || !MCP_TAG_ID_SET.has(selectedTagId)) return list;
  return list.filter((item) => Array.isArray(item.tagIds) && item.tagIds.includes(selectedTagId));
}

export default function McpManagementPage() {
  const loading = useListInitialLoading();
  const [selectedTagId, setSelectedTagId] = useState(MCP_DEFAULT_TAG_ID);
  const [sheetOpen, setSheetOpen] = useState(false);
  const [tagBarWidth, setTagBarWidth] = useState(MCP_TAGBAR_WIDTH_LIMITS.initial);
  const [tagBarCollapsed, setTagBarCollapsed] = useState(false);
  const [tagBarPanelResizeActive, setTagBarPanelResizeActive] = useState(false);
  const lastExpandedTagBarWidthRef = useRef(MCP_TAGBAR_WIDTH_LIMITS.initial);
  const tagBarPanelDragRef = useRef(null);

  const dataSource = useMemo(
    () => buildListDataSource('mcp', filterMcpByTag(MCP_DATA, selectedTagId)),
    [selectedTagId],
  );

  const handleTagBarPanelWidthChange = useCallback((nextWidth) => {
    const clampedWidth = clampTagBarPanelWidth(nextWidth);
    lastExpandedTagBarWidthRef.current = clampedWidth;
    setTagBarCollapsed(false);
    setTagBarWidth(clampedWidth);
  }, []);

  const handleTagBarCollapsedChange = useCallback((nextCollapsed) => {
    setTagBarCollapsed(nextCollapsed);
    if (nextCollapsed) {
      lastExpandedTagBarWidthRef.current = clampTagBarPanelWidth(tagBarWidth);
      setTagBarWidth(MCP_TAGBAR_WIDTH_LIMITS.collapsed);
      return;
    }
    setTagBarWidth(lastExpandedTagBarWidthRef.current);
  }, [tagBarWidth]);

  const handleTagBarPanelResizePointerDown = useCallback((event) => {
    event.preventDefault();
    const startWidth = tagBarCollapsed
      ? lastExpandedTagBarWidthRef.current
      : tagBarWidth;
    tagBarPanelDragRef.current = {
      startX: event.clientX,
      startWidth,
    };
    setTagBarCollapsed(false);
    setTagBarPanelResizeActive(true);

    const previousUserSelect = document.body.style.userSelect;
    document.body.style.userSelect = 'none';

    const handlePointerMove = (moveEvent) => {
      if (!tagBarPanelDragRef.current) return;
      const deltaX = moveEvent.clientX - tagBarPanelDragRef.current.startX;
      handleTagBarPanelWidthChange(tagBarPanelDragRef.current.startWidth + deltaX);
    };

    const stopDragging = () => {
      tagBarPanelDragRef.current = null;
      setTagBarPanelResizeActive(false);
      document.body.style.userSelect = previousUserSelect;
      window.removeEventListener('pointermove', handlePointerMove);
      window.removeEventListener('pointerup', stopDragging);
    };

    window.addEventListener('pointermove', handlePointerMove);
    window.addEventListener('pointerup', stopDragging, { once: true });
  }, [handleTagBarPanelWidthChange, tagBarCollapsed, tagBarWidth]);

  const handleTagBarPanelResizeKeyDown = useCallback((event) => {
    let nextWidth = tagBarCollapsed
      ? lastExpandedTagBarWidthRef.current
      : tagBarWidth;
    if (event.key === 'ArrowLeft') nextWidth -= 16;
    if (event.key === 'ArrowRight') nextWidth += 16;
    if (event.key === 'Home') nextWidth = MCP_TAGBAR_WIDTH_LIMITS.min;
    if (event.key === 'End') nextWidth = MCP_TAGBAR_WIDTH_LIMITS.max;
    if (nextWidth === (tagBarCollapsed ? lastExpandedTagBarWidthRef.current : tagBarWidth)) return;
    event.preventDefault();
    handleTagBarPanelWidthChange(nextWidth);
  }, [handleTagBarPanelWidthChange, tagBarCollapsed, tagBarWidth]);

  return (
    <div
      className="tfds-page-mcp-management flex flex-1 min-h-0 min-w-0 relative"
      style={{ margin: PAGE_FRAME_CONTENT_MARGIN, gap: PAGE_FRAME_PANEL_GAP }}
    >
      {/* 新建 MCP Sheet 侧边抽屉 */}
      {sheetOpen && (
        <div
          className="absolute inset-0 z-50 flex justify-end"
          style={{ background: 'rgba(0,0,0,0.4)', borderRadius: '12px' }}
          onClick={() => setSheetOpen(false)}
        >
          <div
            style={{ height: '100%' }}
            onClick={(e) => e.stopPropagation()}
          >
            <Sheet
              size="md"
              title="新建 MCP"
              subtitle="配置一个新的 MCP 工具接入"
              confirmText="创建"
              cancelText="取消"
              onClose={() => setSheetOpen(false)}
              onCancel={() => setSheetOpen(false)}
              onConfirm={() => setSheetOpen(false)}
            >
              <div className="flex flex-1 min-h-0" />
            </Sheet>
          </div>
        </div>
      )}
      {/* 左侧辅助白卡：容器级拖拽调宽，TagBar 只负责标签导航与底部展开/收起 */}
      <div
        className="relative flex shrink-0 overflow-visible"
        style={{
          ...WHITE_CARD_STYLE,
          width: `${tagBarWidth}px`,
        }}
      >
        <TagBar
          businesses={MCP_BUSINESSES}
          defaultBusinessId="douyin-local-services"
          items={MCP_TAG_TREE}
          selectedItemId={selectedTagId}
          onSelect={(id) => setSelectedTagId(id)}
          defaultExpandedIds={MCP_DEFAULT_EXPANDED_IDS}
          width={tagBarWidth}
          collapsed={tagBarCollapsed}
          onCollapsedChange={handleTagBarCollapsedChange}
          collapsible
          /* 作为独立辅助大卡展示：白卡外层负责容器层级，TagBar 内部不再额外画右分割线 */
          className="!border-r-0"
          style={{ width: '100%', background: 'transparent' }}
        />
        <div
          className={TAGBAR_PANEL_RESIZE_HANDLE}
          role="separator"
          aria-label="调整标签栏白卡宽度"
          aria-orientation="vertical"
          aria-valuemin={MCP_TAGBAR_WIDTH_LIMITS.min}
          aria-valuemax={MCP_TAGBAR_WIDTH_LIMITS.max}
          aria-valuenow={Math.round(tagBarCollapsed ? lastExpandedTagBarWidthRef.current : tagBarWidth)}
          tabIndex={0}
          onPointerDown={handleTagBarPanelResizePointerDown}
          onKeyDown={handleTagBarPanelResizeKeyDown}
          onPointerEnter={() => setTagBarPanelResizeActive(true)}
          onPointerLeave={() => {
            if (!tagBarPanelDragRef.current) setTagBarPanelResizeActive(false);
          }}
          onFocus={() => setTagBarPanelResizeActive(true)}
          onBlur={() => {
            if (!tagBarPanelDragRef.current) setTagBarPanelResizeActive(false);
          }}
          data-tfds-component="TagBarPanel.ResizeHandle"
        >
          <span className={`${TAGBAR_PANEL_RESIZE_BAR} ${tagBarPanelResizeActive ? 'bg-brand-500' : 'bg-transparent'}`} />
        </div>
      </div>

      {/* 右侧主白卡：保持弹性撑满剩余空间，不参与固定宽计算 */}
      <div
        className="flex flex-1 min-h-0 min-w-0 flex-col overflow-hidden"
        style={{
          ...WHITE_CARD_STYLE,
        }}
      >
        <div
          className="flex flex-1 min-h-0 min-w-0 flex-col"
          style={{ padding: '24px', gap: '16px' }}
        >
          <PageHeader
            title={PAGE_TITLE}
            actions={
              <Button
                variant="primary"
                icon={<Icon name="plus-stroked" />}
                onClick={() => setSheetOpen(true)}
              >
                新建MCP
              </Button>
            }
          />

          <div className="flex flex-1 min-h-0">
            <Table
              className="h-full"
              columns={LIST_COLUMNS}
              dataSource={dataSource}
              loading={loading}
              fixedColumnsMode="last"
              pagination={{
                current: 1,
                pageSize: 10,
                total: dataSource.length,
                pageSizeOptions: [10, 20],
              }}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
