import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useSkills, SKILL_STATUS } from '../contexts/SkillsContext.jsx'
import { useCategories } from '../contexts/CategoryContext.jsx'
import { useAuth } from '../contexts/AuthContext.jsx'
import NodePickerModal, { getNodePath } from '../components/NodePickerModal.jsx'
import { getSkillApi, API_BASE } from '../services/api.js'
import { useChatOverlay } from '../contexts/ChatOverlayContext.jsx'
import { formatSkillDateTime } from '../services/skillTimestamp.js'

const STATUS_OPTIONS = [
  { value: 'draft',     label: '草稿' },
  { value: 'published', label: '已上线' },
  { value: 'archived',  label: '已下线' },
]

export default function SkillEditPage() {
  const { id } = useParams()
  const navigate = useNavigate()
  const { openOverlay } = useChatOverlay()
  const { findById, updateSkill, deleteSkill, skills } = useSkills()
  const { flat } = useCategories()
  const { user } = useAuth()

  const [skill, setSkill]           = useState(null)
  const [notFound, setNotFound]     = useState(false)
  const [loadingSkill, setLoading]  = useState(true)

  const [name, setName]               = useState('')
  const [desc, setDesc]               = useState('')
  const [creatorName, setCreatorName] = useState('')
  const [nodeId, setNodeId]           = useState(null)
  const [status, setStatus]           = useState('draft')
  const [visibility, setVisibility]   = useState('public')
  const [pickerOpen, setPickerOpen]   = useState(false)
  const [saving, setSaving]           = useState(false)
  const [error, setError]             = useState('')
  const [success, setSuccess]         = useState(false)

  const nodePath = nodeId != null ? getNodePath(nodeId, flat) : ''

  // 超级管理员：拥有全权（与后端保持一致）
  const SUPER_ADMIN_EMAIL = '494161546@qq.com'
  const SUPER_ADMIN_PHONE = '13136092523'
  const isSuperAdmin = !!user && (user.email === SUPER_ADMIN_EMAIL || user.phone === SUPER_ADMIN_PHONE)

  // 判断是否是创建人（手机或邮箱任意一个匹配）
  // 兼容历史数据：当 creator_phone 和 creator_email 都为空时，无法验证身份，登录用户即视为有编辑权限
  // 超级管理员永远拥有编辑权限
  const isOwner = skill ? (
    isSuperAdmin ||
    (!skill.creator_phone && !skill.creator_email && !!user) ||
    (user?.phone && skill.creator_phone && user.phone === skill.creator_phone) ||
    (user?.email && skill.creator_email && user.email === skill.creator_email)
  ) : false

  // 统一的可编辑判断：非创建者且非超管 → 进入只读模式
  const canEdit = isOwner

  // 优先从 context 取，取不到再调 API（直接进编辑页的情况）
  useEffect(() => {
    const fromCtx = findById(id)
    if (fromCtx) {
      initForm(fromCtx)
      setLoading(false)
      return
    }
    setLoading(true)
    getSkillApi(id)
      .then(s => {
        if (s && s.id) {
          initForm(s)
        } else {
          setNotFound(true)
        }
      })
      .catch(() => setNotFound(true))
      .finally(() => setLoading(false))
  // skills 作依赖：context 加载完成后重刷一次（处理上传后立即跳转的时序）
  }, [id, skills.length]) // eslint-disable-line

  function initForm(s) {
    setSkill(s)
    setName(s.name || '')
    setDesc(s.desc || s.description || '')
    setCreatorName(s.creator_name || '')
    setNodeId(s.node_id || null)
    setStatus(s.status || 'draft')
    setVisibility(s.visibility === 'private' ? 'private' : 'public')
  }

  // 下载原始包
  const handleDownload = () => {
    if (!skill?.package_key) return
    const url = `${API_BASE}/uploads/download?key=${encodeURIComponent(skill.package_key)}`
    const a = document.createElement('a')
    a.href = url
    a.target = '_blank'
    a.rel = 'noopener noreferrer'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }

  const handleSave = async () => {
    if (!name.trim()) { setError('名称不能为空'); return }
    if (!creatorName.trim()) { setError('创建人不能为空'); return }
    setSaving(true)
    setError('')
    setSuccess(false)
    try {
      await updateSkill(id, {
        name: name.trim(),
        desc: desc.trim(),
        creator_name: creatorName.trim(),
        node_id: nodeId,
        node_path: nodePath, // 仅更新 context state，不发到 API（toCfPayload 不映射此字段）
        status,
        visibility,
      })
      setSuccess(true)
      setTimeout(() => setSuccess(false), 2500)
    } catch (e) {
      setError('保存失败：' + (e?.response?.data?.message || e?.response?.data?.error || e?.message || String(e)))
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async () => {
    if (!window.confirm(`确认删除 Skill「${name}」？此操作不可恢复。`)) return
    try {
      await deleteSkill(id)
      navigate('/my-skills')
    } catch (e) {
      setError('删除失败：' + (e?.message || String(e)))
    }
  }

  if (loadingSkill) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <div className="text-[13px] text-gray-400">加载中…</div>
      </div>
    )
  }

  if (notFound || !skill) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center gap-3">
        <div className="text-[13px] text-gray-500">Skill 不存在或已被删除</div>
        <button onClick={() => navigate('/my-skills')} className="text-[13px] text-brand-600 hover:underline">
          ← 返回我的 Skill
        </button>
      </div>
    )
  }

  const statusMeta = SKILL_STATUS[skill.status] || SKILL_STATUS.draft

  return (
    <div className="flex-1 overflow-auto p-8 max-w-3xl mx-auto w-full">
      {/* 头部 */}
      <div className="flex items-center gap-3 mb-6">
        <button
          onClick={() => navigate('/my-skills')}
          className="text-[13px] text-gray-500 hover:text-gray-700 flex items-center gap-1 flex-shrink-0"
        >
          ← 返回
        </button>
        <span className="text-gray-300">/</span>
        <h1 className="text-[17px] font-semibold text-gray-900 flex-1 truncate">{skill.name}</h1>
        <span className={`text-[11px] px-2 py-0.5 rounded flex-shrink-0 ${statusMeta.color}`}>
          {statusMeta.label}
        </span>
      </div>

      {!canEdit && (
        <p className="text-sm text-gray-400 mb-4">只读模式 · 仅创建者或管理员可编辑</p>
      )}

      <div className="bg-white border border-gray-200 rounded-xl divide-y divide-gray-100">

        {/* 基本信息 */}
        <div className="p-6 space-y-5">
          <div className="text-[11px] font-semibold text-gray-400 uppercase tracking-wider">基本信息</div>

          <div>
            <label className="block text-[13px] text-gray-700 mb-1">
              名称 <span className="text-rose-500">*</span>
            </label>
            <input
              value={name}
              onChange={e => setName(e.target.value)}
              maxLength={80}
              disabled={!canEdit}
              className="w-full px-3 py-2 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400 disabled:bg-gray-50 disabled:text-gray-500 disabled:cursor-not-allowed"
            />
          </div>

          <div>
            <label className="block text-[13px] text-gray-700 mb-1">描述</label>
            <textarea
              rows={3}
              value={desc}
              onChange={e => setDesc(e.target.value)}
              placeholder="一句话说明 Skill 用途"
              disabled={!canEdit}
              className="w-full px-3 py-2 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400 resize-none disabled:bg-gray-50 disabled:text-gray-500 disabled:cursor-not-allowed"
            />
          </div>

          <div>
            <label className="block text-[13px] text-gray-700 mb-1">
              创建人姓名 <span className="text-rose-500">*</span>
              <span className="ml-2 text-[11px] text-gray-400">用于让运营/同事知道这个 Skill 是谁建的</span>
            </label>
            <input
              value={creatorName}
              onChange={e => setCreatorName(e.target.value)}
              maxLength={32}
              placeholder="请填写您的真实姓名"
              disabled={!canEdit}
              className="w-full px-3 py-2 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400 disabled:bg-gray-50 disabled:text-gray-500 disabled:cursor-not-allowed"
            />
          </div>
        </div>

        {/* 归属与状态 */}
        <div className="p-6 space-y-5">
          <div className="text-[11px] font-semibold text-gray-400 uppercase tracking-wider">归属与状态</div>

          <div>
            <label className="block text-[13px] text-gray-700 mb-1">
              关联流程节点 <span className="text-rose-500">*</span>
              <span className="ml-2 text-[11px] text-gray-400">已归档节点不可选</span>
            </label>
            <div
              onClick={() => canEdit && setPickerOpen(true)}
              className={`w-full px-3 py-2 text-[13px] border border-gray-200 rounded-md flex items-center justify-between gap-2 bg-white ${
                canEdit ? 'cursor-pointer hover:border-brand-400 transition' : 'cursor-not-allowed opacity-60'
              }`}
            >
              {nodeId != null ? (
                <span className="text-gray-800 truncate">
                  <span className="text-brand-600 mr-1">⇲</span>{nodePath}
                </span>
              ) : (
                <span className="text-gray-400">点击从流程架构选择关联节点</span>
              )}
              {canEdit && (
                <span className="text-gray-300 text-[12px] flex-shrink-0">{nodeId != null ? '更换' : '选择'} ▸</span>
              )}
            </div>
          </div>

          <div>
            <label className="block text-[13px] text-gray-700 mb-1">状态</label>
            <select
              value={status}
              onChange={e => setStatus(e.target.value)}
              disabled={!canEdit}
              className="w-full px-3 py-2 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400 bg-white disabled:bg-gray-50 disabled:text-gray-500 disabled:cursor-not-allowed"
            >
              {STATUS_OPTIONS.map(o => (
                <option key={o.value} value={o.value}>{o.label}</option>
              ))}
            </select>
          </div>

          {/* 可见范围 */}
          <div className="flex items-center justify-between pt-1">
            <div className="flex-1 min-w-0">
              <div className="text-[13px] text-gray-700">可见范围</div>
              <p className="text-[11px] text-gray-400 mt-0.5">
                {visibility === 'public' ? '所有人可在技能广场看到并下载' : '仅创建者与超级管理员可见'}
              </p>
            </div>
            <div className="flex items-center gap-2 flex-shrink-0 ml-3">
              <button
                type="button"
                disabled={!canEdit}
                onClick={() => canEdit && setVisibility(v => v === 'public' ? 'private' : 'public')}
                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                  visibility === 'public' ? 'bg-brand-500' : 'bg-gray-300'
                } ${canEdit ? 'cursor-pointer' : 'opacity-60 cursor-not-allowed'}`}
                aria-label="切换可见范围"
              >
                <span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
                  visibility === 'public' ? 'translate-x-6' : 'translate-x-1'
                }`} />
              </button>
              <span className="text-[12px] text-gray-600 w-8 text-right">
                {visibility === 'public' ? '公开' : '私密'}
              </span>
            </div>
          </div>
        </div>

        {/* 元信息（只读） */}
        <div className="p-6">
          <div className="text-[11px] font-semibold text-gray-400 uppercase tracking-wider mb-4">元信息（只读）</div>
          <div className="grid grid-cols-2 gap-x-6 gap-y-4 text-[12px]">
            <MetaRow label="来源" value={skill.source === 'upload' ? '上传' : skill.source === 'create' ? '表单创建' : skill.source} />
            <div className="flex flex-col gap-0.5">
              <span className="text-[11px] text-gray-400">文件</span>
              {skill.package_key ? (
                <div className="flex items-center gap-2">
                  <span className="text-gray-700 truncate">
                    {skill.package_name || '未命名'}
                    {skill.package_size ? ` · ${(skill.package_size / 1024).toFixed(1)} KB` : ''}
                  </span>
                  <button
                    onClick={handleDownload}
                    className="flex-shrink-0 text-[11px] px-2 py-0.5 rounded bg-brand-50 text-brand-700 hover:bg-brand-100 transition"
                  >
                    ↓ 下载
                  </button>
                </div>
              ) : (
                <span className="text-gray-700">—</span>
              )}
            </div>
            <MetaRow label="手机（留痕）" value={skill.creator_phone || '—'} />
            <MetaRow label="邮箱（留痕）" value={skill.creator_email || '—'} />
            <MetaRow
              label="创建时间"
              value={formatSkillDateTime(skill.created_at)}
            />
            <MetaRow
              label="更新时间"
              value={formatSkillDateTime(skill.updated_at)}
            />
          </div>
        </div>

        {/* 操作栏 */}
        <div className="px-6 py-4 flex items-center justify-between">
          {canEdit ? (
            <button
              onClick={handleDelete}
              disabled={saving}
              className="px-3.5 py-1.5 text-[13px] rounded-md text-rose-600 border border-rose-200 hover:bg-rose-50 disabled:opacity-50"
            >
              删除此 Skill
            </button>
          ) : (
            <span />
          )}

          <div className="flex items-center gap-3">
            {isSuperAdmin && skill?.package_key && (
              <button
                onClick={() => openOverlay('sandbox', { skillId: skill.id })}
                className="px-3.5 py-1.5 text-[13px] rounded-md text-gray-600 border border-gray-200 hover:bg-gray-50"
              >
                ▶ 运行
              </button>
            )}
            {isSuperAdmin && (
              <button
                onClick={() => skill?.id && openOverlay('eval', { skillId: skill.id })}
                className="px-3.5 py-1.5 text-[13px] rounded-md text-brand-700 border border-brand-200 hover:bg-brand-50"
              >
                ✓ 去评测
              </button>
            )}
            {error && <span className="text-[12px] text-rose-600">{error}</span>}
            {success && <span className="text-[12px] text-emerald-600">✓ 已保存</span>}
            {canEdit && (
              <button
                onClick={handleSave}
                disabled={saving || !name.trim() || !creatorName.trim()}
                className="px-4 py-1.5 text-[13px] rounded-md text-white bg-brand-600 hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {saving ? '保存中…' : '保存'}
              </button>
            )}
          </div>
        </div>
      </div>

      <NodePickerModal
        open={pickerOpen}
        initialNodeId={nodeId}
        onClose={() => setPickerOpen(false)}
        onConfirm={(newId) => { setNodeId(newId); setPickerOpen(false) }}
      />
    </div>
  )
}

function MetaRow({ label, value }) {
  return (
    <div className="flex flex-col gap-0.5">
      <span className="text-[11px] text-gray-400">{label}</span>
      <span className="text-gray-700 break-all">{value}</span>
    </div>
  )
}
