import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Sparkles, Upload } from 'lucide-react'
import { useSkills, SKILL_STATUS } from '../contexts/SkillsContext.jsx'
import { FEATURES } from '../featureFlags.js'
import { useChatOverlay } from '../contexts/ChatOverlayContext.jsx'
import { formatSkillDateTime } from '../services/skillTimestamp.js'

const STATUS_TABS = [
  { key: 'all',       label: '全部' },
  { key: 'draft',     label: '草稿' },
  { key: 'published', label: '已上线' },
  { key: 'archived',  label: '已下线' }
]

export default function MySkills() {
  const navigate = useNavigate()
  const { openOverlay } = useChatOverlay()
  const { skills, summary, deleteSkill } = useSkills()
  const [tab, setTab] = useState('all')
  const [keyword, setKeyword] = useState('')

  const filtered = useMemo(() => {
    let list = skills
    if (tab !== 'all') list = list.filter(s => s.status === tab)
    const kw = keyword.trim().toLowerCase()
    if (kw) {
      list = list.filter(s =>
        s.name.toLowerCase().includes(kw) ||
        (s.desc || '').toLowerCase().includes(kw) ||
        (s.node_path || '').toLowerCase().includes(kw)
      )
    }
    return list
  }, [skills, tab, keyword])

  return (
    <div className="flex-1 overflow-auto">
      {/* 顶部 */}
      <div className="bg-white border-b border-gray-200 px-8 py-5">
        <div className="flex items-start justify-between gap-4">
          <div>
            <h1 className="text-[18px] font-semibold text-gray-900 mb-1">我的 Skill</h1>
            <p className="text-[13px] text-gray-500">
              点击 Skill 进入编辑页，可使用「✓ 去评测」对 Skill 进行 AI 评测和迭代优化。
            </p>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => navigate('/upload')}
              className="px-3.5 py-1.5 text-[13px] rounded-md text-brand-600 bg-white border border-brand-200 hover:bg-brand-50 flex items-center gap-1"
            >
              <Upload size={14} />
              <span>上传</span>
            </button>
            {FEATURES.createSkill && (
              <button
                type="button"
                onClick={() => openOverlay('create')}
                className="px-3.5 py-1.5 text-[13px] rounded-md text-white bg-brand-600 hover:bg-brand-700 flex items-center gap-1"
              >
                <Sparkles size={14} /> 新建 Skill
              </button>
            )}
          </div>
        </div>

        {/* 状态汇总 */}
        <div className="mt-4 grid grid-cols-5 gap-3">
          <SummaryCard label="全部"     value={summary.total}     accent="text-gray-700" />
          <SummaryCard label="草稿"     value={summary.draft}     accent="text-gray-700" />
          <SummaryCard label="已上线"   value={summary.published} accent="text-emerald-600" />
          <SummaryCard label="已下线"   value={summary.archived}  accent="text-rose-600" />
        </div>
      </div>

      {/* 筛选条 */}
      <div className="px-8 py-4 flex items-center gap-4 border-b border-gray-100 bg-white">
        <div className="flex items-center gap-1">
          {STATUS_TABS.map(t => (
            <button
              key={t.key}
              onClick={() => setTab(t.key)}
              className={`px-3 py-1.5 text-[12px] rounded-md transition ${
                tab === t.key
                  ? 'bg-brand-50 text-brand-700 font-medium'
                  : 'text-gray-600 hover:bg-gray-50'
              }`}
            >
              {t.label}
              {t.key !== 'all' && (
                <span className="ml-1 text-gray-400">{summary[t.key] ?? 0}</span>
              )}
            </button>
          ))}
        </div>
        <div className="ml-auto">
          <input
            value={keyword}
            onChange={e => setKeyword(e.target.value)}
            placeholder="搜索 Skill 名 / 节点 / 描述"
            className="w-[260px] px-3 py-1.5 text-[12px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400"
          />
        </div>
      </div>

      {/* 列表 */}
      <div className="p-8">
        {filtered.length === 0 ? (
          <EmptyState onCreate={() => navigate('/create')} />
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            {filtered.map(s => (
              <SkillCard
                key={s.id}
                skill={s}
                onClick={() => navigate(`/skills/${s.id}/edit`)}
                onDelete={(e) => {
                  e.stopPropagation()
                  if (window.confirm(`确认删除 Skill「${s.name}」？此操作不可恢复。`)) {
                    deleteSkill(s.id)
                  }
                }}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

function SummaryCard({ label, value, accent }) {
  return (
    <div className="bg-white border border-gray-200 rounded-lg px-4 py-3">
      <div className="text-[11px] text-gray-500">{label}</div>
      <div className={`text-[22px] font-semibold mt-0.5 ${accent}`}>{value}</div>
    </div>
  )
}

function SkillCard({ skill, onClick, onDelete }) {
  const status = SKILL_STATUS[skill.status] || SKILL_STATUS.draft
  const lastEval = skill.eval_records?.[0]
  const msgCount = skill.messages?.length || 0
  const fileCount = skill.file_ids?.length || 0

  return (
    <div
      onClick={onClick}
      className="bg-white border border-gray-200 rounded-xl p-5 hover:border-brand-400 hover:shadow-sm transition cursor-pointer flex flex-col gap-3"
    >
      {/* 头部 */}
      <div className="flex items-start justify-between gap-2">
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <h3 className="text-[14px] font-semibold text-gray-900 truncate">{skill.name}</h3>
            <span className={`text-[10px] px-1.5 py-0.5 rounded ${status.color} flex-shrink-0`}>
              {status.label}
            </span>
          </div>
          <p className="text-[12px] text-gray-500 mt-1 line-clamp-2 min-h-[32px]">
            {skill.desc || <span className="text-gray-300">— 暂无描述 —</span>}
          </p>
        </div>
        <button
          onClick={onDelete}
          title="删除"
          className="text-gray-300 hover:text-rose-500 text-[14px] flex-shrink-0"
        >
          ✕
        </button>
      </div>

      {/* 节点路径 */}
      <div className="text-[11px] text-gray-500 truncate" title={skill.node_path}>
        <span className="text-brand-600 mr-1">⇲</span>
        {skill.node_path || <span className="text-gray-300">未关联节点</span>}
      </div>

      {/* 指标 */}
      <div className="grid grid-cols-3 gap-2 text-center border-t border-gray-100 pt-3">
        <Metric label="文件"   value={fileCount} />
        <Metric label="对话"   value={msgCount} />
        <Metric
          label="评测得分"
          value={lastEval ? `${lastEval.score}` : '—'}
          highlight={lastEval && lastEval.score >= 60 ? 'text-emerald-600' : (lastEval ? 'text-amber-600' : '')}
        />
      </div>

      {/* 底部 */}
      <div className="flex items-center justify-between text-[11px] text-gray-400 border-t border-gray-100 pt-2.5">
        <span>{skill.version}</span>
        <span>{formatTime(skill.updated_at)}</span>
      </div>
    </div>
  )
}

function Metric({ label, value, highlight = '' }) {
  return (
    <div>
      <div className={`text-[14px] font-semibold ${highlight || 'text-gray-800'}`}>{value}</div>
      <div className="text-[10px] text-gray-400 mt-0.5">{label}</div>
    </div>
  )
}

function EmptyState({ onCreate }) {
  return (
    <div className="bg-white border border-dashed border-gray-300 rounded-xl py-16 flex flex-col items-center justify-center text-center">
      <div className="text-[40px] mb-2">🤖</div>
      <div className="text-[14px] text-gray-700 mb-1">还没有 Skill</div>
      <div className="text-[12px] text-gray-400 mb-4">
        {FEATURES.createSkill
          ? '从一个流程节点 + 几份文件开始，创建你的第一个 Agent Skill'
          : '可以到「上传 Skill」入口导入现有的 Skill 文档'}
      </div>
      {FEATURES.createSkill && (
        <button
          onClick={onCreate}
          className="px-4 py-1.5 text-[13px] rounded-md text-white bg-brand-600 hover:bg-brand-700"
        >
          ＋ 新建 Skill
        </button>
      )}
    </div>
  )
}

function formatTime(iso) {
  if (!iso) return ''
  const d = new Date(iso)
  if (Number.isNaN(d.getTime())) return ''
  const now = new Date()
  const diff = (now - d) / 1000
  if (diff < 60) return '刚刚'
  if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`
  if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`
  return formatSkillDateTime(iso).slice(5, 16)
}
