'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import { Play, RefreshCw } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendOpsJob } from '@/lib/backend'

function formatResult(value: unknown) {
  if (!value) return '-'
  return JSON.stringify(value, null, 2)
}

export default function AdminOpsJobsPage() {
  const [items, setItems] = useState<BackendOpsJob[]>([])
  const [selected, setSelected] = useState<BackendOpsJob | null>(null)
  const [runningKey, setRunningKey] = useState('')
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)

  async function reload() {
    setLoading(true)
    try {
      const result = await backend.adminOpsJobs()
      setItems(result.items)
      setSelected((current) => result.items.find((item) => item.key === current?.key) || result.items[0] || null)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '运维任务加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void reload()
  }, [])

  async function runJob(job: BackendOpsJob) {
    setRunningKey(job.key)
    setMessage('')
    setError('')
    try {
      const result = await backend.runAdminOpsJob(job.key)
      setSelected(result)
      setItems((current) => current.map((item) => item.key === job.key ? { ...item, lastResult: result.result as Record<string, unknown>, lastRunAt: result.finishedAt || new Date().toISOString() } : item))
      setMessage(`${job.name} 已执行`)
    } catch (err) {
      setError(err instanceof Error ? err.message : '运维任务执行失败')
    } finally {
      setRunningKey('')
    }
  }

  return (
    <AdminShell title="运维任务" description="人工触发少量白名单系统任务；会员运营和通知派发不在这里混放。">
      {(message || error) && (
        <div className={`mb-3 rounded-[4px] px-4 py-3 text-sm font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>
          {error || message}
        </div>
      )}

      <section className="grid h-[calc(100vh-112px)] min-h-[560px] overflow-hidden border border-line bg-white xl:grid-cols-[minmax(0,1fr)_380px]">
        <div className="min-h-0 flex flex-col overflow-hidden">
          <div className="flex shrink-0 flex-wrap items-center justify-between gap-2 border-b border-line px-3 py-2.5">
            <div className="text-sm font-extrabold text-ink">任务列表</div>
            <div className="flex gap-2">
              <Link href="/admin/system" className="h-9 rounded-[4px] border border-line px-3 py-2 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">系统健康</Link>
              <button type="button" onClick={() => void reload()} className="inline-flex h-9 items-center gap-2 rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
                <RefreshCw className="h-4 w-4" />
                刷新
              </button>
            </div>
          </div>
          <div className="min-h-0 flex-1 overflow-y-auto">
            {loading && <div className="px-5 py-8 text-sm font-bold text-muted">正在加载运维任务...</div>}
            {!loading && items.length === 0 && <div className="px-5 py-8 text-sm font-bold text-muted">暂无运维任务</div>}
            {!loading && items.map((job) => (
              <button key={job.key} type="button" onClick={() => setSelected(job)} className={`grid w-full gap-3 border-b border-line px-4 py-3 text-left hover:bg-bg lg:grid-cols-[1fr_120px_120px] lg:items-center ${selected?.key === job.key ? 'bg-bg' : ''}`}>
                <div>
                  <div className="text-sm font-extrabold text-ink">{job.name}</div>
                  <div className="mt-1 text-xs font-bold text-muted">{job.description}</div>
                </div>
                <div className="text-xs font-bold text-muted">{job.status || 'ready'}</div>
                <div className="lg:text-right">
                  <span className="text-xs font-bold text-soft">{job.lastRunAt || '未记录'}</span>
                </div>
              </button>
            ))}
          </div>
        </div>

        <aside className="min-h-0 overflow-y-auto border-l border-line bg-bg p-3">
          <div className="mb-2 text-sm font-extrabold text-ink">任务详情</div>
          {!selected ? (
            <div className="border border-dashed border-line bg-white px-3 py-8 text-center text-sm font-bold text-muted">选择任务查看详情</div>
          ) : (
            <div className="space-y-3">
              <section className="border border-line bg-white p-3">
                <div className="text-sm font-extrabold text-ink">{selected.name}</div>
                <div className="mt-1 text-xs font-bold leading-5 text-muted">{selected.description}</div>
                <button type="button" onClick={() => void runJob(selected)} disabled={runningKey === selected.key} className="mt-3 inline-flex h-9 items-center gap-2 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white disabled:bg-line-dark">
                  <Play className="h-4 w-4" />
                  {runningKey === selected.key ? '执行中...' : '手动运行'}
                </button>
              </section>
              <section className="border border-line bg-white p-3">
                <div className="mb-2 text-sm font-extrabold text-ink">最近结果</div>
                <pre className="max-h-[420px] overflow-auto text-[11px] leading-5 text-ink">{formatResult(selected.result || selected.lastResult)}</pre>
              </section>
            </div>
          )}
        </aside>
      </section>
    </AdminShell>
  )
}
