import { RefreshCcw } from 'lucide-react'
import { startTransition, useCallback, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { adminApi, ApiError } from '@/lib/api'
import type { AuditLogRecord } from '@/lib/types'

export function AuditPage() {
  const [logs, setLogs] = useState<AuditLogRecord[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [keyword, setKeyword] = useState('')

  const loadLogs = useCallback(async (showToast = false) => {
    try {
      if (showToast) {
        setRefreshing(true)
      }
      const next = await adminApi.listAuditLogs({ limit: 120 })
      startTransition(() => {
        setLogs(next)
      })
      if (showToast) {
        toast.success('审计日志已刷新。')
      }
    } catch (error) {
      if (error instanceof ApiError && error.status === 401) {
        return
      }
      toast.error(error instanceof ApiError ? error.message : '无法加载审计日志。')
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }, [])

  useEffect(() => {
    void loadLogs(false)
  }, [loadLogs])

  const filteredLogs = useMemo(() => {
    const normalized = keyword.trim().toLowerCase()
    if (!normalized) {
      return logs
    }

    return logs.filter((log) =>
      [
        log.action,
        log.target_type,
        log.target_id ?? '',
        log.target_label ?? '',
        log.actor_username ?? '',
        log.actor_email ?? '',
      ]
        .join(' ')
        .toLowerCase()
        .includes(normalized),
    )
  }, [keyword, logs])

  if (loading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-32 rounded-3xl" />
        <Skeleton className="h-[520px] rounded-3xl" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between">
        <div className="space-y-3">
          <Badge variant="secondary">操作审计</Badge>
          <div>
            <h2 className="text-3xl font-semibold tracking-tight">后台操作审计日志</h2>
            <p className="mt-2 max-w-3xl text-sm leading-7 text-muted-foreground">
              登录、发布、回滚、订阅推送等关键后台动作都会在这里留下记录，方便排查误操作与安全事件。
            </p>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <Input
            value={keyword}
            onChange={(event) => setKeyword(event.target.value)}
            placeholder="按动作 / 对象 / 操作者过滤"
            className="w-[280px]"
          />
          <Button variant="secondary" onClick={() => void loadLogs(true)} disabled={refreshing}>
            <RefreshCcw className="h-4 w-4" />
            {refreshing ? '刷新中...' : '刷新'}
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-start justify-between gap-4">
          <div>
            <CardTitle>最近操作</CardTitle>
            <CardDescription>默认展示最近 120 条关键后台动作。</CardDescription>
          </div>
          <Badge variant="outline">{filteredLogs.length} 条</Badge>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>时间</TableHead>
                <TableHead>动作</TableHead>
                <TableHead>对象</TableHead>
                <TableHead>操作者</TableHead>
                <TableHead>补充信息</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredLogs.map((log) => (
                <TableRow key={log.id}>
                  <TableCell className="text-muted-foreground">{log.created_at}</TableCell>
                  <TableCell>
                    <Badge variant="secondary">{log.action}</Badge>
                  </TableCell>
                  <TableCell>
                    <div className="space-y-1">
                      <div className="font-medium">{log.target_type}</div>
                      <div className="font-mono text-xs text-muted-foreground">
                        {log.target_label ?? log.target_id ?? '—'}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="space-y-1 text-sm">
                      <div>{log.actor_username ?? 'system'}</div>
                      <div className="text-xs text-muted-foreground">
                        {log.actor_email ?? log.actor_source ?? '未记录'}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className="max-w-[320px] text-sm text-muted-foreground">
                    <pre className="whitespace-pre-wrap break-words font-mono text-[11px] leading-5">
                      {log.metadata ? JSON.stringify(log.metadata, null, 2) : '—'}
                    </pre>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  )
}
