import { useCallback, useEffect, useMemo, useState } from "react"
import {
  Alert,
  Badge,
  Button,
  Card,
  Col,
  Empty,
  Modal,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tag,
  Typography,
  message,
} from "antd"
import type { TableColumnsType } from "antd"
import { PlayCircleOutlined, ReloadOutlined, SyncOutlined, WarningOutlined } from "@ant-design/icons"
import { listTaskRuns, listTasks, runTask, type TaskItem, type TaskRunLog } from "../api/tasks"

const { Text, Title, Paragraph } = Typography

const STATUS_META: Record<string, { label: string; color: "success" | "processing" | "error" | "default" | "warning" }> = {
  running: { label: "运行中", color: "processing" },
  success: { label: "成功", color: "success" },
  failed: { label: "失败", color: "error" },
  skipped: { label: "跳过", color: "warning" },
}

function statusBadge(status?: string | null) {
  if (!status) return <Badge status="default" text="未执行" />
  const meta = STATUS_META[status] || { label: status, color: "default" as const }
  return <Badge status={meta.color} text={meta.label} />
}

function fmtTime(value?: string | null) {
  if (!value) return "-"
  const hasTimezone = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(value)
  const date = new Date(hasTimezone ? value : `${value}Z`)
  if (Number.isNaN(date.getTime())) return "-"
  return date.toLocaleString("zh-CN", { hour12: false })
}

function fmtDuration(value?: number | null) {
  if (value == null) return "-"
  if (value < 1000) return `${value} ms`
  return `${(value / 1000).toFixed(2)} s`
}

function jsonPreview(value: Record<string, unknown> | null | undefined) {
  if (!value) return "-"
  return JSON.stringify(value)
}

