import { Fragment, useEffect, useMemo, useState } from 'react'
import {
  createApiKey,
  listApiKeys,
  revokeApiKey,
  getApiKeyStats,
  listSkills,
} from '../services/api.js'

// 时间戳（秒）格式化
function fmtTs(ts) {
  if (!ts) return '—'
  const n = Number(ts)
  if (!Number.isFinite(n)) return '—'
  const d = new Date(n * 1000)
  if (Number.isNaN(d.getTime())) return '—'
  const pad = x => String(x).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

function fmtSuccessRate(value) {
  if (value == null || value === '') return '—'
  if (typeof value === 'string' && value.trim().endsWith('%')) return value.trim()
  const n = Number(value)
  if (!Number.isFinite(n)) return '—'
  return n <= 1 ? `${(n * 100).toFixed(1)}%` : `${n.toFixed(1)}%`
}

const INVOKE_HOST = import.meta.env.VITE_PUBLIC_BASE_URL
  || (typeof window !== 'undefined' ? window.location.origin : 'https://zhenyuskill.com')

function buildCurl({ skillId, keyPrefix }) {
  const prefix = String(keyPrefix || '').replace(/\.+$/, '')
  return `curl -X POST "${INVOKE_HOST}/v1/skills/${skillId}/invoke" \\
  -H "Authorization: Bearer ${prefix}...<完整 Key>" \\
  -H "Content-Type: application/json" \\
  -d '{"input": "你的输入内容"}'`
}

function CopyButton({ text, label = '复制', className = '' }) {
  const [ok, setOk] = useState(false)
  async function copy() {
    try {
      await navigator.clipboard.writeText(text)
      setOk(true)
      setTimeout(() => setOk(false), 1500)
    } catch {
      // 降级方案
      const ta = document.createElement('textarea')
      ta.value = text
      document.body.appendChild(ta)
      ta.select()
      try { document.execCommand('copy'); setOk(true); setTimeout(() => setOk(false), 1500) } catch {}
      document.body.removeChild(ta)
    }
  }
  return (
    <button
      type="button"
      onClick={copy}
      className={[
        'inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-medium transition',
        ok ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
           : 'bg-white text-brand-700 border border-brand-200 hover:bg-brand-50',
        className,
      ].join(' ')}
    >
      {ok ? '已复制' : label}
    </button>
  )
}

function StatusTag({ status }) {
  const isActive = status === 'active'
  return (
    <span className={[
      'inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-medium',
      isActive
        ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
        : 'bg-gray-100 text-gray-500 border border-gray-200',
    ].join(' ')}>
      <span className={['w-1.5 h-1.5 rounded-full mr-1.5', isActive ? 'bg-emerald-500' : 'bg-gray-400'].join(' ')} />
      {isActive ? 'active' : 'revoked'}
    </span>
  )
}

function CreatedKeyModal({ data, onClose }) {
  if (!data) return null
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center px-4">
      <div className="absolute inset-0 bg-gray-900/40 backdrop-blur-sm" onClick={onClose} />
      <div className="relative bg-white rounded-2xl shadow-2xl w-full max-w-lg overflow-hidden border border-gray-100">
        <div className="px-6 py-5 border-b border-gray-100">
          <div className="flex items-center gap-2">
            <span className="w-8 h-8 rounded-lg bg-emerald-50 text-emerald-600 grid place-items-center text-base">✓</span>
            <div>
              <div className="text-base font-semibold text-gray-900">Key 创建成功</div>
              <div className="text-xs text-gray-500">{data.autoCopied ? '已自动复制到剪贴板，关闭前仍建议再核对一次' : '请立即复制保存，关闭后将无法再次查看完整 Key'}</div>
            </div>
          </div>
        </div>
        <div className="px-6 py-5 space-y-4">
          <div>
            <div className="text-xs text-gray-500 mb-1">Skill</div>
            <div className="text-sm text-gray-800">{data.skill_name || data.skill_id}</div>
          </div>
          <div>
            <div className="text-xs text-gray-500 mb-1">Key 名称</div>
            <div className="text-sm text-gray-800">{data.name || '—'}</div>
          </div>
          <div>
            <div className="flex items-center justify-between mb-1.5">
              <div className="text-xs text-gray-500">完整 API Key</div>
              <CopyButton text={data.key || ''} />
            </div>
            <div className="px-3 py-3 rounded-lg bg-gray-900 text-emerald-300 font-mono text-xs break-all leading-relaxed">
              {data.key}
            </div>
          </div>
          <div className="text-[11px] text-amber-700 bg-amber-50 border border-amber-200 rounded-md px-3 py-2 leading-relaxed">
            出于安全考虑，完整 Key 只会显示这一次。请保存到安全的地方（密码管理器、CI/CD 环境变量等）。
          </div>
        </div>
        <div className="px-6 py-4 bg-gray-50 border-t border-gray-100 flex justify-end">
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 transition"
          >
            我已保存
          </button>
        </div>
      </div>
    </div>
  )
}

