import { useCallback, useRef, useState } from 'react';
import NavBar from '../components/NavBar';
import Modal from '../components/Modal';
import Empty from '../components/Empty';
import Button from '../components/Button';
import FullScreenPage from '../components/FullScreenPage';
import McpManagementPage from './McpManagementPage';
import StrategyListPage from './StrategyListPage';
import TabTopBarListPage from './TabTopBarListPage';
import VariableManagementPage from './VariableManagementPage';
import {
  PAGE_FRAME_CONTENT_MARGIN,
  PAGE_FRAME_PANEL_GAP,
  WHITE_CARD_STYLE,
} from './pageListShared';
import { tfdsResizeHandleLineClass } from '../shared/resize-handle';

const BASE_FRAME_RESIZE_LINE = tfdsResizeHandleLineClass('base-frame-resize', { sizeClass: 'my-2' });

/**
 * BasePageFramePattern — B 端基础页面框架
 *
 * 整体充当"模板示例集"的外壳：
 *   外框：blueGrey-200 浅灰底，业务页面根容器贴浏览器边缘，不额外加整页圆角或描边
 *   左侧：NavBar 业务侧边导航（OLA 平台变体），菜单项替换为通用"列表示例 1~5"，
 *         每项对应一个独立的列表页模板（业务可直接复用整页代码）
 *   右侧：根据当前选中的菜单 id 渲染对应模板
 *     · example-1 → 变量管理（单白卡：标题/筛选/表格）
 *     · example-2 → MCP 工具管理（双白卡：左 TagBar + 右主白卡）
 *     · example-3 → 胶囊 Tab 标题栏 + 白卡（顶部 TopBar 承担一级切换 + 平台级操作）
 *     · example-4/5 → 暂留空白卡占位，后续可继续添加新模板
 *
 * 业务接入：
 *   · 直接复制 VariableManagementPage / McpManagementPage 单文件即可作为新页面起点
 *   · 共用结构（标题栏 / 筛选栏 / 列定义）封装在 pageListShared.jsx
 *
 * @prop {string} [defaultSelectedItemId='home'] — 初始高亮菜单 id
 */

const NAV_ITEMS = [
  { id: 'home', label: '页面示例0', iconName: 'layout-alt-01-stroked' },
  { id: 'example-1', label: '页面示例1', iconName: 'layout-alt-01-stroked' },
  { id: 'example-2', label: '页面示例2', iconName: 'layout-alt-01-stroked' },
  { id: 'example-3', label: '页面示例3', iconName: 'layout-alt-01-stroked' },
  { id: 'example-4', label: '页面示例4', iconName: 'layout-alt-01-stroked' },
  { id: 'example-5', label: '页面示例5', iconName: 'layout-alt-01-stroked' },
];

const QA_PANEL_LIMITS = {
  left: { min: 260, max: 420, initial: 320 },
  middle: { min: 280, max: 520, initial: 360 },
};

const QA_PANEL_CONTENT = [
  {
    key: 'left',
    step: '1',
    title: '步骤标题一',
    hint: '支持拖拽调宽',
    body: '该区域模拟左侧辅助工作区。横向大卡布局下，辅助卡默认支持宽度拖拽调整，便于用户按任务分配浏览与编辑空间。内容过高时仍在卡片内部滚动，不把整页撑出视口。',
  },
  {
    key: 'middle',
    step: '2',
    title: '步骤标题二',
    hint: '默认可调宽',
    body: '该区域模拟中间次级工作区。基础页面框架示例不再使用静态三等分网格，而是提供可拖拽的大卡工作区样板，帮助生成页面时默认学习到“主卡弹性、辅卡可拖”的结构。',
  },
  {
    key: 'right',
    step: '3',
    title: '步骤标题三',
    hint: '主卡弹性',
    body: '右侧主卡继续保持 flex 弹性，自动占满剩余空间。拖拽分隔条只改变相邻大卡宽度，不改变卡片内标题、正文和滚动容器的结构关系。',
  },
];

function clampQaPanelWidth(key, width) {
  const limits = QA_PANEL_LIMITS[key];
  if (!limits) return width;
  return Math.min(limits.max, Math.max(limits.min, width));
}