export default function AdminTasks() {
  const [loading, setLoading] = useState(true)
  const [tasks, setTasks] = useState<TaskItem[]>([])
  const [runs, setRuns] = useState<TaskRunLog[]>([])
  const [total, setTotal] = useState(0)
  const [selectedTask, setSelectedTask] = useState<string | undefined>(undefined)
  const [status, setStatus] = useState<string | undefined>(undefined)
  const [runningKey, setRunningKey] = useState<string | null>(null)
  const [detail, setDetail] = useState<TaskRunLog | null>(null)

  const reload = useCallback(async () => {
    setLoading(true)
    try {
      const [taskRes, runRes] = await Promise.all([
        listTasks(),
        listTaskRuns({ task_key: selectedTask, status, limit: 50 }),
      ])
      setTasks(taskRes.data ?? [])
      setRuns(runRes.data?.items ?? [])
      setTotal(runRes.data?.total ?? 0)
    } catch {
      message.error("加载任务中心失败")
    } finally {
      setLoading(false)
    }
  }, [selectedTask, status])

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

  const stats = useMemo(() => {
    const running = tasks.filter((item) => item.running || item.latest_run?.status === "running").length
    const failed = tasks.filter((item) => item.latest_run?.status === "failed").length
    const success = tasks.filter((item) => item.latest_run?.status === "success").length
    return { total: tasks.length, running, failed, success }
  }, [tasks])

  const handleRun = async (task: TaskItem) => {
    setRunningKey(task.key)
    try {
      const res = await runTask(task.key)
      if (res.data?.accepted === false) {
        message.warning(res.data.reason || "任务正在运行")
      } else {
        message.success("任务执行完成")
      }
      await reload()
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "任务执行失败")
      await reload()
    } finally {
      setRunningKey(null)
    }
  }

  const taskColumns: TableColumnsType<TaskItem> = [
    {
      title: "任务",
      key: "task",
      width: 260,
      render: (_value, row) => (
        <Space orientation="vertical" size={0}>
          <Space>
            <Text strong>{row.name}</Text>
            <Tag>{row.group}</Tag>
          </Space>
          <Text type="secondary" style={{ fontSize: 12 }}>{row.key}</Text>
        </Space>
      ),
    },
    { title: "说明", dataIndex: "description", width: 360 },
    { title: "频率", dataIndex: "interval_label", width: 120 },
    { title: "最近状态", key: "status", width: 120, render: (_value, row) => statusBadge(row.running ? "running" : row.latest_run?.status) },
    { title: "最近执行", key: "latest", width: 180, render: (_value, row) => fmtTime(row.latest_run?.started_at) },
    { title: "耗时", key: "duration", width: 100, render: (_value, row) => fmtDuration(row.latest_run?.duration_ms) },
    { title: "失败次数", dataIndex: "failed_runs", width: 90, align: "center", render: (value: number) => value > 0 ? <Tag color="red">{value}</Tag> : <Tag>0</Tag> },
    {
      title: "操作",
      key: "action",
      width: 120,
      align: "right",
      render: (_value, row) => (
        <Button
          size="small"
          type="primary"
          icon={<PlayCircleOutlined />}
          disabled={!row.manual_enabled || row.running}
          loading={runningKey === row.key}
          onClick={() => handleRun(row)}
        >
          立即执行
        </Button>
      ),
    },
  ]

  const runColumns: TableColumnsType<TaskRunLog> = [
    { title: "时间", dataIndex: "started_at", width: 170, render: fmtTime },
    { title: "任务", dataIndex: "task_name", width: 160 },
    { title: "触发", dataIndex: "trigger_type", width: 90, render: (value: string) => <Tag>{value === "manual" ? "手动" : "自动"}</Tag> },
    { title: "状态", dataIndex: "status", width: 100, render: statusBadge },
    { title: "耗时", dataIndex: "duration_ms", width: 100, render: fmtDuration },
    { title: "摘要", dataIndex: "summary", ellipsis: true, render: jsonPreview },
    {
      title: "详情",
      key: "detail",
      width: 90,
      align: "right",
      render: (_value, row) => <Button size="small" onClick={() => setDetail(row)}>查看</Button>,
    },
  ]

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row justify="space-between" align="bottom">
        <Col>
          <Title level={3}>任务中心</Title>
          <Paragraph type="secondary">查看自动任务执行状态、运行日志，并手动触发关键后台任务。</Paragraph>
        </Col>
        <Col>
          <Button icon={<ReloadOutlined />} loading={loading} onClick={reload}>刷新</Button>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={6}><Card variant="outlined"><Statistic title="任务数量" value={stats.total} prefix={<SyncOutlined />} /></Card></Col>
        <Col xs={24} sm={6}><Card variant="outlined"><Statistic title="运行中" value={stats.running} styles={{ content: { color: stats.running ? "#1677ff" : undefined } }} /></Card></Col>
        <Col xs={24} sm={6}><Card variant="outlined"><Statistic title="最近成功" value={stats.success} styles={{ content: { color: "#52c41a" } }} /></Card></Col>
        <Col xs={24} sm={6}><Card variant="outlined"><Statistic title="最近失败" value={stats.failed} prefix={<WarningOutlined />} styles={{ content: { color: stats.failed ? "#ff4d4f" : undefined } }} /></Card></Col>
      </Row>

      <Alert
        type="info"
        showIcon
        title="任务手动执行会写入运行日志"
        description="如果任务已在本进程运行，系统会跳过新的执行请求，避免重复处理。跨进程任务锁后续可以继续升级为数据库级锁。"
      />

      <Card variant="outlined" title="任务列表">
        <Table
          rowKey="key"
          loading={loading}
          columns={taskColumns}
          dataSource={tasks}
          pagination={false}
          scroll={{ x: 1320 }}
          locale={{ emptyText: <Empty description="暂无任务" /> }}
        />
      </Card>

      <Card
        variant="outlined"
        title={
          <Space wrap>
            <span>运行日志</span>
            <Select
              allowClear
              placeholder="筛选任务"
              style={{ width: 220 }}
              value={selectedTask}
              onChange={setSelectedTask}
              options={tasks.map((item) => ({ label: item.name, value: item.key }))}
            />
            <Select
              allowClear
              placeholder="筛选状态"
              style={{ width: 140 }}
              value={status}
              onChange={setStatus}
              options={[
                { label: "成功", value: "success" },
                { label: "失败", value: "failed" },
                { label: "运行中", value: "running" },
              ]}
            />
          </Space>
        }
      >
        <Table
          rowKey="id"
          loading={loading}
          columns={runColumns}
          dataSource={runs}
          pagination={{ pageSize: 20, total, showSizeChanger: false }}
          scroll={{ x: 980 }}
          locale={{ emptyText: <Empty description="暂无运行日志" /> }}
        />
      </Card>

      <Modal title="运行详情" open={!!detail} onCancel={() => setDetail(null)} footer={null} width={720}>
        {detail && (
          <Space orientation="vertical" size="middle" style={{ width: "100%" }}>
            <Space wrap>
              <Text strong>{detail.task_name}</Text>
              {statusBadge(detail.status)}
              <Tag>{detail.trigger_type === "manual" ? "手动" : "自动"}</Tag>
            </Space>
            <Text type="secondary">开始：{fmtTime(detail.started_at)} · 结束：{fmtTime(detail.finished_at)} · 耗时：{fmtDuration(detail.duration_ms)}</Text>
            {detail.error_message && <Alert type="error" showIcon title="错误信息" description={detail.error_message} />}
            <pre style={{ maxHeight: 360, overflow: "auto", background: "#f6f8fa", padding: 12, borderRadius: 6 }}>
              {JSON.stringify(detail.summary ?? {}, null, 2)}
            </pre>
          </Space>
        )}
      </Modal>
    </Space>
  )
}
