"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Badge } from "@/components/ui/badge"
import { History, Trash2, RefreshCw, User, FileText, Image, Settings } from "lucide-react"
import { getActivityLogs, cleanOldLogs, getActivityStats } from "@/lib/activity-logger"
import type { ActivityLog } from "@/lib/db"
import { format } from "date-fns"

const actionLabels = {
  create: "创建",
  update: "更新",
  delete: "删除",
  import: "导入",
  export: "导出",
}

const actionColors = {
  create: "bg-green-500",
  update: "bg-blue-500",
  delete: "bg-red-500",
  import: "bg-purple-500",
  export: "bg-orange-500",
}

const entityTypeLabels = {
  member: "成员",
  photo: "照片",
  story: "故事",
  settings: "设置",
}

const entityTypeIcons = {
  member: User,
  photo: Image,
  story: FileText,
  settings: Settings,
}

export function ActivityLogViewer() {
  const [logs, setLogs] = useState<ActivityLog[]>([])
  const [stats, setStats] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const loadLogs = async () => {
    setLoading(true)
    setError(null)
    try {
      const [activityLogs, activityStats] = await Promise.all([
        getActivityLogs(100),
        getActivityStats()
      ])
      setLogs(activityLogs)
      setStats(activityStats)
    } catch (err) {
      console.error("加载日志失败:", err)
      setError(err instanceof Error ? err.message : "加载失败")
    } finally {
      setLoading(false)
    }
  }

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

  const handleCleanOldLogs = async () => {
    if (confirm("确定要清除90天前的日志吗？")) {
      const count = await cleanOldLogs(90)
      alert(`已清除 ${count} 条旧日志`)
      loadLogs()
    }
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <History className="h-5 w-5" />
            操作日志
          </CardTitle>
          <CardDescription>
            查看所有修谱操作记录
          </CardDescription>
        </CardHeader>
        <CardContent>
          {stats && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
              <div className="bg-muted p-4 rounded-lg">
                <p className="text-sm text-muted-foreground">总记录数</p>
                <p className="text-2xl font-bold">{stats.total}</p>
              </div>
              <div className="bg-muted p-4 rounded-lg">
                <p className="text-sm text-muted-foreground">24小时内</p>
                <p className="text-2xl font-bold">{stats.recentCount}</p>
              </div>
              <div className="bg-muted p-4 rounded-lg">
                <p className="text-sm text-muted-foreground">创建操作</p>
                <p className="text-2xl font-bold">{stats.byAction.create || 0}</p>
              </div>
              <div className="bg-muted p-4 rounded-lg">
                <p className="text-sm text-muted-foreground">更新操作</p>
                <p className="text-2xl font-bold">{stats.byAction.update || 0}</p>
              </div>
            </div>
          )}

          <div className="flex gap-2 mb-4">
            <Button
              variant="outline"
              size="sm"
              onClick={loadLogs}
            >
              <RefreshCw className="mr-2 h-4 w-4" />
              刷新
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handleCleanOldLogs}
            >
              <Trash2 className="mr-2 h-4 w-4" />
              清除旧日志
            </Button>
          </div>

          <ScrollArea className="h-[400px] pr-4">
            {error ? (
              <div className="text-center py-8 text-destructive">
                加载失败: {error}
              </div>
            ) : loading ? (
              <div className="text-center py-8 text-muted-foreground">
                加载中...
              </div>
            ) : logs.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                暂无操作记录
              </div>
            ) : (
              <div className="space-y-3">
                {logs.map((log) => {
                  const EntityIcon = entityTypeIcons[log.entityType]
                  return (
                    <div
                      key={log.id}
                      className="flex items-start gap-3 p-3 bg-muted/50 rounded-lg hover:bg-muted transition-colors"
                    >
                      <div className={`p-2 rounded-full ${actionColors[log.action]} bg-opacity-10`}>
                        <EntityIcon className={`h-4 w-4 ${actionColors[log.action].replace('bg-', 'text-')}`} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <Badge variant="outline" className="text-xs">
                            {actionLabels[log.action]}
                          </Badge>
                          <Badge variant="secondary" className="text-xs">
                            {entityTypeLabels[log.entityType]}
                          </Badge>
                          {log.entityName && (
                            <span className="text-sm font-medium truncate">
                              {log.entityName}
                            </span>
                          )}
                        </div>
                        <div className="flex items-center justify-between">
                          <p className="text-xs text-muted-foreground">
                            {log.userName || "系统"}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            {format(new Date(log.timestamp), "yyyy-MM-dd HH:mm:ss")}
                          </p>
                        </div>
                        {log.changes && Object.keys(log.changes).length > 0 && (
                          <details className="mt-2">
                            <summary className="text-xs text-muted-foreground cursor-pointer hover:text-foreground">
                              查看变更详情
                            </summary>
                            <pre className="text-xs mt-1 p-2 bg-background rounded overflow-x-auto">
                              {JSON.stringify(log.changes, null, 2)}
                            </pre>
                          </details>
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </ScrollArea>
        </CardContent>
      </Card>
    </div>
  )
}
