import { findMany } from 'helpers/http';
import { buildPageTree } from 'helpers/page-tree';
import React, { useEffect, useMemo, useState } from 'react';
import { TreeSelect } from 'antd';

interface Props {
  getIframe: () => HTMLIFrameElement | null;
  onConfirm: (prompt: string) => void;
  onCancel: () => void;
  onGoAddData: () => void;
}

type Step = 'type' | 'crud' | 'dashboard' | 'other';

interface Page {
  id: number | string;
  zhName?: string;
  name?: string;
  code?: string;
  parentId?: number | string | null;
  sortOrder?: number | null;
}
interface Role {
  id: number | string;
  name?: string;
}

export default function AddPageModal({
  getIframe,
  onConfirm,
  onCancel,
  onGoAddData,
}: Props) {
  const [step, setStep] = useState<Step>('type');
  const [desc, setDesc] = useState('');
  const [pages, setPages] = useState<Page[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [selectedParent, setSelectedParent] = useState<string | undefined>(
    '__root__',
  );
  const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
  const [loadError, setLoadError] = useState(false);

  const pageTreeData = useMemo(() => {
    const tree = buildPageTree(
      pages,
      (p) => p.zhName || p.name || p.code || String(p.id),
    );
    // 只保留非叶子节点（有 children 的节点）
    const pruneLeaves = (nodes: typeof tree): typeof tree =>
      nodes
        .filter((n) => n.children && n.children.length > 0)
        .map((n) => ({ ...n, children: pruneLeaves(n.children!) }));
    const nonLeafTree = pruneLeaves(tree);
    // 虚拟根节点 "/"，现有顶层目录作为其子节点
    return [
      { title: '/', value: '__root__', key: '__root__', children: nonLeafTree },
    ];
  }, [pages]);

  useEffect(() => {
    if (step !== 'other') return;
    findMany<Page>('page', { take: 1000, where: { isVirtual: false } })
      .then(setPages)
      .catch(() => setLoadError(true));
    findMany<Role>('role', { take: 200 })
      .then((data) => {
        setRoles(data);
        // 如果存在 SYSTEM_ADMIN 角色，默认勾选
        const sysAdmin = data.find((r) => r.name === 'SYSTEM_ADMIN');
        if (sysAdmin) setSelectedRoles(['SYSTEM_ADMIN']);
      })
      .catch(() => setLoadError(true));
  }, [step]);

  function handleTypeSelect(type: 'crud' | 'dashboard' | 'other') {
    setStep(type);
  }

  function submitOther() {
    if (!desc.trim()) {
      alert('请描述页面功能');
      return;
    }
    if (!selectedParent) {
      alert('请选择挂载目录');
      return;
    }
    if (!selectedRoles.length) {
      alert('请至少选择一个可查看的角色');
      return;
    }
    const parentText =
      selectedParent === '__root__'
        ? '/'
        : pages.find((p) => String(p.id) === selectedParent)?.zhName ||
          pages.find((p) => String(p.id) === selectedParent)?.name ||
          pages.find((p) => String(p.id) === selectedParent)?.code ||
          '';
    const lines = [
      '请帮我使用 page-create-new skill 添加一个新页面。\n\n以下是页面需求：\n',
      desc,
    ];
    if (parentText) lines.push('挂载目录：' + parentText);
    lines.push('可查看角色：' + selectedRoles.join('、'));
    onConfirm(lines.join('\n\n'));
  }

  return (
    <div
      id="add-page-modal-overlay"
      onClick={(e) => {
        if (e.target === e.currentTarget) onCancel();
      }}
    >
      <div id="add-page-modal-card">
        <div className="add-data-modal-header">
          <h3>📄 添加新页面</h3>
          <button className="add-data-modal-close" onClick={onCancel}>
            ×
          </button>
        </div>

        {/* Step 1: type selection */}
        {step === 'type' && (
          <>
            <div id="add-page-modal-body">
              <p className="add-data-hint" style={{ padding: '12px 24px 0' }}>
                请选择要添加的页面类型：
              </p>
              <div className="add-page-type-grid">
                {[
                  {
                    type: 'crud' as const,
                    icon: '🗂️',
                    label: '数据管理',
                    desc: '增删改查的管理页面',
                  },
                  {
                    type: 'dashboard' as const,
                    icon: '📊',
                    label: '看板',
                    desc: '数据可视化 Dashboard',
                  },
                  {
                    type: 'other' as const,
                    icon: '✨',
                    label: '其他',
                    desc: '自定义功能页面',
                  },
                ].map((item) => (
                  <button
                    key={item.type}
                    className="add-page-type-card"
                    onClick={() => handleTypeSelect(item.type)}
                  >
                    <span className="add-page-type-icon">{item.icon}</span>
                    <span className="add-page-type-label">{item.label}</span>
                    <span className="add-page-type-desc">{item.desc}</span>
                  </button>
                ))}
              </div>
            </div>
            <div id="add-page-modal-footer">
              <button className="add-data-btn-cancel" onClick={onCancel}>
                取消
              </button>
            </div>
          </>
        )}

        {/* Step 2a: CRUD redirect */}
        {step === 'crud' && (
          <>
            <div id="add-page-modal-body">
              <div className="add-page-redirect-panel">
                <div className="add-page-redirect-icon">🗄️</div>
                <p className="add-page-redirect-title">数据管理页面</p>
                <p className="add-page-redirect-desc">
                  数据管理页面由数据表自动生成。
                  <br />
                  请先使用「添加新的数据表」来创建数据模型，
                  <br />
                  系统会同步生成对应的管理页面。
                </p>
              </div>
            </div>
            <div id="add-page-modal-footer">
              <button className="add-data-btn-cancel" onClick={onCancel}>
                取消
              </button>
              <button
                className="add-data-btn-confirm"
                onClick={() => {
                  onCancel();
                  onGoAddData();
                }}
              >
                去添加数据表
              </button>
            </div>
          </>
        )}

        {/* Step 2b: Dashboard redirect */}
        {step === 'dashboard' && (
          <>
            <div id="add-page-modal-body">
              <div className="add-page-redirect-panel">
                <div className="add-page-redirect-icon">📊</div>
                <p className="add-page-redirect-title">看板页面</p>
                <p className="add-page-redirect-desc">
                  看板页面请前往 <strong>Canvas 页面</strong> 进行可视化配置，
                  <br />在 Canvas 中完成设计后，页面将自动注册到导航菜单。
                </p>
              </div>
            </div>
            <div id="add-page-modal-footer">
              <button className="add-data-btn-cancel" onClick={onCancel}>
                取消
              </button>
              <button
                className="add-data-btn-confirm"
                onClick={() => {
                  onCancel();
                  const iframe = getIframe();
                  if (iframe) iframe.src = '/app/admin/canvas';
                }}
              >
                前往 Canvas
              </button>
            </div>
          </>
        )}

        {/* Step 2c: Other */}
        {step === 'other' && (
          <>
            <div id="add-page-modal-body">
              <div className="add-data-modal-body" style={{ paddingTop: 8 }}>
                <div className="guided-question">
                  <label className="guided-question-label">
                    📝 描述你想要的页面功能
                  </label>
                  <textarea
                    className="guided-question-textarea"
                    rows={4}
                    placeholder="比如：一个可以上传并预览文件的页面、一个展示团队成员分布的地图页…"
                    value={desc}
                    onChange={(e) => setDesc(e.target.value)}
                  />
                </div>
                <div className="guided-question">
                  <label className="guided-question-label">
                    📁 挂载到哪个目录？
                    <span className="guided-required-tag">（必填）</span>
                  </label>
                  <TreeSelect
                    style={{ width: '100%' }}
                    treeData={pageTreeData}
                    value={selectedParent}
                    onChange={setSelectedParent}
                    treeDefaultExpandAll
                    allowClear
                    placeholder="请选择挂载目录"
                    status={loadError ? 'error' : undefined}
                    getPopupContainer={() =>
                      document.getElementById('add-page-modal-card') ||
                      document.body
                    }
                  />
                  <span className="guided-hint-text">
                    后续可在「系统管理 → 页面管理」中调整
                  </span>
                </div>
                <div className="guided-question">
                  <label className="guided-question-label">
                    🔑 哪些角色可以查看？
                    <span className="guided-required-tag">（必填）</span>
                  </label>
                  <div className="add-page-roles-wrap">
                    {roles.length === 0 && !loadError && (
                      <span style={{ color: '#999', fontSize: 12 }}>
                        加载中…
                      </span>
                    )}
                    {loadError && (
                      <span style={{ color: '#999', fontSize: 12 }}>
                        （角色加载失败，请手动填写描述中）
                      </span>
                    )}
                    {roles.map((role) => {
                      const val = String(role.name || role.id);
                      const checked = selectedRoles.includes(val);
                      return (
                        <label key={role.id} className="add-page-role-checkbox">
                          <input
                            type="checkbox"
                            checked={checked}
                            onChange={() =>
                              setSelectedRoles((prev) =>
                                checked
                                  ? prev.filter((r) => r !== val)
                                  : [...prev, val],
                              )
                            }
                          />{' '}
                          {val}
                        </label>
                      );
                    })}
                  </div>
                  <span className="guided-hint-text">
                    后续可在「系统管理 → 角色管理」中调整
                  </span>
                </div>
              </div>
            </div>
            <div id="add-page-modal-footer">
              <button
                className="add-data-btn-cancel"
                onClick={() => setStep('type')}
              >
                返回
              </button>
              <button className="add-data-btn-confirm" onClick={submitOther}>
                确认，开始生成
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