function KeyDetailPanel({ keyRow }) {
  const [stats, setStats] = useState(null)
  const [loading, setLoading] = useState(true)
  const [err, setErr] = useState('')

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    setErr('')
    setStats(null)
    getApiKeyStats(keyRow.id)
      .then(r => { if (!cancelled) setStats(r) })
      .catch(e => { if (!cancelled) setErr(e.friendlyMessage || e.message || '加载失败') })
      .finally(() => { if (!cancelled) setLoading(false) })
    return () => { cancelled = true }
  }, [keyRow.id])

  const curl = useMemo(
    () => buildCurl({ skillId: keyRow.skill_id, keyPrefix: keyRow.key_prefix }),
    [keyRow.skill_id, keyRow.key_prefix]
  )

  return (
    <div className="bg-gray-50/60 border-t border-gray-100 px-4 sm:px-6 py-5 space-y-5">
      {/* 统计卡片 */}
      <div>
        <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">调用统计</div>
        {loading ? (
          <div className="text-sm text-gray-400 py-3">加载中…</div>
        ) : err ? (
          <div className="text-sm text-rose-600 py-3">{err}</div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 sm:gap-3">
            <StatCard label="今日调用" value={stats?.today_calls ?? 0} />
            <StatCard label="总调用" value={stats?.total_calls ?? 0} />
            <StatCard
              label="成功率"
              value={fmtSuccessRate(stats?.success_rate)}
            />
            <StatCard
              label="平均延迟"
              value={stats?.avg_latency_ms != null ? `${Math.round(stats.avg_latency_ms)} ms` : '—'}
            />
          </div>
        )}
      </div>

      {/* 最近调用 */}
      <div>
        <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">最近调用记录</div>
        <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
          {loading ? (
            <div className="p-4 text-sm text-gray-400">加载中…</div>
          ) : (stats?.recent_calls?.length ? (
            <div className="divide-y divide-gray-100">
              {stats.recent_calls.map((c, i) => {
                const statusNum = Number(c.response_status)
                const ok = c.response_status === 'success' || (Number.isFinite(statusNum) && statusNum >= 200 && statusNum < 300)
                return (
                  <div key={i} className="flex items-center gap-3 px-3 sm:px-4 py-2.5 text-xs sm:text-sm">
                    <span className={[
                      'inline-flex items-center justify-center w-12 sm:w-14 px-1.5 py-0.5 rounded text-[11px] font-mono font-medium',
                      ok ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700',
                    ].join(' ')}>{c.response_status ?? '—'}</span>
                    <span className="flex-1 min-w-0 truncate text-gray-700">{c.skill_name || '—'}</span>
                    <span className="text-gray-400 tabular-nums hidden sm:inline">{c.latency_ms != null ? `${c.latency_ms} ms` : '—'}</span>
                    <span className="text-gray-400 tabular-nums">{fmtTs(c.ts)}</span>
                  </div>
                )
              })}
            </div>
          ) : (
            <div className="p-4 text-sm text-gray-400">暂无调用记录</div>
          ))}
        </div>
      </div>

      {/* curl 示例 */}
      <div>
        <div className="flex items-center justify-between mb-2">
          <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide">curl 调用示例</div>
          <CopyButton text={curl} label="复制命令" />
        </div>
        <pre className="bg-gray-900 text-emerald-200 text-[12px] sm:text-[13px] leading-relaxed font-mono px-4 py-3 rounded-lg overflow-x-auto whitespace-pre">{curl}</pre>
        <div className="text-[11px] text-gray-400 mt-1.5">
          请把示例里的 <code className="px-1 py-0.5 bg-gray-100 rounded">...&lt;完整 Key&gt;</code> 替换为创建时保存的完整 Key
        </div>
      </div>
    </div>
  )
}

