import { useState, useRef, useMemo, useCallback, useEffect } from 'react'
import KeycapButton from './KeycapButton.jsx'
import { useCategories } from '../contexts/CategoryContext.jsx'

const L1_GRADIENT = 'linear-gradient(135deg, #1d4ed8, #2563eb, #1d4ed8)'

// 极简铅笔图标
function EditIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"
         strokeLinecap="round" strokeLinejoin="round" className="w-2.5 h-2.5 text-gray-500">
      <path d="M12 20h9" />
      <path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
    </svg>
  )
}

// 编辑下拉菜单
function EditMenu({ nodeId, label, onRename, onDelete }) {
  return (
    <div
      className="absolute top-5 left-0 z-30 bg-white rounded-lg shadow-xl border border-gray-100 py-1 min-w-[110px]"
      onClick={(e) => e.stopPropagation()}
    >
      <button
        type="button"
        className="w-full px-3 py-1.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-blue-700"
        onClick={(e) => { e.stopPropagation(); onRename(nodeId, label) }}
      >改名</button>
      <button
        type="button"
        className="w-full px-3 py-1.5 text-left text-sm text-red-600 hover:bg-red-50"
        onClick={(e) => { e.stopPropagation(); onDelete(nodeId) }}
      >删除</button>
    </div>
  )
}

// 重命名输入框（替换键帽位置）
function RenameInput({ value, onChange, onSubmit, onCancel, size = 'md' }) {
  return (
    <input
      autoFocus
      type="text"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      onBlur={onSubmit}
      onKeyDown={(e) => {
        if (e.key === 'Enter') { e.preventDefault(); onSubmit() }
        else if (e.key === 'Escape') { e.preventDefault(); onCancel() }
      }}
      onClick={(e) => e.stopPropagation()}
      className={`px-3 py-1.5 text-sm rounded-md border-2 border-blue-400 outline-none shadow-sm bg-white text-gray-800
                  ${size === 'md' ? 'min-w-[120px]' : 'min-w-[90px]'}`}
    />
  )
}

// 新增节点输入框
function AddInput({ value, onChange, onSubmit, onCancel, placeholder }) {
  return (
    <input
      autoFocus
      type="text"
      value={value}
      placeholder={placeholder}
      onChange={(e) => onChange(e.target.value)}
      onBlur={onSubmit}
      onKeyDown={(e) => {
        if (e.key === 'Enter') { e.preventDefault(); onSubmit() }
        else if (e.key === 'Escape') { e.preventDefault(); onCancel() }
      }}
      onClick={(e) => e.stopPropagation()}
      className="px-3 py-1.5 text-sm rounded-md border-2 border-blue-400 outline-none shadow-sm bg-white text-gray-800 min-w-[120px]"
    />
  )
}