export default function BasePageFramePattern({
  defaultSelectedItemId = 'home',
}) {
  const [selectedItemId, setSelectedItemId] = useState(defaultSelectedItemId);
  const [newVarModalOpen, setNewVarModalOpen] = useState(false);
  const [createQAOpen, setCreateQAOpen] = useState(false);

  const PAGE_BY_ITEM_DYNAMIC = {
    'home':      <StrategyListPage />,
    'example-1': <VariableManagementPage onNewVariable={() => setNewVarModalOpen(true)} />,
    'example-2': <McpManagementPage />,
    'example-3': <TabTopBarListPage onCreateQA={() => setCreateQAOpen(true)} />,
    'example-4': <NoAccessPage />,
    'example-5': <ConstructionPage />,
  };
  const activePage = PAGE_BY_ITEM_DYNAMIC[selectedItemId];

  return (
    <div
      className="tfds-page-base-frame relative flex h-full min-h-0 min-w-0 w-full items-stretch overflow-hidden"
      style={{
        flex: '1 1 auto',
        alignSelf: 'stretch',
        minHeight: '100%',
        background: 'var(--color-blueGrey-200, #F2F4F7)',
        /* 基础页面框架：作为整页背景容器，贴浏览器边缘展示，不做外圈圆角 */
        borderRadius: 0,
      }}
    >
      {/* 新建变量弹窗遮罩 — absolute 覆盖整个红框区域（含 NavBar） */}
      {newVarModalOpen && (
        <div
          className="absolute inset-0 z-50 flex items-start justify-center"
          style={{ background: 'rgba(0,0,0,0.4)', borderRadius: 0, paddingTop: '80px' }}
        >
          <Modal
            size="sm"
            title="新建变量"
            subtitle={null}
            showFooterHint={false}
            confirmText="创建"
            cancelText="取消"
            onClose={() => setNewVarModalOpen(false)}
            onCancel={() => setNewVarModalOpen(false)}
            onConfirm={() => setNewVarModalOpen(false)}
          >
            <div style={{ height: '200px' }} />
          </Modal>
        </div>
      )}

      {/* 创建QA对 — 全屏页面，absolute inset-0 覆盖含 NavBar 在内的整个框架 */}
      {createQAOpen && (
        <FullScreenPage
          bg="grey"
          title="创建QA对"
          onBack={() => setCreateQAOpen(false)}
          headerActions={
            <>
              <Button variant="outline-black" onClick={() => setCreateQAOpen(false)}>
                保存草稿
              </Button>
              <Button variant="primary" onClick={() => setCreateQAOpen(false)}>
                发布
              </Button>
            </>
          }
        >
          <CreateQAContent />
        </FullScreenPage>
      )}

      {/* 左侧 NavBar 区（受控：点击切换右侧模板） */}
      <div className="flex shrink-0">
        <NavBar
          platform="ola"
          navItems={NAV_ITEMS}
          selectedItemId={selectedItemId}
          onSelect={(nextKey) => setSelectedItemId(nextKey)}
        />
      </div>

      {/* 右侧内容区：按当前菜单 id 渲染对应模板；未实现的示例显示占位白卡 */}
      <div className="flex flex-1 min-h-0 min-w-0 flex-col overflow-hidden">
        {activePage || <PlaceholderPage />}
      </div>
    </div>
  );
}

/* ── 卡片标题行（对齐 Figma 14757:86669：黑色数字徽章 + 标题 + 右侧辅助文字） ── */
function QACardHeader({ step, title, hint }) {
  return (
    <div
      className="flex items-center justify-between"
      style={{
        padding: '20px 24px',
        flexShrink: 0,
      }}
    >
      <div className="flex items-center" style={{ gap: 10 }}>
        {/* 黑色数字徽章 */}
        <div
          style={{
            width: 20,
            height: 20,
            borderRadius: 6,
            background: 'var(--color-grey-900, #1C1C23)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexShrink: 0,
          }}
        >
          <span style={{ fontSize: 12, fontWeight: 600, color: '#fff', lineHeight: 1, letterSpacing: '-0.01em' }}>
            {step}
          </span>
        </div>
        {/* 标题 */}
        <span style={{ fontSize: 16, fontWeight: 600, color: 'var(--color-foreground, #182230)', lineHeight: '22px' }}>
          {title}
        </span>
      </div>
      {/* 右侧辅助文字 */}
      {hint && (
        <span style={{ fontSize: 14, color: 'var(--color-foreground-secondary, #475467)', lineHeight: '20px' }}>
          {hint}
        </span>
      )}
    </div>
  );
}

function ResizablePanelHandle({
  label,
  value,
  min,
  max,
  onPointerDown,
  onKeyDown,
}) {
  return (
    <div
      role="separator"
      aria-label={label}
      aria-orientation="vertical"
      aria-valuenow={value}
      aria-valuemin={min}
      aria-valuemax={max}
      tabIndex={0}
      className="group/base-frame-resize relative flex w-2 shrink-0 cursor-col-resize items-stretch justify-center outline-none"
      onPointerDown={onPointerDown}
      onKeyDown={onKeyDown}
    >
      <span
        className={`pointer-events-none ${BASE_FRAME_RESIZE_LINE}`}
        aria-hidden="true"
      />
    </div>
  );
}

