import { useEffect, useState } from 'react'
import { RefreshCw, Search, Trash2 } from 'lucide-react'
import { LOG_CATEGORY } from '@/api'
import { api } from '@/api'
import { useAppLogs } from '@/api/hooks'
import { Button, Card, Input, Modal, PageHeader, Select, Tabs } from '@/components/ui'
import { formatDateTime } from '@/lib/format'
import { toast } from '@/lib/toast'

const TABS = [
  { value: LOG_CATEGORY.SYSTEM_NOTICE, label: '系统事件' },
  { value: LOG_CATEGORY.PUSH_LOG, label: '推送日志' },
  { value: LOG_CATEGORY.LOGIN_LOG, label: '登录日志' },
  { value: LOG_CATEGORY.SCHEDULER_LOG, label: '调度日志' },
]

export default function MessageLogs() {
  const [page, setPage] = useState(1)
  const [category, setCategory] = useState<string>(LOG_CATEGORY.SYSTEM_NOTICE)
  const [keyword, setKeyword] = useState('')
  const [debouncedKeyword, setDebouncedKeyword] = useState('')
  const [level, setLevel] = useState('')
  const [status, setStatus] = useState('')
  const [clearOpen, setClearOpen] = useState(false)
  const [message, setMessage] = useState('')

  useEffect(() => {
    const t = setTimeout(() => {
      setDebouncedKeyword(keyword)
      setPage(1)
    }, 300)
    return () => clearTimeout(t)
  }, [keyword])

  const { data, isLoading, refetch, isFetching } = useAppLogs({
    page,
    page_size: 20,
    category,
    keyword: debouncedKeyword || undefined,
    level: level || undefined,
    status: status || undefined,
  })

  const items = Array.isArray(data?.data) ? data.data : []
  const total = data?.total || 0
  const totalPages = Math.max(1, Math.ceil(total / 20))

  async function clearLogs() {
    try {
      await api.appLogs.clear(category)
      setClearOpen(false)
      setMessage('已清空当前分类日志')
      toast.success('已清空当前分类日志')
      refetch()
    } catch (e: any) {
      setMessage(e?.message || '清空失败')
      toast.error(e?.message || '清空失败')
    }
  }

  async function markRead(id: string) {
    try {
      await api.appLogs.markAsRead({ id })
      refetch()
    } catch {
      // ignore
    }
  }

  return (
    <div>
      <PageHeader
        title="运行日志"
        description="系统通知、推送、登录与调度日志"
        actions={
          <>
            <Button variant="secondary" onClick={() => refetch()} disabled={isFetching}>
              <RefreshCw size={14} className={isFetching ? 'animate-spin' : ''} />
              刷新
            </Button>
            {category !== LOG_CATEGORY.LOGIN_LOG ? (
              <Button variant="danger" onClick={() => setClearOpen(true)}>
                <Trash2 size={14} />
                清空
              </Button>
            ) : null}
          </>
        }
      />

      {message ? (
        <div className="mb-3 rounded-md border border-[var(--border)] bg-[var(--bg-tertiary)] px-3 py-2 text-sm">{message}</div>
      ) : null}

      <div className="mb-4 flex flex-wrap items-center gap-2">
        <Tabs
          value={category}
          onValueChange={(v) => {
            setCategory(v)
            setPage(1)
            setLevel('')
            setStatus('')
          }}
          items={TABS}
        />
        <div className="relative min-w-[180px] flex-1 max-w-xs">
          <Search size={14} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-muted)]" />
          <Input
            className="pl-9"
            placeholder={category === LOG_CATEGORY.LOGIN_LOG ? '搜索用户名' : '关键词'}
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
          />
        </div>
        {category === LOG_CATEGORY.SYSTEM_NOTICE || category === LOG_CATEGORY.SCHEDULER_LOG ? (
          <Select value={level} onChange={(e) => { setLevel(e.target.value); setPage(1) }}>
            <option value="">全部级别</option>
            <option value="info">info</option>
            <option value="warning">warning</option>
            <option value="error">error</option>
          </Select>
        ) : null}
        {category === LOG_CATEGORY.PUSH_LOG ? (
          <Select value={status} onChange={(e) => { setStatus(e.target.value); setPage(1) }}>
            <option value="">全部状态</option>
            <option value="success">success</option>
            <option value="failed">failed</option>
          </Select>
        ) : null}
      </div>

      <Card className="overflow-hidden">
        {isLoading ? (
          <div className="p-6 text-[var(--text-muted)]">加载中...</div>
        ) : items.length === 0 ? (
          <div className="p-6 text-[var(--text-muted)]">暂无日志</div>
        ) : (
          <div className="divide-y divide-[var(--border)]">
            {items.map((log) => (
              <div key={log.id} className="p-4" onClick={() => markRead(log.id)}>
                <div className="flex flex-wrap items-center gap-2">
                  <span className="font-medium">{log.title || log.category}</span>
                  <span className="rounded bg-[var(--bg-tertiary)] px-1.5 py-0.5 text-xs text-[var(--text-muted)]">{log.level || log.status}</span>
                  {log.channel_name ? (
                    <span className="rounded bg-[var(--bg-tertiary)] px-1.5 py-0.5 text-xs text-[var(--text-muted)]">{log.channel_name}</span>
                  ) : null}
                  <span className="text-xs text-[var(--text-muted)]">{formatDateTime(log.created_at)}</span>
                </div>
                <div className="mt-2 whitespace-pre-wrap text-sm text-[var(--text-secondary)]">
                  {log.content || log.error_msg || '-'}
                </div>
              </div>
            ))}
          </div>
        )}
        <div className="flex items-center justify-between border-t border-[var(--border)] px-4 py-3">
          <span className="text-sm text-[var(--text-muted)]">
            共 {total} 条 · 第 {page}/{totalPages} 页
          </span>
          <div className="flex gap-2">
            <Button variant="secondary" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
              上一页
            </Button>
            <Button variant="secondary" size="sm" disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>
              下一页
            </Button>
          </div>
        </div>
      </Card>

      <Modal
        open={clearOpen}
        title="清空日志"
        onClose={() => setClearOpen(false)}
        footer={
          <>
            <Button variant="secondary" onClick={() => setClearOpen(false)}>
              取消
            </Button>
            <Button variant="danger" onClick={clearLogs}>
              确认清空
            </Button>
          </>
        }
      >
        <p className="text-sm">确认清空当前分类的全部日志？此操作不可恢复。</p>
      </Modal>
    </div>
  )
}