export default function SkillKeyboardView({ skills = [], categories = [], onSkillClick }) {
  const { addNode, updateNode, deleteNode } = useCategories()
  const containerRef = useRef(null)
  const [isFullscreen, setIsFullscreen] = useState(false)

  // 弹层/编辑状态
  const [activeMenu, setActiveMenu] = useState(null)   // 当前编辑菜单的 nodeId
  const [renaming, setRenaming]     = useState(null)   // { id, value }
  const [adding, setAdding]         = useState(null)   // { parentId, value }
  const [skillPopup, setSkillPopup] = useState(null)   // { nodeId, skills }

  const closePopups = useCallback(() => {
    setActiveMenu(null)
    setSkillPopup(null)
  }, [])

  // document 全局点击：关闭编辑菜单/技能 popup（不影响重命名/新增 input，它们靠 onBlur 提交）
  useEffect(() => {
    const handler = () => closePopups()
    document.addEventListener('click', handler)
    return () => document.removeEventListener('click', handler)
  }, [closePopups])

  // 全屏退出监听
  useEffect(() => {
    const handler = () => { if (!document.fullscreenElement) setIsFullscreen(false) }
    document.addEventListener('fullscreenchange', handler)
    return () => document.removeEventListener('fullscreenchange', handler)
  }, [])

  // ===== 节点索引 & 树结构 =====
  const nodeMap = useMemo(() => {
    const map = new Map()
    categories.forEach(n => map.set(n.id, n))
    return map
  }, [categories])

  const childrenMap = useMemo(() => {
    const map = new Map()
    categories.forEach(n => {
      const pid = n.parent_id || '__root__'
      if (!map.has(pid)) map.set(pid, [])
      map.get(pid).push(n)
    })
    for (const [, arr] of map) {
      arr.sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
    }
    return map
  }, [categories])

  const l1Nodes = useMemo(() => childrenMap.get('__root__') || [], [childrenMap])
  const getChildren = useCallback((id) => childrenMap.get(id) || [], [childrenMap])

  // ===== 技能数（含子孙） =====
  const skillCountMap = useMemo(() => {
    const direct = new Map()
    skills.forEach(s => {
      const nid = s.category_nodes?.[0]?.id
      if (nid) direct.set(nid, (direct.get(nid) || 0) + 1)
    })
    const totalMap = new Map()
    function calc(nid) {
      if (totalMap.has(nid)) return totalMap.get(nid)
      let t = direct.get(nid) || 0
      ;(childrenMap.get(nid) || []).forEach(c => { t += calc(c.id) })
      totalMap.set(nid, t)
      return t
    }
    categories.forEach(n => calc(n.id))
    return totalMap
  }, [skills, categories, childrenMap])

  const getSkillCount = useCallback((node) => skillCountMap.get(node.id) || 0, [skillCountMap])

  // 获取某节点（含子孙）的所有技能
  const getNodeSkills = useCallback((nodeId) => {
    if (!nodeId) return []
    const ids = new Set()
    function collect(nid) {
      ids.add(nid)
      ;(childrenMap.get(nid) || []).forEach(c => collect(c.id))
    }
    collect(nodeId)
    return skills.filter(s => {
      const sn = s.category_nodes?.[0]?.id
      return sn && ids.has(sn)
    })
  }, [skills, childrenMap])

  // ===== 编辑操作 =====
  const startRename = useCallback((id, label) => {
    setRenaming({ id, value: label })
    setActiveMenu(null)
    setSkillPopup(null)
  }, [])

  const submitRename = useCallback(async () => {
    if (!renaming) return
    const { id, value } = renaming
    const trimmed = (value || '').trim()
    const original = nodeMap.get(id)?.label
    if (trimmed && trimmed !== original && typeof updateNode === 'function') {
      await updateNode(id, trimmed)
    }
    setRenaming(null)
  }, [renaming, nodeMap, updateNode])

  const cancelRename = useCallback(() => setRenaming(null), [])

  const handleDelete = useCallback(async (id) => {
    setActiveMenu(null)
    if (!window.confirm('确定删除该节点？子节点和绑定关系将一并清理。')) return
    if (typeof deleteNode === 'function') {
      await deleteNode(id)
    }
  }, [deleteNode])

  const startAdd = useCallback((parentId) => {
    setAdding({ parentId, value: '' })
    setActiveMenu(null)
    setSkillPopup(null)
  }, [])

  const submitAdd = useCallback(async () => {
    if (!adding) return
    const { parentId, value } = adding
    const trimmed = (value || '').trim()
    if (trimmed && typeof addNode === 'function') {
      await addNode(parentId, trimmed)
    }
    setAdding(null)
  }, [adding, addNode])

  const cancelAdd = useCallback(() => setAdding(null), [])

  // ===== L3 键帽点击：弹技能选择 popup =====
  const handleL3Click = useCallback((node) => {
    const list = getNodeSkills(node.id)
    if (list.length === 0) return
    if (list.length === 1) {
      onSkillClick?.(list[0])
      return
    }
    setSkillPopup({ nodeId: node.id, nodeLabel: node.label, skills: list })
    setActiveMenu(null)
  }, [getNodeSkills, onSkillClick])

  const toggleEditMenu = useCallback((id) => {
    setActiveMenu(prev => (prev === id ? null : id))
    setSkillPopup(null)
  }, [])

  // ===== 全屏切换 =====
  const toggleFullscreen = useCallback(() => {
    if (!containerRef.current) return
    if (!document.fullscreenElement) {
      containerRef.current.requestFullscreen?.().then(() => setIsFullscreen(true)).catch(() => {})
    } else {
      document.exitFullscreen?.().then(() => setIsFullscreen(false)).catch(() => {})
    }
  }, [])

  const containerCls = isFullscreen
    ? 'fixed inset-0 z-50 overflow-auto p-8 fullscreen-enter'
    : 'rounded-xl p-6 min-h-[400px]'

  const containerStyle = {
    background: 'linear-gradient(135deg, #f8fafc 0%, #f1f5f9 50%, #e2e8f0 100%)',
  }

  // ===== 渲染键帽 wrapper（带编辑能力） =====
  const renderKeycap = ({ node, size, colorScheme, isActive, onKeycapClick, extraSlot }) => {
    const isRenaming = renaming?.id === node.id
    return (
      <div
        key={node.id}
        className="relative group inline-block"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 左上角编辑按钮 */}
        {!isRenaming && (
          <button
            type="button"
            className="absolute -top-1.5 -left-1.5 z-20 w-5 h-5 bg-white rounded-full shadow
                       opacity-0 group-hover:opacity-100 transition-opacity duration-150
                       flex items-center justify-center border border-gray-200 hover:border-blue-400"
            onClick={(e) => { e.stopPropagation(); toggleEditMenu(node.id) }}
            title="编辑"
          >
            <EditIcon />
          </button>
        )}

        {/* 下拉菜单 */}
        {activeMenu === node.id && !isRenaming && (
          <EditMenu
            nodeId={node.id}
            label={node.label}
            onRename={startRename}
            onDelete={handleDelete}
          />
        )}

        {/* 键帽 或 重命名输入 */}
        {isRenaming ? (
          <RenameInput
            value={renaming.value}
            onChange={(v) => setRenaming({ ...renaming, value: v })}
            onSubmit={submitRename}
            onCancel={cancelRename}
            size={size}
          />
        ) : (
          <KeycapButton
            label={node.label}
            count={getSkillCount(node)}
            size={size}
            isActive={isActive}
            colorScheme={colorScheme}
            onClick={onKeycapClick}
          />
        )}

        {/* 额外槽位（如 L3 的技能 popup） */}
        {extraSlot}
      </div>
    )
  }

  // 新增按钮（虚线 ghost 风格）
  const AddButton = ({ onClick, label, tone = 'sky' }) => {
    const toneCls = tone === 'teal'
      ? 'text-teal-600 border-teal-300 hover:bg-teal-50 hover:border-teal-400'
      : 'text-sky-600 border-sky-300 hover:bg-sky-50 hover:border-sky-400'
    return (
      <button
        type="button"
        onClick={(e) => { e.stopPropagation(); onClick() }}
        className={`px-3 py-1.5 text-xs rounded-md border border-dashed bg-white transition-colors ${toneCls}`}
      >
        {label}
      </button>
    )
  }

  return (
    <div ref={containerRef} className={containerCls} style={containerStyle}>
      {/* 顶部工具栏 */}
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-lg font-bold text-gray-800">⌨ 技能键盘</h2>
        <button
          onClick={(e) => { e.stopPropagation(); toggleFullscreen() }}
          className="px-3.5 py-1.5 text-[13px] rounded-lg border border-gray-300 text-gray-600 bg-white hover:border-gray-400 hover:shadow-sm transition-all"
        >
          {isFullscreen ? '✕ 退出全屏' : '⛶ 全屏'}
        </button>
      </div>

      {/* 键盘视图 */}
      <div className="space-y-5">
        {l1Nodes.map(l1 => {
          const l2Children = getChildren(l1.id)
          const isL1Renaming = renaming?.id === l1.id
          return (
            <section key={l1.id} className="rounded-xl overflow-hidden shadow-sm border border-blue-200/40">
              {/* L1 横条 */}
              <div
                className="relative px-5 py-3 flex items-center justify-between"
                style={{ background: L1_GRADIENT }}
                onClick={(e) => e.stopPropagation()}
              >
                <div className="flex items-center gap-3 min-w-0 flex-1">
                  {/* L1 编辑按钮 */}
                  {!isL1Renaming && (
                    <div className="relative group/l1">
                      <button
                        type="button"
                        className="w-6 h-6 bg-white/15 hover:bg-white/30 rounded-full flex items-center justify-center text-white/80 hover:text-white transition-colors border border-white/20"
                        onClick={(e) => { e.stopPropagation(); toggleEditMenu(l1.id) }}
                        title="编辑"
                      >
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"
                             strokeLinecap="round" strokeLinejoin="round" className="w-3 h-3">
                          <path d="M12 20h9" />
                          <path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
                        </svg>
                      </button>
                      {activeMenu === l1.id && (
                        <EditMenu
                          nodeId={l1.id}
                          label={l1.label}
                          onRename={startRename}
                          onDelete={handleDelete}
                        />
                      )}
                    </div>
                  )}

                  {isL1Renaming ? (
                    <RenameInput
                      value={renaming.value}
                      onChange={(v) => setRenaming({ ...renaming, value: v })}
                      onSubmit={submitRename}
                      onCancel={cancelRename}
                      size="md"
                    />
                  ) : (
                    <h2 className="text-white font-bold text-base tracking-wide truncate">
                      {l1.label}
                      {l1.code && <span className="ml-2 text-blue-100/80 text-xs font-normal">({l1.code})</span>}
                    </h2>
                  )}
                </div>

                <div className="flex items-center gap-3 flex-shrink-0">
                  <span className="text-blue-100/90 text-sm">{getSkillCount(l1)} 个技能</span>
                  {adding?.parentId === l1.id ? (
                    <AddInput
                      value={adding.value}
                      onChange={(v) => setAdding({ ...adding, value: v })}
                      onSubmit={submitAdd}
                      onCancel={cancelAdd}
                      placeholder="新流程名称"
                    />
                  ) : (
                    <button
                      type="button"
                      onClick={(e) => { e.stopPropagation(); startAdd(l1.id) }}
                      className="px-2.5 py-1 text-xs rounded-md bg-white/15 hover:bg-white/25 text-white border border-white/25 transition-colors"
                    >
                      + 新增流程
                    </button>
                  )}
                </div>
              </div>

              {/* L2 + L3 内容区 */}
              <div className="p-4 space-y-3 bg-gradient-to-b from-blue-50/40 to-white">
                {l2Children.length === 0 && adding?.parentId !== l1.id && (
                  <div className="text-xs py-3 text-center text-gray-400">暂无子节点</div>
                )}

                {l2Children.map(l2 => {
                  const l3Children = getChildren(l2.id)
                  return (
                    <div key={l2.id} className="mb-2">
                      {/* L2 行 */}
                      <div className="flex items-center gap-2 mb-1.5 flex-wrap">
                        {renderKeycap({
                          node: l2,
                          size: 'md',
                          colorScheme: 'teal',
                          isActive: false,
                          onKeycapClick: () => {},
                        })}
                      </div>

                      {/* L3 行 */}
                      <div className="flex flex-wrap gap-1.5 ml-4 mt-1 items-center">
                        {l3Children.map(l3 => {
                          const isPopupOpen = skillPopup?.nodeId === l3.id
                          return renderKeycap({
                            node: l3,
                            size: 'sm',
                            colorScheme: 'sky',
                            isActive: isPopupOpen,
                            onKeycapClick: () => handleL3Click(l3),
                          })
                        })}

                        {/* 新增活动 */}
                        {adding?.parentId === l2.id ? (
                          <AddInput
                            value={adding.value}
                            onChange={(v) => setAdding({ ...adding, value: v })}
                            onSubmit={submitAdd}
                            onCancel={cancelAdd}
                            placeholder="新活动名称"
                          />
                        ) : (
                          <AddButton
                            onClick={() => startAdd(l2.id)}
                            label="+ 新增活动"
                            tone="sky"
                          />
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            </section>
          )
        })}
      </div>

      {/* 空状态 */}
      {categories.length === 0 && (
        <div className="text-center text-[13px] py-16 text-gray-400">暂无分类数据</div>
      )}

      {/* 技能选择居中弹层 */}
      {skillPopup && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ paddingBottom: '10vh' }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* 遮罩 */}
          <div
            className="absolute inset-0 bg-black/20 backdrop-blur-[2px]"
            onClick={(e) => { e.stopPropagation(); setSkillPopup(null) }}
          />

          {/* 面板 */}
          <div
            className="relative bg-white rounded-2xl shadow-2xl border border-gray-100
                       w-[90vw] max-w-[400px] max-h-[400px] overflow-hidden
                       animate-[scaleIn_0.2s_ease-out]"
            onClick={(e) => e.stopPropagation()}
          >
            {/* 头部 */}
            <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
              <div className="min-w-0">
                <h3 className="text-sm font-semibold text-gray-800 truncate">{skillPopup.nodeLabel}</h3>
                <p className="text-xs text-gray-400 mt-0.5">{skillPopup.skills.length} 个技能</p>
              </div>
              <button
                type="button"
                onClick={(e) => { e.stopPropagation(); setSkillPopup(null) }}
                className="w-7 h-7 rounded-full bg-gray-100 flex items-center justify-center
                           text-gray-400 hover:text-gray-600 hover:bg-gray-200 transition-colors flex-shrink-0 ml-3"
              >
                ✕
              </button>
            </div>

            {/* 技能列表 */}
            <div className="overflow-y-auto max-h-[320px] py-2">
              {skillPopup.skills.map((skill, idx) => (
                <button
                  key={skill.id}
                  type="button"
                  className="w-full px-5 py-3 text-left flex items-center gap-3
                             hover:bg-blue-50 transition-colors group"
                  onClick={(e) => {
                    e.stopPropagation()
                    onSkillClick?.(skill)
                    setSkillPopup(null)
                  }}
                >
                  {/* 序号 */}
                  <span className="w-6 h-6 rounded-full bg-gray-100 group-hover:bg-blue-100
                                   flex items-center justify-center text-xs text-gray-500
                                   group-hover:text-blue-600 flex-shrink-0 font-medium">
                    {idx + 1}
                  </span>

                  {/* 技能信息 */}
                  <div className="flex-1 min-w-0">
                    <div className="text-sm text-gray-700 group-hover:text-blue-700 truncate font-medium">
                      {skill.title}
                    </div>
                    {skill.description && (
                      <div className="text-xs text-gray-400 truncate mt-0.5">
                        {skill.description}
                      </div>
                    )}
                  </div>

                  {/* 状态点 */}
                  <span className={`w-2 h-2 rounded-full flex-shrink-0 ${
                    skill.status === 'published' ? 'bg-green-400' :
                    skill.status === 'testing' ? 'bg-amber-400' :
                    skill.status === 'offline' ? 'bg-gray-300' : 'bg-gray-300'
                  }`} />
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
