import { useCallback, useEffect, useState } from 'react'
import { api, ApiError } from '../api/client'
import {
  Button,
  Card,
  ErrorText,
  HoverTip,
  PageTitle,
  ProgressBar,
  StatusBadge,
  TableEmpty,
} from '../components/ui'
import { formatUnixNano } from '../lib/formatDate'
import {
  isTerminalJobStatus,
  jobErrorMessage,
  jobStatusBadgeClass,
  jobStatusLabel,
} from '../lib/jobStatus'
import { jobTemplateLabel } from '../lib/jobTemplate'
import type { JobData, Pagination } from '../types/api'

const PAGE_SIZE = 15

export function JobsPage() {
  const [jobs, setJobs] = useState<JobData[]>([])
  const [pagination, setPagination] = useState<Pagination | null>(null)
  const [page, setPage] = useState(1)
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)

  const load = useCallback(async () => {
    setError('')
    setLoading(true)
    try {
      const data = await api.get<{ list: JobData[]; pagination: Pagination }>('/api/v1/jobs', {
        auth: true,
        query: { page, pageSize: PAGE_SIZE },
      })
      setJobs(data.list ?? [])
      setPagination(data.pagination ?? null)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '載入失敗')
      setJobs([])
      setPagination(null)
    } finally {
      setLoading(false)
    }
  }, [page])

  useEffect(() => {
    load().catch(() => undefined)
  }, [load])

  useEffect(() => {
    const hasActive = jobs.some((j) => !isTerminalJobStatus(j.status))
    if (!hasActive) return
    const timer = window.setInterval(() => load().catch(() => undefined), 3000)
    return () => window.clearInterval(timer)
  }, [jobs, load])

  const totalPages = pagination?.totalPages ?? 1

  return (
    <div>
      <PageTitle title="背景任務" subtitle="歷史執行紀錄" />

      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <p className="text-sm text-ink-secondary">
          {pagination ? `共 ${pagination.total} 筆` : loading ? '載入中…' : '—'}
        </p>
        <Button variant="ghost" onClick={() => load().catch(() => undefined)} disabled={loading}>
          重新載入
        </Button>
      </div>

      <ErrorText message={error} />

      <Card className="overflow-hidden p-0">
        {loading && jobs.length === 0 ? (
          <TableEmpty>載入任務紀錄中…</TableEmpty>
        ) : jobs.length === 0 ? (
          <TableEmpty>尚無背景任務紀錄。在工作流中觸發的任務會出現在這裡。</TableEmpty>
        ) : (
          <ul className="divide-y divide-line">
            {jobs.map((job) => {
              const summary = job.progress?.summary?.trim()
              const updatedAt = formatUnixNano(job.update_at || job.create_at)
              const percentage = job.progress?.percentage ?? 0
              const errorMessage = jobErrorMessage(job)

              return (
                <li key={job.id} className="ac-job-history-row">
                  <div className="ac-job-history-grid">
                    <div className="ac-job-history-grid__meta">
                      <p className="ac-job-history-grid__title">
                        {jobTemplateLabel(job.template_type)}
                      </p>
                      {updatedAt ? (
                        <p className="ac-job-history-grid__time">{updatedAt}</p>
                      ) : null}
                    </div>

                    <div className="ac-job-history-grid__status">
                      <div className="ac-job-history-grid__status-badges">
                        <StatusBadge className={jobStatusBadgeClass(job.status)}>
                          {jobStatusLabel(job.status)}
                        </StatusBadge>
                        {errorMessage ? (
                          <HoverTip label={errorMessage} placement="bottom">
                            <button type="button" className="ac-job-error-btn">
                              查看錯誤
                            </button>
                          </HoverTip>
                        ) : null}
                      </div>
                      <span className="ac-job-history-grid__percent">{percentage}%</span>
                    </div>

                    <div className="ac-job-history-grid__progress">
                      <ProgressBar value={percentage} />
                    </div>

                    {summary ? (
                      <p className="ac-job-history-grid__summary">{summary}</p>
                    ) : null}
                  </div>
                </li>
              )
            })}
          </ul>
        )}
      </Card>

      {pagination && totalPages > 1 ? (
        <div className="mt-5 flex flex-wrap items-center justify-between gap-3">
          <p className="text-sm text-muted">
            第 {pagination.page} / {totalPages} 頁
          </p>
          <div className="flex gap-2">
            <Button
              variant="ghost"
              disabled={page <= 1 || loading}
              onClick={() => setPage((p) => Math.max(1, p - 1))}
            >
              上一頁
            </Button>
            <Button
              variant="ghost"
              disabled={page >= totalPages || loading}
              onClick={() => setPage((p) => p + 1)}
            >
              下一頁
            </Button>
          </div>
        </div>
      ) : null}
    </div>
  )
}