import { useCallback, useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { api } from '../api/client'
import { ApiError } from '../api/client'
import { Card, PageTitle, ProgressBar, StatusBadge } from '../components/ui'
import { isTerminalJobStatus, jobStatusBadgeClass, jobStatusLabel } from '../lib/jobStatus'
import type { JobData, JobEventData } from '../types/api'

export function JobDetailPage() {
  const { id } = useParams()
  const [job, setJob] = useState<JobData | null>(null)
  const [events, setEvents] = useState<JobEventData[]>([])
  const [error, setError] = useState('')

  const load = useCallback(async () => {
    if (!id) return
    const [j, ev] = await Promise.all([
      api.get<JobData>(`/api/v1/jobs/${id}`, { auth: true }),
      api.get<{ list: JobEventData[] }>(`/api/v1/jobs/${id}/events`, {
        auth: true,
        query: { limit: 50 },
      }),
    ])
    setJob(j)
    setEvents(ev.list)
  }, [id])

  useEffect(() => {
    load().catch((e: ApiError) => setError(e.message))
  }, [load])

  useEffect(() => {
    if (!job || isTerminalJobStatus(job.status)) return
    const timer = window.setInterval(() => {
      load().catch(() => {})
    }, 3000)
    return () => window.clearInterval(timer)
  }, [job, load])

  if (error) return <p className="text-rose-600">{error}</p>
  if (!job) return <p className="text-ink-secondary">載入中…</p>

  return (
    <div>
      <PageTitle
        title={`Job ${id?.slice(0, 8)}…`}
        subtitle={`${jobStatusLabel(job.status)} · ${job.phase}`}
      />
      <Card className="ac-island-card mb-4">
        <div className="flex flex-wrap items-center gap-3">
          <StatusBadge className={jobStatusBadgeClass(job.status)}>
            {jobStatusLabel(job.status)}
          </StatusBadge>
          <span className="text-sm text-ink-secondary">{job.progress.summary || '—'}</span>
        </div>
        <ProgressBar value={job.progress.percentage} className="mt-3 h-3" />
        <p className="mt-1 text-sm font-bold text-ink-secondary">{job.progress.percentage}%</p>
      </Card>
      <Link
        to="/jobs"
        className="mb-4 inline-block rounded-[var(--radius-pill)] border border-line bg-surface px-4 py-2 text-sm font-medium text-brand hover:bg-brand-soft"
      >
        ← 返回任務列表
      </Link>
      <div className="grid gap-4 lg:grid-cols-2">
        <Card>
          <pre className="overflow-auto text-xs">{JSON.stringify(job, null, 2)}</pre>
        </Card>
        <Card>
          <h2 className="font-medium">Events</h2>
          <ul className="mt-3 max-h-[32rem] space-y-2 overflow-auto text-sm">
            {events.map((e) => (
              <li key={e.id} className="rounded-[var(--radius-md)] border border-line bg-surface-muted p-3">
                <div className="font-mono text-xs font-semibold text-ink-secondary">{e.type}</div>
                <div>{e.message}</div>
              </li>
            ))}
          </ul>
        </Card>
      </div>
    </div>
  )
}