/* ── 创建QA对 — 全屏页面内容演示（灰底 + 横向可拖拽大卡） ── */
function CreateQAContent() {
  const [panelWidths, setPanelWidths] = useState(() => ({
    left: QA_PANEL_LIMITS.left.initial,
    middle: QA_PANEL_LIMITS.middle.initial,
  }));
  const dragStateRef = useRef(null);

  const updatePanelWidth = useCallback((key, nextWidth) => {
    setPanelWidths((prev) => {
      const clampedWidth = clampQaPanelWidth(key, nextWidth);
      if (prev[key] === clampedWidth) return prev;
      return {
        ...prev,
        [key]: clampedWidth,
      };
    });
  }, []);

  const handleResizePointerDown = useCallback((key, event) => {
    event.preventDefault();
    const startWidth = panelWidths[key];
    if (!startWidth) return;

    dragStateRef.current = {
      key,
      startX: event.clientX,
      startWidth,
    };

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

    const handlePointerMove = (moveEvent) => {
      if (!dragStateRef.current) return;
      const deltaX = moveEvent.clientX - dragStateRef.current.startX;
      updatePanelWidth(key, dragStateRef.current.startWidth + deltaX);
    };

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

    window.addEventListener('pointermove', handlePointerMove);
    window.addEventListener('pointerup', stopDragging, { once: true });
  }, [panelWidths, updatePanelWidth]);

  const handleResizeKeyDown = useCallback((key, event) => {
    const limits = QA_PANEL_LIMITS[key];
    if (!limits) return;

    let nextWidth = panelWidths[key];
    if (event.key === 'ArrowLeft') nextWidth -= 16;
    if (event.key === 'ArrowRight') nextWidth += 16;
    if (event.key === 'Home') nextWidth = limits.min;
    if (event.key === 'End') nextWidth = limits.max;
    if (nextWidth === panelWidths[key]) return;

    event.preventDefault();
    updatePanelWidth(key, nextWidth);
  }, [panelWidths, updatePanelWidth]);

  return (
    <div
      className="flex flex-1 min-h-0 min-w-0 overflow-hidden"
      style={{ padding: PAGE_FRAME_CONTENT_MARGIN }}
    >
      <div
        className="flex min-h-0 min-w-0 flex-1 overflow-hidden"
        style={{ gap: PAGE_FRAME_PANEL_GAP }}
      >
        {QA_PANEL_CONTENT.map((panel) => {
          const limits = QA_PANEL_LIMITS[panel.key];
          const panelStyle = panel.key === 'right'
            ? WHITE_CARD_STYLE
            : { ...WHITE_CARD_STYLE, width: `${panelWidths[panel.key]}px` };
          const panelWrapClassName = panel.key === 'right'
            ? 'flex min-h-0 min-w-0 flex-1 items-stretch'
            : 'flex min-h-0 shrink-0 items-stretch';
          const panelClassName = panel.key === 'right'
            ? 'flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden'
            : 'flex min-h-0 shrink-0 flex-col overflow-hidden';

          return (
            <div key={panel.key} className={panelWrapClassName}>
              <div className={panelClassName} style={panelStyle}>
                <QACardHeader step={panel.step} title={panel.title} hint={panel.hint} />
                <div className="flex-1 min-h-0 overflow-y-auto p-6 text-sm leading-6 text-blueGrey-600">
                  {panel.body}
                </div>
              </div>
              {limits ? (
                <ResizablePanelHandle
                  label={`${panel.title}宽度调节`}
                  value={panelWidths[panel.key]}
                  min={limits.min}
                  max={limits.max}
                  onPointerDown={(event) => handleResizePointerDown(panel.key, event)}
                  onKeyDown={(event) => handleResizeKeyDown(panel.key, event)}
                />
              ) : null}
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── 示例4：暂无权限（含申请权限操作） ── */
function NoAccessPage() {
  return (
    <div
      className="flex flex-1 min-h-0"
      style={{ margin: PAGE_FRAME_CONTENT_MARGIN }}
    >
      <div
        className="flex flex-1 min-w-0 items-center justify-center p-6"
        style={WHITE_CARD_STYLE}
      >
        <Empty
          illustrationType="no-access"
          title="暂无权限"
          description="您没有访问该页面的权限，请联系管理员申请。"
          primaryLabel="申请权限"
          onPrimary={() => {}}
        />
      </div>
    </div>
  );
}

/* ── 示例5：功能建设中（仅文案，无操作） ── */
function ConstructionPage() {
  return (
    <div
      className="flex flex-1 min-h-0"
      style={{ margin: PAGE_FRAME_CONTENT_MARGIN }}
    >
      <div
        className="flex flex-1 min-w-0 items-center justify-center p-6"
        style={WHITE_CARD_STYLE}
      >
        <Empty
          illustrationType="construction"
          title="功能建设中"
          description="该功能正在开发中，敬请期待。"
        />
      </div>
    </div>
  );
}
