import { useMemo, useState } from 'react'
import { useNavigate } from '@tanstack/react-router'
import { CheckCircle, Clock, RefreshCw, XCircle } from 'lucide-react'
import type { TaskLog } from '@/api'
import { useLogs } from '@/api/hooks'
import { Button, Card, PageHeader, Select } from '@/components/ui'
import { formatDateTime, formatDuration } from '@/lib/format'

export default function Logs() {
  const navigate = useNavigate()
  const [status, setStatus] = useState('')
  const { data, isLoading, refetch, isFetching } = useLogs({
    page: 1,
    page_size: 50,
    status: status || undefined,
  })

  const logs = useMemo(() => {
    if (Array.isArray(data)) return data as TaskLog[]
    if (data && Array.isArray((data as any).data)) return (data as any).data as TaskLog[]
    return [] as TaskLog[]
  }, [data])

  return (
    <div>
      <PageHeader
        title="执行日志"
        description="任务执行记录（简版，完整能力见历史记录）"
        actions={
          <>
            <Button variant="secondary" onClick={() => navigate({ to: '/history', search: {} as any })}>
              打开历史记录
            </Button>
            <Button variant="secondary" onClick={() => refetch()} disabled={isFetching}>
              <RefreshCw size={14} className={isFetching ? 'animate-spin' : ''} />
              刷新
            </Button>
          </>
        }
      />

      <div className="mb-4 flex items-center gap-2">
        <Select value={status} onChange={(e) => setStatus(e.target.value)}>
          <option value="">全部状态</option>
          <option value="success">成功</option>
          <option value="failed">失败</option>
          <option value="running">运行中</option>
          <option value="timeout">超时</option>
          <option value="cancelled">已取消</option>
        </Select>
      </div>

      <div className="space-y-3">
        {isLoading ? (
          <Card className="p-6 text-sm text-[var(--text-muted)]">加载中...</Card>
        ) : logs.length === 0 ? (
          <Card className="p-8 text-center text-sm text-[var(--text-muted)]">暂无日志</Card>
        ) : (
          logs.map((log) => (
            <Card key={log.id} className="p-4">
              <div className="mb-2 flex items-center justify-between gap-3">
                <div className="flex min-w-0 items-center gap-3">
                  {log.status === 'success' ? (
                    <CheckCircle size={18} className="shrink-0 text-emerald-500" />
                  ) : log.status === 'failed' || log.status === 'timeout' ? (
                    <XCircle size={18} className="shrink-0 text-red-500" />
                  ) : (
                    <Clock size={18} className="shrink-0 text-amber-500" />
                  )}
                  <div className="min-w-0">
                    <div className="truncate font-medium">{log.task_name || log.task_id}</div>
                    <div className="text-xs text-[var(--text-muted)]">
                      {formatDateTime(log.start_time || log.created_at)}
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-3 text-xs">
                  <span className="rounded bg-[var(--bg-tertiary)] px-2 py-0.5">{log.status}</span>
                  {log.duration > 0 ? <span className="text-[var(--text-muted)]">{formatDuration(log.duration)}</span> : null}
                </div>
              </div>
              {log.command ? (
                <div className="rounded bg-[var(--bg-primary)] p-2 font-mono text-xs text-[var(--text-secondary)]">
                  {log.command}
                </div>
              ) : null}
            </Card>
          ))
        )}
      </div>
    </div>
  )
}
