import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import api from '@/lib/api'
import { FilterableTable } from '@/components/FilterableTable'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { MetricCard } from '@/components/MetricCard'
import { useState } from 'react'

export function SchedulerManagementPage() {
  const queryClient = useQueryClient()
  const [editingId, setEditingId] = useState<number | null>(null)
  const [editCron, setEditCron] = useState('')

  const { data: tasksData, isLoading } = useQuery({
    queryKey: ['scheduler/tasks'],
    queryFn: () => api.get('/scheduler'),
  })

  const toggleMutation = useMutation({
    mutationFn: (data: { id: number; is_enabled: boolean }) =>
      api.patch(`/scheduler/${data.id}`, { is_enabled: data.is_enabled }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['scheduler/tasks'] }),
  })

  const updateCronMutation = useMutation({
    mutationFn: (data: { id: number; cron_expr: string }) =>
      api.patch(`/scheduler/${data.id}`, { cron_expr: data.cron_expr }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scheduler/tasks'] })
      setEditingId(null)
    },
  })

  const triggerMutation = useMutation({
    mutationFn: (id: number) => api.post(`/scheduler/${id}/trigger`),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['scheduler/tasks'] }),
  })

  const tasks = (tasksData as any)?.data || []

  const enabledCount = tasks.filter((t: any) => t.is_enabled).length
  const successCount = tasks.filter((t: any) => t.last_status === 'success').length
  const failedCount = tasks.filter((t: any) => t.last_status === 'failed').length
  const runningCount = tasks.filter((t: any) => t.last_status === 'running').length

  if (isLoading) {
    return <LoadingSpinner text="加载调度任务..." />
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">调度管理</h1>
          <p className="mt-0.5 text-xs text-muted-foreground">定时任务调度引擎 · 查看与启停</p>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <MetricCard title="总任务数" value={tasks.length} format="number" description="所有注册的调度任务" />
        <MetricCard title="启用中" value={enabledCount} format="number" description="当前启用的任务数" status="good" />
        <MetricCard title="成功执行" value={successCount} format="number" description="上次执行成功的任务数" status="good" />
        <MetricCard title="执行失败" value={failedCount} format="number" description="上次执行失败的任务数" status={failedCount > 0 ? 'bad' : 'good'} />
      </div>

      <CollapsibleSection title={`调度任务列表 (${tasks.length})`} subtitle="查看、启停、手动触发调度任务">
        <FilterableTable
          data={tasks}
          sortOptions={[
            { key: 'task_name', label: '任务名' },
            { key: 'last_run_at', label: '上次执行' },
            { key: 'last_status', label: '状态' },
          ]}
          defaultSort="task_name"
          defaultOrder="asc"
          columns={[
            { key: 'task_name', label: '任务名称' },
            { key: 'description', label: '描述' },
            { key: 'cron_expr', label: 'Cron表达式', render: (r) => (
              editingId === r.id ? (
                <div className="flex gap-1">
                  <input
                    type="text"
                    value={editCron}
                    onChange={(e) => setEditCron(e.target.value)}
                    className="w-32 rounded border px-2 py-0.5 text-xs"
                  />
                  <button
                    onClick={() => updateCronMutation.mutate({ id: r.id, cron_expr: editCron })}
                    className="rounded bg-primary px-2 py-0.5 text-xs text-primary-foreground"
                  >保存</button>
                  <button
                    onClick={() => setEditingId(null)}
                    className="rounded bg-muted px-2 py-0.5 text-xs"
                  >取消</button>
                </div>
              ) : (
                <span className="font-mono text-xs">{r.cron_expr}</span>
              )
            )},
            { key: 'is_enabled', label: '启用', align: 'center', render: (r) => (
              <button
                onClick={() => toggleMutation.mutate({ id: r.id, is_enabled: !r.is_enabled })}
                className={`rounded px-2 py-0.5 text-xs ${r.is_enabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}
              >
                {r.is_enabled ? '启用中' : '已停用'}
              </button>
            )},
            { key: 'last_status', label: '上次状态', align: 'center', render: (r) => {
              if (!r.last_status) return <span className="text-xs text-muted-foreground">未执行</span>
              const colors: Record<string, string> = { success: 'bg-green-100 text-green-700', failed: 'bg-red-100 text-red-700', running: 'bg-blue-100 text-blue-700' }
              const labels: Record<string, string> = { success: '成功', failed: '失败', running: '运行中' }
              return <span className={`rounded px-2 py-0.5 text-xs ${colors[r.last_status] || ''}`}>{labels[r.last_status] || r.last_status}</span>
            }},
            { key: 'last_run_at', label: '上次执行时间', render: (r) => r.last_run_at ? (r.last_run_at as string).substring(0, 19).replace('T', ' ') : '-' },
            { key: 'actions', label: '操作', align: 'center', render: (r) => (
              <div className="flex gap-1">
                <button
                  onClick={() => triggerMutation.mutate(r.id)}
                  disabled={triggerMutation.isPending}
                  className="rounded bg-primary px-2 py-0.5 text-xs text-primary-foreground hover:opacity-80"
                >手动触发</button>
                <button
                  onClick={() => { setEditingId(r.id); setEditCron(r.cron_expr) }}
                  className="rounded bg-muted px-2 py-0.5 text-xs"
                >编辑</button>
              </div>
            )},
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