function StatCard({ label, value }) {
  return (
    <div className="bg-white rounded-lg border border-gray-200 px-3 py-2.5">
      <div className="text-[11px] text-gray-500">{label}</div>
      <div className="text-base sm:text-lg font-semibold text-gray-900 mt-0.5 tabular-nums">{value}</div>
    </div>
  )
}

export default function ApiAccess() {
  const [skills, setSkills] = useState([])
  const [keys, setKeys] = useState([])
  const [loading, setLoading] = useState(true)
  const [err, setErr] = useState('')

  // 表单状态
  const [skillId, setSkillId] = useState('')
  const [keyName, setKeyName] = useState('')
  const [creating, setCreating] = useState(false)
  const [createErr, setCreateErr] = useState('')

  // 创建成功后一次性展示
  const [newKeyData, setNewKeyData] = useState(null)

  // 展开行
  const [expanded, setExpanded] = useState(null)

  // 吊销中
  const [revokingId, setRevokingId] = useState(null)
  const publishedSkills = useMemo(() => skills.filter(s => s.status === 'published'), [skills])

  async function loadKeys() {
    try {
      const r = await listApiKeys()
      setKeys(Array.isArray(r?.data) ? r.data : (r?.list || []))
    } catch (e) {
      setErr(e.friendlyMessage || e.message || '加载失败')
    }
  }

  async function loadSkills() {
    try {
      const r = await listSkills()
      setSkills(r?.list || [])
    } catch {
      setSkills([])
    }
  }

  useEffect(() => {
    let alive = true
    setLoading(true)
    Promise.all([loadKeys(), loadSkills()]).finally(() => { if (alive) setLoading(false) })
    return () => { alive = false }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  async function handleCreate(e) {
    e?.preventDefault?.()
    setCreateErr('')
    if (!skillId) { setCreateErr('请选择 Skill'); return }
    if (!keyName.trim()) { setCreateErr('请填写 Key 名称'); return }
    setCreating(true)
    try {
      const data = await createApiKey(skillId, keyName.trim())
      setKeyName('')
      // 创建成功后自动复制完整 key、并提示用户保存
      let autoCopied = false
      if (data?.key && typeof navigator !== 'undefined' && navigator.clipboard) {
        try {
          await navigator.clipboard.writeText(data.key)
          autoCopied = true
        } catch {}
      }
      setNewKeyData({ ...data, autoCopied })
      await loadKeys()
    } catch (e) {
      setCreateErr(e.response?.data?.error || e.friendlyMessage || e.message || '创建失败')
    } finally {
      setCreating(false)
    }
  }

  async function handleRevoke(row) {
    if (row.status !== 'active') return
    if (!confirm(`确认吊销 Key「${row.name}」吗？吊销后无法恢复。`)) return
    setRevokingId(row.id)
    try {
      await revokeApiKey(row.id)
      await loadKeys()
    } catch (e) {
      alert(e.response?.data?.error || e.friendlyMessage || e.message || '吊销失败')
    } finally {
      setRevokingId(null)
    }
  }

  function toggleExpand(id) {
    setExpanded(prev => prev === id ? null : id)
  }

  return (
    <div className="px-4 sm:px-6 lg:px-8 py-6 sm:py-8 max-w-6xl mx-auto">
      {/* 标题 */}
      <div className="mb-6 sm:mb-8">
        <h1 className="text-xl sm:text-2xl font-bold text-gray-900 flex items-center gap-2">
          <span className="text-brand-600">🔌</span> API 接入
        </h1>
        <p className="text-sm text-gray-500 mt-1.5 leading-relaxed">
          为已发布的 Skill 创建 API Key，通过 HTTP 接口在你的应用中调用 Skill 能力。每个 Key 仅对应一个 Skill，完整 Key 创建后只显示一次。
        </p>
      </div>

      {/* 创建 Key */}
      <section className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden mb-6">
        <div className="px-4 sm:px-6 py-4 border-b border-gray-100">
          <h2 className="text-sm font-semibold text-gray-900">创建新 Key</h2>
          <p className="text-xs text-gray-500 mt-0.5">选择一个 Skill 并为 Key 取一个易识别的名字</p>
        </div>
        <form onSubmit={handleCreate} className="px-4 sm:px-6 py-5 grid grid-cols-1 sm:grid-cols-12 gap-3 sm:gap-4 items-end">
          <div className="sm:col-span-5">
            <label className="block text-xs font-medium text-gray-700 mb-1.5">关联 Skill</label>
            <select
              value={skillId}
              onChange={e => setSkillId(e.target.value)}
              className="w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-sm text-gray-800 focus:border-brand-500 focus:ring-2 focus:ring-brand-100 outline-none transition"
            >
              <option value="">— 请选择 Skill —</option>
              {publishedSkills.map(s => (
                <option key={s.id} value={s.id}>
                  {s.name}{s.status ? `（${s.status}）` : ''}
                </option>
              ))}
            </select>
            <div className="mt-1 text-[11px] text-gray-400">仅已上线 Skill 可创建 API Key。</div>
          </div>
          <div className="sm:col-span-5">
            <label className="block text-xs font-medium text-gray-700 mb-1.5">Key 名称</label>
            <input
              value={keyName}
              onChange={e => setKeyName(e.target.value)}
              placeholder="例如：production-server / 测试环境"
              maxLength={50}
              className="w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-sm text-gray-800 placeholder:text-gray-400 focus:border-brand-500 focus:ring-2 focus:ring-brand-100 outline-none transition"
            />
          </div>
          <div className="sm:col-span-2">
            <button
              type="submit"
              disabled={creating}
              className="w-full h-10 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition"
            >
              {creating ? '创建中…' : '创建 Key'}
            </button>
          </div>
          {createErr && (
            <div className="sm:col-span-12 text-xs text-rose-600 bg-rose-50 border border-rose-200 rounded-md px-3 py-2">
              {createErr}
            </div>
          )}
        </form>
      </section>

      {/* Key 列表 */}
      <section className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
        <div className="px-4 sm:px-6 py-4 border-b border-gray-100 flex items-center justify-between">
          <div>
            <h2 className="text-sm font-semibold text-gray-900">我的 API Key</h2>
            <p className="text-xs text-gray-500 mt-0.5">点击行可展开查看调用统计与示例</p>
          </div>
          <span className="text-xs text-gray-400 tabular-nums">共 {keys.length} 个</span>
        </div>

        {loading ? (
          <div className="px-6 py-10 text-center text-sm text-gray-400">加载中…</div>
        ) : err ? (
          <div className="px-6 py-10 text-center text-sm text-rose-600">{err}</div>
        ) : keys.length === 0 ? (
          <div className="px-6 py-12 text-center">
            <div className="text-4xl mb-2">🗝️</div>
            <div className="text-sm text-gray-600">还没有 API Key</div>
            <div className="text-xs text-gray-400 mt-1">在上方创建第一个 Key 开始使用 API</div>
          </div>
        ) : (
          <>
            {/* 桌面表格 */}
            <div className="hidden md:block overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 text-xs text-gray-500">
                  <tr>
                    <th className="text-left font-medium px-4 py-2.5">Skill</th>
                    <th className="text-left font-medium px-4 py-2.5">Key 名称</th>
                    <th className="text-left font-medium px-4 py-2.5">Key 前缀</th>
                    <th className="text-left font-medium px-4 py-2.5">状态</th>
                    <th className="text-right font-medium px-4 py-2.5 tabular-nums">调用次数</th>
                    <th className="text-left font-medium px-4 py-2.5">创建时间</th>
                    <th className="text-right font-medium px-4 py-2.5">操作</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {keys.map(row => {
                    const isOpen = expanded === row.id
                    return (
                      <Fragment key={row.id}>
                        <tr
                          onClick={() => toggleExpand(row.id)}
                          className={[
                            'cursor-pointer transition',
                            isOpen ? 'bg-brand-50/50' : 'hover:bg-gray-50'
                          ].join(' ')}
                        >
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-2">
                              <span className={['inline-block transition-transform text-gray-400 text-xs', isOpen ? 'rotate-90' : ''].join(' ')}>▶</span>
                              <span className="text-gray-800">{row.skill_name || row.skill_id}</span>
                            </div>
                          </td>
                          <td className="px-4 py-3 text-gray-700">{row.name || '—'}</td>
                          <td className="px-4 py-3">
                            <code className="px-1.5 py-0.5 bg-gray-100 rounded text-[12px] font-mono text-gray-700">{row.key_prefix}…</code>
                          </td>
                          <td className="px-4 py-3"><StatusTag status={row.status} /></td>
                          <td className="px-4 py-3 text-right tabular-nums text-gray-700">{row.total_calls ?? 0}</td>
                          <td className="px-4 py-3 text-gray-500 tabular-nums">{fmtTs(row.created_at)}</td>
                          <td className="px-4 py-3 text-right">
                            {row.status === 'active' ? (
                              <button
                                onClick={e => { e.stopPropagation(); handleRevoke(row) }}
                                disabled={revokingId === row.id}
                                className="text-xs text-rose-600 hover:text-rose-700 hover:bg-rose-50 px-2.5 py-1 rounded-md transition disabled:opacity-50"
                              >
                                {revokingId === row.id ? '吊销中…' : '吊销'}
                              </button>
                            ) : (
                              <span className="text-xs text-gray-400 px-2.5 py-1">已吊销</span>
                            )}
                          </td>
                        </tr>
                        {isOpen && (
                          <tr>
                            <td colSpan={7} className="p-0">
                              <KeyDetailPanel keyRow={row} />
                            </td>
                          </tr>
                        )}
                      </Fragment>
                    )
                  })}
                </tbody>
              </table>
            </div>

            {/* 移动端卡片 */}
            <div className="md:hidden divide-y divide-gray-100">
              {keys.map(row => {
                const isOpen = expanded === row.id
                return (
                  <div key={row.id}>
                    <div
                      onClick={() => toggleExpand(row.id)}
                      className={['px-4 py-3 cursor-pointer transition', isOpen ? 'bg-brand-50/50' : 'active:bg-gray-50'].join(' ')}
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-1.5">
                            <span className={['text-gray-400 text-xs transition-transform', isOpen ? 'rotate-90' : ''].join(' ')}>▶</span>
                            <span className="font-medium text-gray-900 text-sm truncate">{row.name || '—'}</span>
                          </div>
                          <div className="text-xs text-gray-500 mt-0.5 truncate">{row.skill_name || row.skill_id}</div>
                          <div className="flex items-center gap-2 mt-1.5">
                            <code className="px-1.5 py-0.5 bg-gray-100 rounded text-[11px] font-mono text-gray-700">{row.key_prefix}…</code>
                            <StatusTag status={row.status} />
                          </div>
                          <div className="flex items-center gap-3 text-[11px] text-gray-400 mt-1.5 tabular-nums">
                            <span>{row.total_calls ?? 0} 次调用</span>
                            <span>{fmtTs(row.created_at)}</span>
                          </div>
                        </div>
                        <div className="flex-shrink-0">
                          {row.status === 'active' ? (
                            <button
                              onClick={e => { e.stopPropagation(); handleRevoke(row) }}
                              disabled={revokingId === row.id}
                              className="text-xs text-rose-600 hover:bg-rose-50 px-2 py-1 rounded-md transition disabled:opacity-50"
                            >
                              {revokingId === row.id ? '…' : '吊销'}
                            </button>
                          ) : (
                            <span className="text-xs text-gray-400">已吊销</span>
                          )}
                        </div>
                      </div>
                    </div>
                    {isOpen && <KeyDetailPanel keyRow={row} />}
                  </div>
                )
              })}
            </div>
          </>
        )}
      </section>

      <CreatedKeyModal data={newKeyData} onClose={() => setNewKeyData(null)} />
    </div>
  )
}
